diff --git a/src/main/native-chat/orchestration-agent-reference-delivery.test.ts b/src/main/native-chat/orchestration-agent-reference-delivery.test.ts new file mode 100644 index 000000000000..ba23f0d23b90 --- /dev/null +++ b/src/main/native-chat/orchestration-agent-reference-delivery.test.ts @@ -0,0 +1,26 @@ +import { expect, it, vi } from 'vitest' +import { claudeDispatchMessageContent } from '../claude/structured/claude-structured-dispatch-content' +import { turnInputFor } from '../codex/codex-structured-message-options' +import type { CodexTurnHost } from '../codex/codex-structured-turn-start' +import { createCodexDispatchEchoes } from '../codex/codex-structured-dispatch-echo' +import { preparePiRpcPrompt } from '../pi/rpc-prompt' +import { structuredAgentSessionSendBody } from '../../shared/agent-session/requests/structured-agent-session-send-mutation' +import { agentReferenceDeliveryText } from '../../shared/orchestration-agent-reference.test-fixture' + +it('preserves the renderer-captured occurrence and address association through actual provider adapters', async () => { + const body = structuredAgentSessionSendBody(agentReferenceDeliveryText, []) + const codexHost: CodexTurnHost = { + connection: { request: vi.fn() }, + threadId: 'captured-thread', + options: new Map(), + dispatchEchoes: createCodexDispatchEchoes(), + turnOpenWaits: { wait: vi.fn() } + } + expect(await claudeDispatchMessageContent(body)).toEqual([ + { type: 'text', text: agentReferenceDeliveryText } + ]) + expect(turnInputFor(codexHost, body)).toEqual([ + { type: 'text', text: agentReferenceDeliveryText } + ]) + expect((await preparePiRpcPrompt(body)).message).toBe(agentReferenceDeliveryText) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.reader-navigation.spec.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.reader-navigation.spec.tsx index c857d56439e9..3a4a5dc0b18e 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.reader-navigation.spec.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.reader-navigation.spec.tsx @@ -365,6 +365,7 @@ describe('reader navigation', () => { const composer = { focus, insertTypedText, + insertAgentReferences: () => false, acceptsText: () => true, appendText: vi.fn(), handlePasteEvent: vi.fn(), diff --git a/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx b/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx index 62e8044f3aa7..3f96ea7edc1e 100644 --- a/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx +++ b/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx @@ -1,3 +1,4 @@ +import { insertAgentReferences, NativeChatAgentReference } from './native-chat-agent-reference' import { nativeChatDraftPositions } from './native-chat-composer-draft-memory' import { createNativeChatPastedTextHistory } from './native-chat-pasted-text-history' import { resolveNativeChatPastedText } from './native-chat-composer-pasted-text-references' @@ -97,6 +98,7 @@ function NativePromptEditor({ underline: false, trailingNode: false }), + NativeChatAgentReference, NativeChatSkill, NativeChatFileReference, NativeChatImageReference, @@ -234,14 +236,13 @@ function NativePromptEditor({ return subscribeToNativeChatComposerDraft(scopeKey, capture) }, [editor, scopeKey, historyPaths]) - useLayoutEffect(() => { - editor?.setEditable(!disabled, false) - }, [disabled, editor]) + useLayoutEffect(() => editor?.setEditable(!disabled, false), [disabled, editor]) const input = useMemo( () => editor ? { + insertAgentReferences: (references) => insertAgentReferences(editor, references), insertText: (text) => { const content = editor.schema.nodeFromJSON(promptTextContent(text)) editor.view.dispatch( diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx index b7dc7e6df0d8..b67e4abb6d9a 100644 --- a/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx @@ -49,6 +49,7 @@ vi.mock('./NativeChatComposer', async () => { fieldRef.current?.focus() return true }, + insertAgentReferences: () => false, insertTypedText: composer.typed, acceptsText: () => true, appendText: () => {}, diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx index e41efb5f4116..c35d234ebfe4 100644 --- a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx @@ -205,6 +205,7 @@ export function NativeChatResolvedView({ }) const { card: shownPromptCard, collapsedCard } = promptCardPresentation const mountedPromptCard = shownPromptCard ?? collapsedCard + const composerReady = shownPromptCard === null && targetPtyId !== null && canSend const rootInput = useNativeChatRootInputRouting({ tabId: terminalTabId, rootRef, @@ -212,7 +213,7 @@ export function NativeChatResolvedView({ questionAnswerInputRef, isVisible, isFocusedGroup, - composerReady: shownPromptCard === null && targetPtyId !== null && canSend + composerReady }) // Match mobile ordering: hook preview before optimistic user echoes. @@ -343,7 +344,12 @@ export function NativeChatResolvedView({ data-native-chat-scheme={appearanceStyle.colorScheme} > } + panel={ + + } > {find.isOpen ? : null} {viewState.kind === 'loading' ? ( diff --git a/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx b/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx index d9693d222868..2f90e4c81ad8 100644 --- a/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx @@ -19,6 +19,7 @@ const appendText = vi.fn<(text: string) => void>() const acceptsText = vi.fn(() => true) const composer: NativeChatComposerHandle = { focus: () => true, + insertAgentReferences: () => false, insertTypedText: () => true, appendText, acceptsText, diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx index 50cfc54755b5..65851b4ede51 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx @@ -192,7 +192,7 @@ it('ends only the native menu lifetime on hide, retaining disclosure and the sub const view = render(content(true)) await user.click(screen.getByRole('button', { name: /^Show orchestration: 1 worker,/ })) const panel = screen.getByRole('complementary', { name: 'Orchestration' }) - const disclosure = screen.getByRole('button', { name: /Check the result/ }) + const disclosure = screen.getByRole('button', { name: "Show Worker's task and latest message" }) await user.click(disclosure) const composer = screen.getByRole('textbox', { name: 'Message' }) await user.type(composer, 'Keep this draft') diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index 8e868cab46f0..188a12849d12 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -184,6 +184,7 @@ export function NativeChatStructuredSession( // An owned prompt keeps its card; otherwise a missing program leaves the composer disabled. const installLayout = viewState.kind === 'empty' ? 'hero' : 'strip' const install = useNativeChatInstallSlot(props, agentLabel, installLayout) + const canMention = composerShown && install.unavailableHint === undefined const approval = prompt?.body.kind === 'approval' ? chatApprovalFromJournal(prompt.body) : null const cancelPrompt = () => cancelStructuredPrompt(controller, prompt, props.agent) const rootInput = useNativeChatRootInputRouting({ @@ -221,9 +222,6 @@ export function NativeChatStructuredSession( transport }) - // Said once: on the pane when the failure took it, else in the composer's notices. - const sessionError = - viewState.kind === 'error' || !readFailure ? controller.error : readFailure.text const launch = { ...provisionalLaunch, retry: submits.retryLaunch } const availability = useNativeChatAvailabilityNotice({ unavailable: controller.unavailable, @@ -244,7 +242,8 @@ export function NativeChatStructuredSession( const notices = structuredSessionNotices({ launch: install.slot.kind === 'install' ? { ...launch, lifecycle: null } : launch, agentLabel, - sessionError, + // Said once: on the pane when the failure took it, else in the composer's notices. + sessionError: viewState.kind === 'error' || !readFailure ? controller.error : readFailure.text, composerError: composerError ?? continuation.continueError, claudeSignIn, availability, @@ -277,7 +276,9 @@ export function NativeChatStructuredSession( data-native-chat-scheme={appearanceStyle.colorScheme} > {nativeChatPaneHeader(props, ownerWorktreeId, appearanceStyle.colorScheme, handOff)} - }> + } + > {find.isOpen ? : null} {viewState.kind === 'loading' || (viewState.kind === 'error' && !readFailure) ? ( diff --git a/src/renderer/src/components/native-chat/inline-composer-scaling.test.tsx b/src/renderer/src/components/native-chat/inline-composer-scaling.test.tsx index 5305666084b5..e2075b16f245 100644 --- a/src/renderer/src/components/native-chat/inline-composer-scaling.test.tsx +++ b/src/renderer/src/components/native-chat/inline-composer-scaling.test.tsx @@ -176,6 +176,7 @@ it.each([20, 200])( const handle: NativeChatComposerHandle = { focus: () => true, insertTypedText: () => true, + insertAgentReferences: () => false, acceptsText: () => true, appendText: () => {}, handlePasteEvent: () => {}, @@ -270,6 +271,7 @@ it.each([20, 200])( const handle: NativeChatComposerHandle = { focus: () => true, insertTypedText: inserted, + insertAgentReferences: () => false, acceptsText: () => true, appendText: () => {}, handlePasteEvent: () => {}, diff --git a/src/renderer/src/components/native-chat/inline-deferred-input.test.tsx b/src/renderer/src/components/native-chat/inline-deferred-input.test.tsx index 4b841d411ed0..e241538d4cb2 100644 --- a/src/renderer/src/components/native-chat/inline-deferred-input.test.tsx +++ b/src/renderer/src/components/native-chat/inline-deferred-input.test.tsx @@ -24,6 +24,7 @@ import { updateNativeChatComposerDraft } from './native-chat-composer-draft-store' import { promptSkillRefs, promptText } from './native-chat-prompt-document' +import { agentReferenceToken } from '../../../../shared/orchestration-agent-reference' import { changePrompt, promptEditor } from './native-chat-prompt-editor.test-support' import { dispatchNativeChatStructuredComposerText } from './native-chat-structured-composer-dispatch' import { structuredAgentSessionSendBody } from '../../../../shared/agent-session/requests/structured-agent-session-send-mutation' @@ -38,7 +39,16 @@ import { nativeChatPastedTextOperations } from './native-chat-pasted-text-refere const clipboard = vi.hoisted(() => ({ text: vi.fn(), file: vi.fn() })) vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) const handles = new Map() -function Field({ scope, disabled = false }: { scope: string; disabled?: boolean }) { +const notComposing = () => false +function Field({ + scope, + disabled = false, + isComposing = notComposing +}: { + scope: string + disabled?: boolean + isComposing?: () => boolean +}) { const input = useRef(null) const handle = useRef(null) const root = useRef(null) @@ -50,7 +60,7 @@ function Field({ scope, disabled = false }: { scope: string; disabled?: boolean }, [draft.draft]) useNativeChatComposerHandle(handle, { textareaRef: input, - isComposing: () => false, + isComposing, setDraft: draft.setDraft, setCaret: () => {}, setActiveSuggestion: () => {}, @@ -285,3 +295,37 @@ it.each(['/clear', '@/same.txt'] as const)( expect(promptText(editor.state.doc)).toBe(`${before}@/same.txt`) } ) + +it('lets the mounted input own mention acceptance and restores that editor focus only after insertion', () => { + let composing = false + const isComposing = () => composing + const reference = { label: 'Worker', address: 'term_worker', hostKey: 'local' } + const fields = (disabled: boolean) => ( + <> + + + + ) + const view = render(fields(true)) + const input = screen.getByRole('textbox', { name: 'mention-owner' }) + const other = screen.getByRole('textbox', { name: 'other-owner' }) + other.focus() + const handle = handles.get('mention-owner')! + expect(handle.acceptsText()).toBe(false) + act(() => expect(handle.insertAgentReferences([reference])).toBe(false)) + expect(readNativeChatComposerDraft('mention-owner').text).toBe('') + expect(document.activeElement).toBe(other) + view.rerender(fields(false)) + composing = true + expect(handle.acceptsText()).toBe(true) + act(() => expect(handle.insertAgentReferences([reference])).toBe(false)) + expect(readNativeChatComposerDraft('mention-owner').text).toBe('') + expect(document.activeElement).toBe(other) + composing = false + act(() => expect(handle.insertAgentReferences([reference])).toBe(true)) + expect(readNativeChatComposerDraft('mention-owner').text).toBe( + `${agentReferenceToken(reference)} ` + ) + expect(document.activeElement).toBe(input) + expect(readNativeChatComposerDraft('other-owner').text).toBe('') +}) diff --git a/src/renderer/src/components/native-chat/inline-rich-draft-consumers.test.tsx b/src/renderer/src/components/native-chat/inline-rich-draft-consumers.test.tsx index 1a220f7f6513..d8d168ef43bf 100644 --- a/src/renderer/src/components/native-chat/inline-rich-draft-consumers.test.tsx +++ b/src/renderer/src/components/native-chat/inline-rich-draft-consumers.test.tsx @@ -1,5 +1,5 @@ // @vitest-environment happy-dom -import { useLayoutEffect, useRef, useState, useImperativeHandle } from 'react' +import { useLayoutEffect, useRef, useState } from 'react' import { act, cleanup, render, screen, waitFor } from '@testing-library/react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { NativeChatPromptEditor } from './NativeChatPromptEditor' @@ -460,7 +460,7 @@ it('retains re-picked rich identity after unknown proof and saves the whole repl expect(nextSend().blocks).toEqual([{ type: 'text', text: 'occupied' }]) }) -import { useNativeChatTypedInsertion } from './use-native-chat-typed-insertion' +import { useNativeChatComposerHandle } from './use-native-chat-composer-handle' import { useNativeChatComposerEditSession } from './use-native-chat-composer-edit-session' import type { NativeChatComposerHandle } from './native-chat-composer-types' import { captureInsertionTarget, insertText } from '../dictation/dictation-insertion-target' @@ -472,19 +472,26 @@ function useCapturedPrompt( ) { const root = useRef(null) const handle = useRef(null) - const insertion = useNativeChatTypedInsertion({ + useNativeChatComposerHandle(handle, { textareaRef: input, isComposing: () => composing, setDraft, setCaret: () => {}, - setActiveSuggestion: () => {} + setActiveSuggestion: () => {}, + attachmentScopeKey: key, + targetKey: key, + disabled: false, + caret: input.current?.selectionStart ?? 0, + resolveAttachmentOwner: () => ({ kind: 'local' }), + attachResolvedPaths: () => {}, + attachCopiedFiles: () => {}, + captureCopiedFiles: () => async () => {}, + beginPendingImageAttachment: () => null, + resolvePendingImageAttachment: () => {}, + dropPendingImageAttachment: () => {}, + setNotice: () => {}, + pastedTextEditor: () => input.current }) - useImperativeHandle(handle, () => ({ - ...insertion, - isComposing: () => composing, - handlePasteEvent: () => {}, - pasteFromClipboard: () => {} - })) useNativeChatComposerEditSession({ root, handle, diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference-send.test.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.test.tsx new file mode 100644 index 000000000000..25fcaffa867a --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.test.tsx @@ -0,0 +1,174 @@ +// @vitest-environment happy-dom +import type { JSONContent } from '@tiptap/react' +import type * as PastedTextProjection from './native-chat-composer-pasted-text-references' +import { expect, it, vi } from 'vitest' +import { + agentReferenceToken, + type OrchestrationAgentReference +} from '../../../../shared/orchestration-agent-reference' +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' +import { nativeChatPastedTextToken } from './native-chat-pasted-text-reference' +import { formatNativeChatFileReference } from '../../../../shared/agent-image-paste' + +const work = vi.hoisted(() => ({ plainCharacters: 0, opaqueVisits: 0 })) +vi.mock('./native-chat-composer-pasted-text-references', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + projectNativeChatPastedText: ( + ...args: Parameters + ) => { + work.plainCharacters += args[0].length + return actual.projectNativeChatPastedText(...args) + }, + projectNativeChatPastedTextParts: ( + ...args: Parameters + ) => { + for (const part of args[0]) { + if (typeof part === 'string') { + work.plainCharacters += part.length + } else { + work.opaqueVisits++ + } + } + return actual.projectNativeChatPastedTextParts(...args) + } + } +}) + +const alpha = { label: 'Worker', address: 'term_alpha', hostKey: 'local' } +const beta = { ...alpha, address: 'term_beta' } +function submission(parts: (string | OrchestrationAgentReference)[]) { + const text = parts + .map((part) => (typeof part === 'string' ? part : agentReferenceToken(part))) + .join('') + const document: JSONContent = { + type: 'doc', + content: [ + { + type: 'paragraph', + content: parts.map((part) => + typeof part === 'string' + ? { type: 'text', text: part } + : { type: 'nativeChatAgentReference', attrs: part } + ) + } + ] + } + return { text, document } +} +const line = (label: string, address: string) => + `[Orca agent "${label}": ${address} — message it with orca orchestration send --to ${address}]` +function send(parts: (string | OrchestrationAgentReference)[]) { + const { text, document } = submission(parts) + return serializeNativeChatAgentReferences(text, document) +} + +it('preserves occurrence identity for repeated collisions and stored-label variants without changing ordinary bytes', () => { + const a = send([alpha, ' tests; ', beta, ' docs; ', alpha, ' tests; ', beta, ' docs']) + const b = send([alpha, ' tests; ', beta, ' docs; ', beta, ' tests; ', alpha, ' docs']) + expect(a).not.toBe(b) + expect(a).toBe( + `@Worker (1) tests; @Worker (2) docs; @Worker (1) tests; @Worker (2) docs\n\n${line('Worker (1)', alpha.address)}\n${line('Worker (2)', beta.address)}` + ) + const old = { ...alpha, label: 'Old' }, + other = { ...beta, label: 'Other' } + expect(send([old, ' ', other, ' ', alpha, ' tests ', old, ' ', other])).not.toBe( + send([old, ' ', other, ' ', { ...beta, label: 'Worker' }, ' tests ', old, ' ', other]) + ) + expect(send([old, ' ', alpha, ' ', old])).toBe( + `@Old (1) @Old (1) @Old (1)\n\n${line('Old (1)', alpha.address)}` + ) + expect(send(['Ask ', alpha, ' then ', alpha])).toBe( + `Ask @Worker then @Worker\n\n${line('Worker', alpha.address)}` + ) + const raw = submission(['ordinary @Worker ', alpha]) + const before = structuredClone(raw) + serializeNativeChatAgentReferences(raw.text, raw.document) + expect(raw).toEqual(before) + expect(serializeNativeChatAgentReferences(`${raw.text} changed`, raw.document)).toBe( + `${raw.text} changed` + ) + expect(serializeNativeChatAgentReferences(raw.text)).toBe(raw.text) +}) + +it('reserves globally against real labels, authored suffixes and the completed file projection, preserving host tuple dedupe', () => { + const id = '11111111-1111-4111-8111-111111111111' + const token = nativeChatPastedTextToken(id) + const path = '/tmp/Worker (3).txt' + const raw = submission([ + alpha, + ' ', + beta, + ' ', + { ...alpha, address: 'term_real', label: 'Worker (1)' }, + ' authored (2) ', + token, + ' ', + { ...alpha, hostKey: 'remote' } + ]) + const result = serializeNativeChatAgentReferences(raw.text, raw.document, { [id]: path }) + expect(result).toContain( + `@Worker (4) @Worker (5) @Worker (1) authored (2) ${formatNativeChatFileReference(path)} @Worker (6)` + ) + expect(result).toContain(line('Worker (4)', alpha.address)) + expect(result).toContain(line('Worker (6)', alpha.address)) + expect(result.match(/\[Orca agent/g)).toHaveLength(4) + const huge = '9'.repeat(400) + expect(send([alpha, ` (${huge}) `, beta, ' (1) (01)'])).toContain('@Worker (2)') + expect(send(['authored\0@', alpha, '\0', beta])).toContain('@Worker (1)\0@Worker (2)') + const ordinary = submission(['before', token, alpha, 'after']) + expect( + serializeNativeChatAgentReferences(ordinary.text, ordinary.document, { [id]: '/tmp/plain.txt' }) + ).toBe( + `before ${formatNativeChatFileReference('/tmp/plain.txt')} @Workerafter\n\n${line('Worker', alpha.address)}` + ) +}) + +it('frames only generated label data safely, including normalization collisions and empty control-only labels', () => { + const dangerous = { ...alpha, label: 'Zoë"\\]\r\n\u001b\u0085\u2028[' } + const safe = 'Zoë\\"\\\\\\] \\[' + expect(send(['literal [Orca agent "authored"] ', dangerous])).toBe( + `literal [Orca agent "authored"] @${safe}\n\n${line(safe, alpha.address)}` + ) + expect(send([{ ...alpha, label: '\u0000\u001b\u0085' }])).toBe( + `@Agent\n\n${line('Agent', alpha.address)}` + ) + expect(send([{ ...alpha, label: 'A\nB' }, ' ', { ...beta, label: 'A B' }])).toBe( + `@A B (1) @A B (2)\n\n${line('A B (1)', alpha.address)}\n${line('A B (2)', beta.address)}` + ) + expect(send(['ordinary @Worker ', { ...alpha, address: 'term_bad\n' }])).toBe( + 'ordinary @Worker @Worker (Orca agent term_bad\n)' + ) +}) + +it('bounds cumulative real projection work at N and 10N without multiplying authored NULs by selected occurrences', () => { + const results = [ + { nul: 100, atoms: 10, raw: 420, units: 273, bytes: 275 }, + { nul: 1000, atoms: 100, raw: 4200, units: 1893, bytes: 1895 } + ].map((size) => { + const parts: (string | OrchestrationAgentReference)[] = ['\0'.repeat(size.nul)] + for (let i = 0; i < size.atoms; i++) { + parts.push(alpha, ' ') + } + const input = submission(parts) + const before = structuredClone(input) + Object.assign(work, { plainCharacters: 0, opaqueVisits: 0 }) + const body = serializeNativeChatAgentReferences(input.text, input.document) + const observed = { ...size, ...work, total: work.plainCharacters + work.opaqueVisits } + return { ...observed, body, input, before } + }) + for (const result of results) { + expect(result.body).toBe( + `${'\0'.repeat(result.nul)}${'@Worker '.repeat(result.atoms)}\n\n[Orca agent "Worker": term_alpha — message it with orca orchestration send --to term_alpha]` + ) + expect(result.body.length).toBe(result.units) + expect(new TextEncoder().encode(result.body).length).toBe(result.bytes) + expect(result.input.text.length).toBe(result.raw) + expect(result.input).toEqual(result.before) + expect(result.total).toBeLessThanOrEqual(4 * result.raw) + expect(result.plainCharacters).toBeGreaterThan(0) + expect(result.opaqueVisits).toBe(result.atoms) + } + expect(results[1].total).toBeGreaterThan(results[0].total) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts new file mode 100644 index 000000000000..fca31a08f317 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts @@ -0,0 +1,154 @@ +import type { JSONContent } from '@tiptap/react' +import { imageReferenceToken } from '../../../../shared/native-chat/native-chat-image-reference' +import { + agentReferenceNote, + agentReferenceToken, + isPublicOrchestrationAddress, + mayHoldAgentReferences, + printableAgentLabel, + type OrchestrationAgentReference +} from '../../../../shared/orchestration-agent-reference' +import { + projectNativeChatPastedText, + projectNativeChatPastedTextParts +} from './native-chat-composer-pasted-text-references' + +type SelectedReference = { + reference: OrchestrationAgentReference + labels: Set + safeLabels: Set + label: string + affected: boolean +} + +function framedLabel(label: string): string { + return printableAgentLabel(label).replace(/[\\"[\]]/g, '\\$&') || 'Agent' +} + +/** Only a matching submitted document contributes targets; delivery owns the finished plain text. */ +export function serializeNativeChatAgentReferences( + text: string, + document?: JSONContent, + files: Readonly> = {}, + // A goal is one line, so a typed /goal still parses as one; a message puts each note on its own line. + layout: 'message' | 'goal' = 'message' +): string { + // Only a panel Mention prints a reference; any other draft keeps the ordinary send text. + if (!mayHoldAgentReferences(text)) { + return projectNativeChatPastedText(text, files) + } + const selected = new Map() + const occurrences: (SelectedReference | string)[] = [] + const render = (node: JSONContent): string => { + if (node.type === 'nativeChatAgentReference') { + const { label, address, hostKey } = node.attrs ?? {} + if (typeof label !== 'string' || typeof address !== 'string' || typeof hostKey !== 'string') { + return '' + } + const reference = { label, address, hostKey } + const literal = agentReferenceToken(reference) + if (isPublicOrchestrationAddress(address)) { + const key = JSON.stringify([hostKey, address]) + let target = selected.get(key) + if (!target) { + target = { + reference, + labels: new Set(), + safeLabels: new Set(), + label: framedLabel(label), + affected: false + } + selected.set(key, target) + } + target.labels.add(label) + target.safeLabels.add(framedLabel(label)) + occurrences.push(target) + } else { + occurrences.push(literal) + } + return literal + } + if (node.type === 'hardBreak') { + occurrences.push('\n') + return '\n' + } + if (node.type === 'doc' || node.content) { + return (node.content ?? []) + .map((child, index) => { + if (node.type === 'doc' && index > 0) { + occurrences.push('\n') + } + return render(child) + }) + .join(node.type === 'doc' ? '\n' : '') + } + const plain = + node.type === 'nativeChatImageReference' + ? imageReferenceToken(String(node.attrs?.attachmentId)) + : (node.text ?? (typeof node.attrs?.token === 'string' ? node.attrs.token : '')) + occurrences.push(plain) + return plain + } + if (!document || render(document) !== text || selected.size === 0) { + return projectNativeChatPastedText(text, files) + } + const owners = new Map>() + const forbidden = new Set() + const spellings = new Set() + const reserve = (value: string) => { + for (const match of value.matchAll(/\(([1-9][0-9]*)\)/g)) { + forbidden.add(match[1]) + } + } + for (const target of selected.values()) { + for (const label of target.labels) { + reserve(label) + } + for (const label of target.safeLabels) { + reserve(label) + spellings.add(label) + const keys = owners.get(label) ?? new Set() + keys.add(target) + owners.set(label, keys) + } + } + for (const target of selected.values()) { + target.affected = + target.labels.size > 1 || [...target.safeLabels].some((label) => owners.get(label)!.size > 1) + } + const projected = projectNativeChatPastedTextParts( + occurrences.map((part) => + typeof part === 'string' + ? part + : { opaque: part, tail: part.affected ? '' : (part.label.match(/\s+$/)?.[0] ?? '') } + ), + files + ) + for (const part of projected) { + if (typeof part === 'string') { + reserve(part) + } + } + let suffix = 0 + for (const target of selected.values()) { + if (!target.affected) { + continue + } + // At most forbidden.size + selected.size candidates: each skipped number was captured above. + do { + suffix++ + } while (forbidden.has(String(suffix)) || spellings.has(`${target.label} (${suffix})`)) + forbidden.add(String(suffix)) + target.label = `${target.label} (${suffix})` + spellings.add(target.label) + } + const body = projected + .map((part) => (typeof part === 'string' ? part : `@${part.opaque.label}`)) + .join('') + const notes = [...selected.values()].map(({ reference, label }) => + agentReferenceNote(label, reference.address) + ) + return layout === 'goal' + ? `${body.trimEnd()} ${notes.join(' ')}` + : `${body}\n\n${notes.join('\n')}` +} diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference.test-fixture.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference.test-fixture.tsx new file mode 100644 index 000000000000..33591235b0b0 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference.test-fixture.tsx @@ -0,0 +1,76 @@ +import { createRef, type RefObject } from 'react' +import { render, type RenderResult } from '@testing-library/react' +import type { OrchestrationCrewRow } from '../../../../shared/orchestration-crew' +import type { OrchestrationAgentReference } from '../../../../shared/orchestration-agent-reference' +import { NativeChatCrewPanel } from '../orchestration-crew/NativeChatCrewPanel' +import { TooltipProvider } from '../ui/tooltip' +import type { NativeChatComposerInput } from './native-chat-composer-input' +import type { NativeChatComposerHandle } from './native-chat-composer-types' +import { NativeChatPromptEditor } from './NativeChatPromptEditor' +import { useNativeChatComposerHandle } from './use-native-chat-composer-handle' + +export function mountedMention( + crewRows: OrchestrationCrewRow[], + first: OrchestrationAgentReference, + managed = false, + initialValue = 'Hello suffix' +): RenderResult & { + input: RefObject + handle: RefObject +} { + crewRows.push({ + partyKey: 'worker', + role: 'worker', + label: first.label, + agentKind: 'codex', + status: 'working', + sendAddress: first.address, + ...(managed ? { task: { title: 'Inspect', state: 'dispatched' as const } } : {}) + }) + const input = createRef() + const handle = createRef() + function Pane() { + useNativeChatComposerHandle(handle, { + textareaRef: input, + isComposing: () => false, + setDraft: () => {}, + setCaret: () => {}, + setActiveSuggestion: () => {}, + attachmentScopeKey: 'menu', + targetKey: 'menu', + disabled: false, + caret: 6, + resolveAttachmentOwner: () => ({ kind: 'local' }), + attachResolvedPaths: () => {}, + attachCopiedFiles: () => {}, + captureCopiedFiles: () => async () => {}, + beginPendingImageAttachment: () => null, + resolvePendingImageAttachment: () => {}, + dropPendingImageAttachment: () => {}, + setNotice: () => {}, + pastedTextEditor: () => input.current + }) + return ( + +
+ + {}} + onSelect={() => {}} + /> +
+
+ ) + } + return { ...render(), input, handle } +} diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx new file mode 100644 index 000000000000..dcc1333364a0 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx @@ -0,0 +1,490 @@ +// @vitest-environment happy-dom +import { agentReferenceDeliveryText } from '../../../../shared/orchestration-agent-reference.test-fixture' +import { dispatchStructuredAgentSessionComposerCommand } from '../../../../shared/agent-session/view/structured-agent-session-composer' +import { nativeChatPastedTextToken } from './native-chat-pasted-text-reference' +import { emptyCrew, type OrchestrationCrewRow } from '../../../../shared/orchestration-crew' +import { createRef } from 'react' +import { act, cleanup, render, renderHook, within, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' +import type { PaneManager } from '@/lib/pane-manager/pane-manager' +import type { PtyTransport } from '../terminal-pane/pty-transport-types' +import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types' +import type { NativeChatComposerInput } from './native-chat-composer-input' +import { NativeChatPromptEditor } from './NativeChatPromptEditor' +import { mountedMention } from './native-chat-agent-reference.test-fixture' +import { promptEditor } from './native-chat-prompt-editor.test-support' +import { agentReferenceToken } from '../../../../shared/orchestration-agent-reference' +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' +import { useNativeChatStructuredComposerSend } from './use-native-chat-structured-composer-send' +import { useNativeChatPtyComposerSend } from './use-native-chat-pty-composer-send' +import { useNativeChatComposerSubmit } from './use-native-chat-composer-submit' +import { sendNativeChatMessage } from './native-chat-runtime-send' +import { + clearNativeChatComposerDraftsForTests, + readNativeChatComposerDraft, + updateNativeChatComposerDraft +} from './native-chat-composer-draft-store' +import { captureTerminalDropTarget } from '../terminal-pane/terminal-drop-target' +import { insertTerminalCrewMention } from '../terminal-pane/terminal-crew-mention' +import { clearStructuredAgentSessionPendingSends } from './structured-agent-session-pending-sends' + +const crewRows = vi.hoisted(() => new Array()) +vi.mock('./use-orchestration-crew', () => ({ + useOrchestrationCrew: () => ({ + ...emptyCrew('ok'), + sections: { managedBy: [], managing: crewRows, talkingWith: [] } + }) +})) + +// Render the real panel synchronously; the lazy chunk boundary is the app's load detail. +vi.mock('../orchestration-crew/LazyOrchestrationCrewPanel', async () => ({ + LazyOrchestrationCrewPanel: (await import('../orchestration-crew/OrchestrationCrewPanel')) + .OrchestrationCrewPanel +})) +vi.mock('@/lib/open-agent-message-sender', () => ({ openOrchestrationCrewAgent: vi.fn() })) +vi.mock('./native-chat-runtime-send', () => ({ + sendNativeChatMessage: vi.fn(() => ({ cancel() {}, settleAfterMs: 0 })), + sendNativeChatTypedCommand: vi.fn(), + submitNativeChatPrompt: vi.fn() +})) +vi.mock('@/lib/native-chat-telemetry', () => ({ emitNativeChatMessageSent: vi.fn() })) +afterEach(() => { + cleanup() + crewRows.length = 0 + clearNativeChatComposerDraftsForTests() + clearStructuredAgentSessionPendingSends('test-session') + vi.restoreAllMocks() +}) +const first = { label: 'Same name', address: 'term_first', hostKey: 'local' } +const second = { ...first, address: 'dispatch:ctx_second' } +function editor(scope: string, text = 'Hello ') { + const ref = createRef() + const view = render( + + ) + return { + ...view, + input: ref.current!, + editor: promptEditor(within(view.container).getByRole('textbox')) + } +} +function transport(): NativeChatStructuredComposerTransport { + return { + capturePresentation: () => () => true, + send: vi.fn(() => 'queued'), + dispatchCommand: vi.fn(async () => ({ + handled: false, + accepted: false, + error: null + })), + optionsSurface: { + getSnapshot: () => [], + setOption: vi.fn(), + invokeAction: vi.fn(), + subscribe: () => () => {} + }, + optionSnapshot: [], + onError: vi.fn(), + runtime: 'local', + sessionId: 'test-session', + runtimeEnvironmentId: null + } +} + +it('keeps a split’s caret, duplicate-name identities, literal unsent copy and atomic undo', async () => { + const left = editor('left') + const right = editor('right', 'Other draft') + await act(async () => { + left.input.setSelectionRange(6, 6) + right.input.focus() + left.input.insertAgentReferences!([first, second]) + }) + const stored = `Hello ${agentReferenceToken(first)} ${agentReferenceToken(second)} ` + expect(left.input.value).toBe(stored) + expect(right.input.value).toBe('Other draft') + expect(left.container.querySelectorAll('[data-native-chat-agent-reference]')).toHaveLength(2) + const doc = readNativeChatComposerDraft('left').document + expect(serializeNativeChatAgentReferences(stored, doc)).toBe( + 'Hello @Same name (1) @Same name (2) \n\n[Orca agent "Same name (1)": term_first — message it with orca orchestration send --to term_first]\n[Orca agent "Same name (2)": dispatch:ctx_second — message it with orca orchestration send --to dispatch:ctx_second]' + ) + expect(left.editor.getText()).toBe(stored) + expect(serializeNativeChatAgentReferences('/model', doc)).toBe('/model') + await act(async () => { + left.input.setSelectionRange(6, 6 + agentReferenceToken(first).length) + left.editor.commands.deleteSelection() + }) + expect(left.container.querySelectorAll('[data-native-chat-agent-reference]')).toHaveLength(1) + await act(async () => { + left.editor.commands.undo() + }) + expect(left.input.value).toBe(stored) + await act(async () => { + left.input.value = 'Old plain @Same name draft' + }) + expect(left.container.querySelectorAll('[data-native-chat-agent-reference]')).toHaveLength(0) + expect( + serializeNativeChatAgentReferences( + left.input.value, + readNativeChatComposerDraft('left').document + ) + ).toBe('Old plain @Same name draft') +}) + +it('serializes the captured draft before structured and PTY sends', async () => { + const pane = editor('send') + act(() => { + pane.input.setSelectionRange(6, 6) + pane.input.insertAgentReferences!([first, first, second]) + }) + const fileId = '22222222-2222-4222-8222-222222222222' + act(() => pane.editor.commands.insertContent(` ${nativeChatPastedTextToken(fileId)}`)) + updateNativeChatComposerDraft( + 'send', + { pastedTextFiles: { [fileId]: '/tmp/Same name (1).txt' } }, + 'immediate' + ) + const snapshot = readNativeChatComposerDraft('send') + const wire = serializeNativeChatAgentReferences( + snapshot.text, + snapshot.document, + snapshot.pastedTextFiles + ) + const structured = transport() + const structuredHook = renderHook(() => + useNativeChatStructuredComposerSend({ + agent: 'claude', + draftScopeKey: 'send', + imageAttachments: [], + structuredTransport: structured, + isComposing: () => false, + clearSkillOrigin: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + await act(async () => { + await structuredHook.result.current(snapshot.text) + }) + expect(wire).toBe(agentReferenceDeliveryText) + expect(structured.send).toHaveBeenCalledWith(wire, []) + expect(wire.match(/\[Orca agent/g)).toHaveLength(2) + updateNativeChatComposerDraft('send', snapshot, 'immediate') + const optimistic = vi.fn() + const ptyHook = renderHook(() => + useNativeChatPtyComposerSend({ + agent: 'codex', + draftScopeKey: 'send', + draft: snapshot.text, + imageAttachments: [], + disabled: false, + isDispatchingSessionOption: false, + launchDraftResolved: true, + resolveTarget: () => ({ ptyId: 'pty-left', settings: null }), + classifySend: () => 'chat', + sessionOptionsSurface: null, + terminalTabId: 'tab-left', + trackPendingSend: vi.fn(), + onOptimisticSend: optimistic, + setDraft: vi.fn(), + setCaret: vi.fn(), + clearSkillOrigin: vi.fn(), + clearImageAttachments: vi.fn(), + setNotice: vi.fn() + }) + ) + act(() => ptyHook.result.current()) + expect(vi.mocked(sendNativeChatMessage).mock.calls.at(-1)?.slice(0, 2)).toEqual([ + 'pty-left', + wire + ]) + expect(optimistic).toHaveBeenCalledExactlyOnceWith(wire, []) +}) + +it('writes only revalidated split bytes, sanitizing controls without Enter and surfacing rejected acceptance', async () => { + let leaf = 'leaf-left' + const sendInput = vi.fn(() => true) + const sendInputAccepted = vi.fn(async () => true) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: mention only reads pane id/leaf, never operates a terminal widget. + const manager = { getPanes: () => [{ id: 1, leafId: leaf }] } as PaneManager + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the existing drop validator and writer only consume these four transport methods. + const pty = { + getPtyId: () => 'pty-left', + isConnected: () => true, + sendInput, + sendInputAccepted + } as unknown as PtyTransport + const target = captureTerminalDropTarget({ id: 1, leafId: leaf }, pty) + const transports = new Map([[1, pty]]) + expect( + await insertTerminalCrewMention(manager, transports, target, [ + { ...first, label: 'Zoë\r\n\u001b[31m\u2028\u0085' } + ]) + ).toBe(true) + expect(sendInputAccepted).toHaveBeenCalledWith('Zoë [31m (Orca agent term_first) ', 'driving') + expect(sendInput).not.toHaveBeenCalled() + leaf = 'leaf-replaced' + expect(await insertTerminalCrewMention(manager, transports, target, [first])).toBe(false) + expect(sendInputAccepted).toHaveBeenCalledTimes(1) + leaf = 'leaf-left' + sendInputAccepted.mockResolvedValueOnce(false) + expect(await insertTerminalCrewMention(manager, transports, target, [first])).toBe(false) + expect(sendInputAccepted).toHaveBeenCalledTimes(2) + expect( + await insertTerminalCrewMention(manager, transports, target, [ + { ...first, address: 'term_bad\r' } + ]) + ).toBe(false) + expect(sendInputAccepted).toHaveBeenCalledTimes(2) +}) + +it('captures projected identity once for real typed-goal dispatch and Goal mode', async () => { + const id = '11111111-1111-4111-8111-111111111111' + const token = nativeChatPastedTextToken(id) + const pane = editor('goals', '/goal Inspect ') + act(() => { + pane.input.setSelectionRange(pane.input.value.length, pane.input.value.length) + // A row Mention, then Mention all: the agent already in the draft is not added again. + pane.input.insertAgentReferences!([first]) + pane.input.insertAgentReferences!([second, first]) + pane.editor.commands.insertContent(` ${token}`) + }) + updateNativeChatComposerDraft( + 'goals', + { pastedTextFiles: { [id]: '/tmp/Same name (1).txt' } }, + 'immediate' + ) + const snapshot = readNativeChatComposerDraft('goals') + const expected = serializeNativeChatAgentReferences( + snapshot.text, + snapshot.document, + snapshot.pastedTextFiles, + 'goal' + ) + .replace(/^\/goal\s+/, '') + .trim() + expect(expected).toContain('@Same name (2) @Same name (3)') + // One line, so main's one-line /goal parser still reads the typed goal, routing notes included. + expect(expected).not.toContain('\n') + expect(expected).toContain('message it with orca orchestration send --to') + expect(expected.match(/@Same name \(2\)/g)).toHaveLength(1) + const setObjective = vi.fn(async () => true) + const structured = transport() + structured.threadGoal = { setObjective } + structured.dispatchCommand = (text) => + dispatchStructuredAgentSessionComposerCommand(text, { + snapshot: [], + invokeAction: async () => true, + setOption: async () => true, + setThreadGoalObjective: setObjective + }) + structured.capturePresentation = () => { + updateNativeChatComposerDraft( + 'goals', + { text: 'later @label', document: undefined, pastedTextFiles: { [id]: '/tmp/later.txt' } }, + 'immediate' + ) + return () => true + } + const hook = renderHook(() => + useNativeChatStructuredComposerSend({ + agent: 'claude', + draftScopeKey: 'goals', + imageAttachments: [], + structuredTransport: structured, + isComposing: () => false, + clearSkillOrigin: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + await act(async () => hook.result.current(snapshot.text)) + expect(setObjective).toHaveBeenLastCalledWith(expected) + expect(structured.send).not.toHaveBeenCalled() + updateNativeChatComposerDraft('goals', snapshot, 'immediate') + const mode = renderHook(() => + useNativeChatComposerSubmit({ + structuredTransport: structured, + draftScopeKey: 'goals', + draft: snapshot.text, + caret: 0, + imageAttachments: [], + disabled: false, + sendPty: vi.fn(), + sendStructured: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + act(() => + mode.result.current.goalMode.interceptPick(vi.fn())({ + kind: 'command', + id: 'goal', + name: 'goal', + token: '/goal', + skillCollision: false + }) + ) + await act(async () => mode.result.current.send()) + expect(setObjective).toHaveBeenCalledTimes(2) + expect(setObjective).toHaveBeenLastCalledWith(expected) +}) + +it('keeps routing notes in Goal mode on a host without goals, where /goal goes out as a message', async () => { + const pane = editor('native-goal', 'Inspect ') + act(() => { + pane.input.setSelectionRange(pane.input.value.length, pane.input.value.length) + pane.input.insertAgentReferences!([first]) + }) + const snapshot = readNativeChatComposerDraft('native-goal') + const sendStructured = vi.fn(async () => true) + const mode = renderHook(() => + useNativeChatComposerSubmit({ + structuredTransport: transport(), + draftScopeKey: 'native-goal', + draft: snapshot.text, + caret: 0, + imageAttachments: [], + disabled: false, + sendPty: vi.fn(), + sendStructured, + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + act(() => + mode.result.current.goalMode.interceptPick(vi.fn())({ + kind: 'command', + id: 'goal', + name: 'goal', + token: '/goal', + builtin: true, + skillCollision: false + }) + ) + await act(async () => mode.result.current.send()) + const objective = serializeNativeChatAgentReferences( + snapshot.text, + snapshot.document, + snapshot.pastedTextFiles + ).trim() + expect(objective).toContain('message it with orca orchestration send --to') + expect(sendStructured).toHaveBeenCalledExactlyOnceWith(`/goal ${objective}`, [], undefined) +}) + +it('applies structured UTF-8 admission to the expanded final body before any send slot is taken', async () => { + const pane = editor('size', '') + act(() => pane.input.insertAgentReferences!([{ ...first, label: 'é'.repeat(70000) }])) + const raw = readNativeChatComposerDraft('size') + expect(Buffer.byteLength(raw.text, 'utf8')).toBeLessThan(256 * 1024) + const structured = transport() + structured.dispatchCommand = async () => ({ handled: false, accepted: false, error: null }) + const hook = renderHook(() => + useNativeChatStructuredComposerSend({ + agent: 'claude', + draftScopeKey: 'size', + imageAttachments: [], + structuredTransport: structured, + isComposing: () => false, + clearSkillOrigin: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + await act(async () => hook.result.current(raw.text)) + expect(structured.send).not.toHaveBeenCalled() + expect(structured.onError).toHaveBeenCalledTimes(1) + expect(readNativeChatComposerDraft('size').text).toBe(raw.text) +}) + +it('keeps direct, Mention all and real menu Mention on the current native handle, caret and captured host after dismissal', async () => { + for (const route of ['direct', 'all', 'menu']) { + const user = userEvent.setup() + const view = mountedMention(crewRows, first, route === 'all') + const input = view.input.current! + act(() => { + input.focus() + input.setSelectionRange(6, 6) + }) + await user.click(view.getByRole('button', { name: /^Show orchestration: 1 worker,/ })) + const more = view.getByRole('button', { name: `More for ${first.label}` }) + const insert = vi.spyOn(view.handle.current!, 'insertAgentReferences') + if (route === 'menu') { + await user.click(more) + } + const popup = within(document.body).queryByRole('menu') + const closed = vi.fn() + popup?.addEventListener('focusScope.autoFocusOnUnmount', closed) + const returnFocus = vi.spyOn(more, 'focus') + await user.click( + route === 'menu' + ? within(document.body).getByRole('menuitem', { name: 'Mention in message' }) + : route === 'all' + ? view.getByRole('button', { name: 'Mention all' }) + : within(view.getByRole('complementary', { name: 'Orchestration' })) + .getByText(first.label) + .closest('button')! + ) + expect(insert).toHaveBeenCalledExactlyOnceWith([{ ...first, hostKey: 'captured-host' }]) + expect(insert.mock.results[0]?.value).toBe(true) + expect(input.contains?.(document.activeElement)).toBe(true) + expect(view.getByRole('button', { name: 'Collapse orchestration panel' }).isConnected).toBe( + true + ) + await waitFor(() => expect(within(document.body).queryByRole('menu')).toBeNull()) + if (popup) { + await waitFor(() => expect(closed).toHaveBeenCalledOnce()) + expect(closed.mock.calls[0][0].target).toBe(popup) + } + expect(input.value).toBe(`Hello ${agentReferenceToken(first)} suffix`) + expect(input.selectionStart).toBe(`Hello ${agentReferenceToken(first)} `.length) + expect(input.contains?.(document.activeElement)).toBe(true) + expect(returnFocus).not.toHaveBeenCalled() + expect(readNativeChatComposerDraft('menu').document?.content?.[0]?.content).toEqual([ + { type: 'text', text: 'Hello ' }, + { type: 'nativeChatAgentReference', attrs: { ...first, hostKey: 'captured-host' } }, + { type: 'text', text: ' suffix' } + ]) + view.unmount() + clearNativeChatComposerDraftsForTests() + crewRows.length = 0 + } +}) + +it('preserves the exact QA3773 ordinary draft around a native row Mention at caret 14', async () => { + const user = userEvent.setup() + const view = mountedMention(crewRows, first, false, 'QA3773 before after') + const input = view.input.current! + act(() => { + input.focus() + input.setSelectionRange(14, 14) + }) + await user.click(view.getByRole('button', { name: /^Show orchestration: 1 worker,/ })) + await user.click( + within(view.getByRole('complementary', { name: 'Orchestration' })) + .getByText(first.label) + .closest('button')! + ) + expect(input.value).toBe(`QA3773 before ${agentReferenceToken(first)} after`) + expect(readNativeChatComposerDraft('menu').document?.content?.[0]?.content).toEqual([ + { type: 'text', text: 'QA3773 before ' }, + { type: 'nativeChatAgentReference', attrs: { ...first, hostKey: 'captured-host' } }, + { type: 'text', text: ' after' } + ]) + expect( + view.container + .querySelector('[data-native-chat-agent-reference]') + ?.getAttribute('data-native-chat-agent-reference') + ).toBe(first.address) + expect(input.selectionStart).toBe(`QA3773 before ${agentReferenceToken(first)}`.length) + expect(input.contains?.(document.activeElement)).toBe(true) + expect(view.getByRole('button', { name: 'Collapse orchestration panel' }).isConnected).toBe(true) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference.tsx new file mode 100644 index 000000000000..2871a3f92cd6 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference.tsx @@ -0,0 +1,87 @@ +import { + Node, + NodeViewWrapper, + ReactNodeViewRenderer, + type Editor, + type NodeViewProps +} from '@tiptap/react' +import { Users } from 'lucide-react' +import { NativeChatPromptPill } from './NativeChatPromptPill' +import { + agentReferenceToken, + type OrchestrationAgentReference +} from '../../../../shared/orchestration-agent-reference' +import { closeHistory } from '@tiptap/pm/history' + +function AgentReferencePill({ node, selected }: NodeViewProps): React.JSX.Element { + return ( + + + + ) +} + +export const NativeChatAgentReference = Node.create({ + name: 'nativeChatAgentReference', + group: 'inline', + inline: true, + atom: true, + selectable: true, + addAttributes: () => ({ + label: { default: '' }, + address: { default: '' }, + hostKey: { default: '' } + }), + addNodeView: () => ReactNodeViewRenderer(AgentReferencePill), + renderText: ({ node }) => + agentReferenceToken({ + label: String(node.attrs.label), + address: String(node.attrs.address), + hostKey: String(node.attrs.hostKey) + }), + renderHTML: ({ node }) => [ + 'span', + { 'data-native-chat-agent-reference': node.attrs.address }, + `@${node.attrs.label}` + ] +}) + +/** A draft holds each agent once: references already in it, or repeated in the list, are skipped. */ +export function insertAgentReferences( + editor: Editor, + candidates: OrchestrationAgentReference[] +): void { + if (!editor.isEditable) { + return + } + const present = new Set() + editor.state.doc.descendants((node) => { + if (node.type.name === NativeChatAgentReference.name) { + present.add(`${node.attrs.hostKey}\0${node.attrs.address}`) + } + }) + const references = candidates.filter(({ hostKey, address }) => { + const key = `${hostKey}\0${address}` + return !present.has(key) && Boolean(present.add(key)) + }) + if (references.length === 0) { + return + } + const nextNode = editor.state.selection.$to.nodeAfter + const hasRightSeparator = nextNode?.isText + ? /^\s/u.test(nextNode.text ?? '') + : nextNode?.type.name === 'hardBreak' + editor.view.dispatch(closeHistory(editor.state.tr)) + editor.commands.insertContent( + references.flatMap((attrs, index) => [ + { type: NativeChatAgentReference.name, attrs }, + ...(index < references.length - 1 || !hasRightSeparator ? [{ type: 'text', text: ' ' }] : []) + ]) + ) + editor.view.dispatch(closeHistory(editor.state.tr)) +} diff --git a/src/renderer/src/components/native-chat/native-chat-composer-destination.test.ts b/src/renderer/src/components/native-chat/native-chat-composer-destination.test.ts index 986c20020193..303051ccaaf8 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-destination.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-destination.test.ts @@ -15,6 +15,7 @@ function handle(): NativeChatComposerHandle { return { focus: vi.fn(() => true), insertTypedText: vi.fn(() => true), + insertAgentReferences: () => false, acceptsText: vi.fn(() => true), appendText: vi.fn(), handlePasteEvent: vi.fn(), diff --git a/src/renderer/src/components/native-chat/native-chat-composer-input.ts b/src/renderer/src/components/native-chat/native-chat-composer-input.ts index c2a6e3ae7b5d..dcbfae9e67de 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-input.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-input.ts @@ -1,3 +1,4 @@ +import type { OrchestrationAgentReference } from '../../../../shared/orchestration-agent-reference' import type { HTMLAttributes, RefObject } from 'react' /** Text coordinates keep transport, attachments, and picker logic independent of the editor. */ @@ -11,6 +12,7 @@ export type NativeChatComposerInput = Pick< | 'select' | 'setSelectionRange' > & { + insertAgentReferences?: (references: OrchestrationAgentReference[]) => void contains?: (node: Node | null) => boolean insertText?: (text: string) => void insertSkill?: (from: number, to: number, token: string, path?: string) => void diff --git a/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts b/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts index a875edab09ed..2e4a13b5f796 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts @@ -26,27 +26,87 @@ export function nativeChatPastedTextState(scope: string, token: string): string /** Only completed paths need boundaries; copied source bytes remain literal. */ export function resolveNativeChatPastedText(scope: string, text: string, copy = false): string { - let resolved = '' + return projectPastedText([text], (token) => nativeChatPastedTextState(scope, token), copy).join( + '' + ) +} + +/** Capture completed file facts with the submitted document, before any send body is built. */ +export function projectNativeChatPastedText( + text: string, + files: Readonly> = {} +): string { + return projectNativeChatPastedTextParts([text], files).join('') +} + +/** Opaque inline parts start nonspace; their tail preserves the existing whitespace edge. */ +export type PastedTextPart = string | { opaque: T; tail: string } + +export function projectNativeChatPastedTextParts( + parts: readonly PastedTextPart[], + files: Readonly> = {} +): PastedTextPart[] { + return projectPastedText(parts, (token) => files[nativeChatPastedTextId(token) ?? ''] ?? null) +} + +function projectPastedText( + parts: readonly PastedTextPart[], + stateOf: (token: string) => string | null, + copy = false +): PastedTextPart[] { + const resolved: PastedTextPart[] = [] + let ordinary: string[] = [] + let projected: string[] = [] let pathBefore = false - text.split(NATIVE_CHAT_PASTED_TEXT_TOKEN).forEach((part, index) => { - const state = index % 2 === 1 ? nativeChatPastedTextState(scope, part) : null - const path = state !== null && state !== 'saving' && state !== 'unsaved' - const piece = path - ? formatNativeChatFileReference(state) - : !copy || state === null - ? part - : state === 'saving' - ? (operations.get(nativeChatPastedTextId(part) ?? '')?.text ?? '') - : translate('components.native-chat.composer.pasteNotSavedLabel', 'Paste not saved') - if (!piece) { - return + let nonspaceBefore = false + const flushProjected = () => { + if (projected.length) { + resolved.push(projected.join('')) + projected = [] } - if ((path || pathBefore) && /\S$/.test(resolved) && /^\S/.test(piece)) { - resolved += ' ' + } + const flushOrdinary = () => { + ordinary + .join('') + .split(NATIVE_CHAT_PASTED_TEXT_TOKEN) + .forEach((part, index) => { + const state = index % 2 === 1 ? stateOf(part) : null + const path = state !== null && state !== 'saving' && state !== 'unsaved' + const piece = path + ? formatNativeChatFileReference(state) + : !copy || state === null + ? part + : state === 'saving' + ? (operations.get(nativeChatPastedTextId(part) ?? '')?.text ?? '') + : translate('components.native-chat.composer.pasteNotSavedLabel', 'Paste not saved') + if (!piece) { + return + } + if ((path || pathBefore) && nonspaceBefore && /^\S/.test(piece)) { + projected.push(' ') + } + projected.push(piece) + nonspaceBefore = /\S$/.test(piece) + pathBefore = path + }) + ordinary = [] + } + for (const part of parts) { + if (typeof part === 'string') { + ordinary.push(part) + } else { + flushOrdinary() + if (pathBefore && nonspaceBefore) { + projected.push(' ') + } + flushProjected() + resolved.push(part) + nonspaceBefore = part.tail.length === 0 + pathBefore = false } - resolved += piece - pathBefore = path - }) + } + flushOrdinary() + flushProjected() return resolved } diff --git a/src/renderer/src/components/native-chat/native-chat-composer-reveal-focus.test.tsx b/src/renderer/src/components/native-chat/native-chat-composer-reveal-focus.test.tsx index 0a4d4c592bcc..4774a5c3274a 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-reveal-focus.test.tsx +++ b/src/renderer/src/components/native-chat/native-chat-composer-reveal-focus.test.tsx @@ -55,6 +55,7 @@ function Harness(props: HarnessProps): React.JSX.Element { return true }, insertTypedText: () => true, + insertAgentReferences: () => false, appendText: () => {}, acceptsText: () => true, handlePasteEvent: () => {}, diff --git a/src/renderer/src/components/native-chat/native-chat-composer-types.ts b/src/renderer/src/components/native-chat/native-chat-composer-types.ts index cb212c77f2c0..848ea5017cc3 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-types.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-types.ts @@ -1,3 +1,4 @@ +import type { OrchestrationAgentReference } from '../../../../shared/orchestration-agent-reference' import type { CaptureStructuredAgentSessionPresentation } from './use-structured-agent-session-mutate' import type { StructuredAgentSessionSendRequest } from './structured-agent-session-send-slot' import type { NativeChatComposerNotice } from './native-chat-composer-notice' @@ -155,6 +156,7 @@ export type NativeChatLaunchSeed = { } export type NativeChatComposerHandle = { + insertAgentReferences: (references: OrchestrationAgentReference[]) => boolean isComposing?: () => boolean focus: () => boolean insertTypedText: (text: string) => boolean diff --git a/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx b/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx index 6bdaa365a9b9..d376bcdde8cb 100644 --- a/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx +++ b/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx @@ -83,6 +83,7 @@ function composerHandle(): NativeChatComposerHandle & { element: HTMLElement } { element.focus() return true }), + insertAgentReferences: () => false, insertTypedText: vi.fn(() => true), appendText: vi.fn(), acceptsText: () => true, diff --git a/src/renderer/src/components/native-chat/native-chat-prompt-document-text.ts b/src/renderer/src/components/native-chat/native-chat-prompt-document-text.ts index 5866dd0e8e59..2c445fe2b21a 100644 --- a/src/renderer/src/components/native-chat/native-chat-prompt-document-text.ts +++ b/src/renderer/src/components/native-chat/native-chat-prompt-document-text.ts @@ -1,4 +1,5 @@ import type { JSONContent } from '@tiptap/react' +import { agentReferenceToken } from '../../../../shared/orchestration-agent-reference' import { imageReferenceToken, splitImageReferences @@ -8,6 +9,24 @@ import { NATIVE_CHAT_PASTED_TEXT_TOKEN } from './native-chat-pasted-text-referen export const IMAGE_REFERENCE_NODE = 'nativeChatImageReference' export const FILE_REFERENCE_NODE = 'nativeChatFileReference' +export function promptLeafString( + type: string | undefined, + attrs: Readonly> | undefined, + text?: string | null +): string { + if (type === 'nativeChatAgentReference') { + return agentReferenceToken({ + label: String(attrs?.label), + address: String(attrs?.address), + hostKey: String(attrs?.hostKey) + }) + } + if (type === IMAGE_REFERENCE_NODE) { + return imageReferenceToken(String(attrs?.attachmentId)) + } + return type === 'hardBreak' ? '\n' : (text ?? String(attrs?.token ?? '')) +} + /** All text-to-document paths must reconstruct image chips and pending-paste pills. */ export function promptTextContent(text: string): JSONContent { return { @@ -114,12 +133,7 @@ export function slicePromptDocument(document: JSONContent, from: number, to: num const start = offset const content: JSONContent[] = [] for (const node of block.content ?? []) { - const value = - node.type === IMAGE_REFERENCE_NODE - ? imageReferenceToken(String(node.attrs?.attachmentId)) - : node.type === 'hardBreak' - ? '\n' - : (node.text ?? String(node.attrs?.token ?? '')) + const value = promptLeafString(node.type, node.attrs, node.text) const end = offset + value.length if (end > from && offset < to) { content.push( diff --git a/src/renderer/src/components/native-chat/native-chat-prompt-document.test.ts b/src/renderer/src/components/native-chat/native-chat-prompt-document.test.ts index df09d9022326..304989dbb685 100644 --- a/src/renderer/src/components/native-chat/native-chat-prompt-document.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-prompt-document.test.ts @@ -5,12 +5,15 @@ import StarterKit from '@tiptap/starter-kit' import { describe, expect, it } from 'vitest' import { NativeChatFileReference, + NativeChatImageReference, NativeChatSkill, promptLeafText, promptText, promptTextOffset, promptTextPosition } from './native-chat-prompt-document' +import { NativeChatAgentReference } from './native-chat-agent-reference' +import { slicePromptDocument } from './native-chat-prompt-document-text' const schema = getSchema([StarterKit, NativeChatSkill, NativeChatFileReference]) @@ -79,6 +82,42 @@ function selectablePositions(doc: ProseMirrorNode): number[] { } describe('prompt document reads', () => { + it('slices serialized UTF-16 offsets with retained agent/image/file/skill atoms, breaks and empty blocks', () => { + const atoms = getSchema([ + StarterKit, + NativeChatSkill, + NativeChatFileReference, + NativeChatImageReference, + NativeChatAgentReference + ]) + const doc = atoms.nodeFromJSON({ + type: 'doc', + content: [ + { type: 'paragraph', content: [{ type: 'text', text: 'sent😀' }] }, + { type: 'paragraph' }, + { + type: 'paragraph', + content: [ + { + type: 'nativeChatAgentReference', + attrs: { label: 'Worker', address: 'term_worker', hostKey: 'remote' } + }, + { type: 'hardBreak' }, + { type: 'nativeChatImageReference', attrs: { attachmentId: 'shot' } }, + { type: 'nativeChatFileReference', attrs: { token: '@f', path: '/f' } }, + { type: 'nativeChatSkill', attrs: { token: '$review', path: '/review/SKILL.md' } }, + { type: 'text', text: '😀 end' } + ] + }, + { type: 'paragraph' } + ] + }) + const text = promptText(doc) + const left = atoms.nodeFromJSON(slicePromptDocument(doc.toJSON(), 'sent😀'.length, text.length)) + expect(promptText(left)).toBe(text.slice('sent😀'.length)) + expect(left.toJSON().content?.[2].content).toEqual(doc.toJSON().content?.[2].content) + expect(promptText(left)).toContain('@Worker (Orca agent term_worker)\n') + }) it('reads UTF-16 units, pills, hard breaks and paragraphs as the agent receives them', () => { const doc = documentWithAtoms() expect(promptText(doc)).toBe('a😀$rev\nb\n@f$x\n') diff --git a/src/renderer/src/components/native-chat/native-chat-prompt-document.ts b/src/renderer/src/components/native-chat/native-chat-prompt-document.ts index 111ae76c6715..43c8cd84d089 100644 --- a/src/renderer/src/components/native-chat/native-chat-prompt-document.ts +++ b/src/renderer/src/components/native-chat/native-chat-prompt-document.ts @@ -3,7 +3,11 @@ import { NativeChatSkillPill, skillLabel } from './NativeChatSkillPill' import { NativeChatImageReferencePill } from './NativeChatImageReferencePill' import { formatNativeChatFileReference } from '../../../../shared/agent-image-paste' import { imageReferenceToken } from '../../../../shared/native-chat/native-chat-image-reference' -import { FILE_REFERENCE_NODE, IMAGE_REFERENCE_NODE } from './native-chat-prompt-document-text' +import { + FILE_REFERENCE_NODE, + IMAGE_REFERENCE_NODE, + promptLeafString +} from './native-chat-prompt-document-text' import { ReactNodeViewRenderer, Node, type JSONContent } from '@tiptap/react' import type { Node as ProseMirrorNode } from '@tiptap/pm/model' import type { AgentJournalSkillRef } from '../../../../shared/agent-session/journal/agent-session-journal-types' @@ -86,10 +90,7 @@ export function fileReferenceContent(path: string): JSONContent { /** A pill reads as its token and a hard break as a newline, so the text is what the agent receives. */ export function promptLeafText(node: ProseMirrorNode): string { - if (node.type.name === IMAGE_REFERENCE_NODE) { - return imageReferenceToken(String(node.attrs.attachmentId)) - } - return node.type.name === 'hardBreak' ? '\n' : String(node.attrs.token ?? '') + return promptLeafString(node.type.name, node.attrs, node.text) } export function promptText(doc: ProseMirrorNode, from = 0, to = doc.content.size): string { diff --git a/src/renderer/src/components/native-chat/native-chat-queued-edit-draft.test.ts b/src/renderer/src/components/native-chat/native-chat-queued-edit-draft.test.ts index d43182883c61..36bae70d207e 100644 --- a/src/renderer/src/components/native-chat/native-chat-queued-edit-draft.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-queued-edit-draft.test.ts @@ -57,6 +57,29 @@ beforeEach(async () => { }) describe('queued edit draft ownership', () => { + it('tracks completed paste projection in edit identity and output without changing raw text', () => { + const id = '11111111-1111-4111-8111-111111111111' + const raw = `before${nativeChatPastedTextToken(id)}after` + const edit = createNativeChatQueuedEditDraft( + { ...body, blocks: [{ type: 'text', text: raw }], skills: [] }, + 'bottom' + ) + expect(nativeChatQueuedEditDirty(edit)).toBe(false) + updateNativeChatComposerDraft( + edit.scopeKey, + { pastedTextFiles: { [id]: '/tmp/queued.txt' } }, + 'immediate' + ) + expect(readNativeChatComposerDraft(edit.scopeKey).text).toBe(raw) + expect(nativeChatQueuedEditDirty(edit)).toBe(true) + expect(nativeChatQueuedEditInput(edit, true, true)).toEqual({ + text: 'before @/tmp/queued.txt after', + images: [], + skills: [] + }) + discardNativeChatQueuedEdit(edit) + }) + it('seeds skill identity without a catalog, preserves original image blocks and omits unsupported fields', async () => { const edit = createNativeChatQueuedEditDraft(body, 'bottom') expect(nativeChatQueuedEditInput(edit, true, true)).toEqual({ diff --git a/src/renderer/src/components/native-chat/native-chat-queued-edit-lifetime.test-fixture.ts b/src/renderer/src/components/native-chat/native-chat-queued-edit-lifetime.test-fixture.ts new file mode 100644 index 000000000000..c97cd1ff4cc9 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-queued-edit-lifetime.test-fixture.ts @@ -0,0 +1,44 @@ +import { renderHook } from '@testing-library/react' +import { vi } from 'vitest' +import { + useNativeChatQueuedEditLifetime, + type NativeChatQueuedEditSession +} from './native-chat-queued-edit-session' +import { + discardNativeChatQueuedEdit, + type NativeChatQueuedEditDraft +} from './native-chat-queued-edit-draft' + +export function mountNativeChatQueuedEditLifetime(draft: NativeChatQueuedEditDraft, scope: string) { + const edit: NativeChatQueuedEditSession = { + ...draft, + scope, + sessionId: 'rich-return', + messageId: 'queued', + baseFingerprint: 'original', + acquiring: false, + uncertain: false, + closed: false, + pendingClose: false, + view: { messages: [], cards: [], submissions: [], promptOpen: false }, + lease: { acquired: Promise.resolve({ status: 'released' }), end: vi.fn() } + } + const active: { current: NativeChatQueuedEditSession | null } = { current: edit } + const reopen = { current: null } + const close = vi.fn((value?: NativeChatQueuedEditSession | null) => { + if (value) { + discardNativeChatQueuedEdit(value) + } + }) + const lifetime = renderHook(() => + useNativeChatQueuedEditLifetime({ + scope, + shownScope: draft.scopeKey, + active, + reopen, + close, + render: vi.fn() + }) + ) + return { lifetime, edit, close, active } +} diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts index f28a14f73203..d4f3852c5a0b 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts @@ -46,6 +46,15 @@ export function useNativeChatComposerHandle( useImperativeHandle( ref, () => ({ + insertAgentReferences: (references) => { + const input = textareaRef.current + if (!input || input.disabled || !input.insertAgentReferences || isComposing()) { + return false + } + input.insertAgentReferences(references) + input.focus() + return true + }, isComposing, focus, insertTypedText, @@ -57,6 +66,7 @@ export function useNativeChatComposerHandle( contains }), [ + textareaRef, isComposing, focus, insertTypedText, diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts index 761ba9ead7e1..c67b8e547721 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts @@ -1,3 +1,5 @@ +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' +import { mayHoldAgentReferences } from '../../../../shared/orchestration-agent-reference' import { useCallback, useMemo, useState } from 'react' import { translate } from '@/i18n/i18n' import { applyPickerSuggestion } from '../../../../shared/native-chat/input/native-chat-picker-triggers' @@ -88,8 +90,17 @@ export function useNativeChatComposerSubmit(args: { // Native goals keep the ordinary sender's paste admission and clearing; host goals clear only an unchanged draft. const setGoal = useCallback( (intent?: NativeChatComposerSendIntent) => { + const submitted = readNativeChatComposerDraft(draftScopeKey) + // A host goal is one line; a provider /goal is sent as a message, so its notes keep their own lines. const objective = structuredAgentSessionGoalObjective( - threadGoal ? resolveNativeChatPastedText(draftScopeKey, draft) : draft + threadGoal || mayHoldAgentReferences(draft) + ? serializeNativeChatAgentReferences( + draft, + submitted.document, + submitted.pastedTextFiles, + threadGoal ? 'goal' : 'message' + ) + : draft ) if (!structuredTransport || objective === '') { return @@ -114,7 +125,6 @@ export function useNativeChatComposerSubmit(args: { } structuredTransport.onSubmitted?.() const isCurrent = structuredTransport.capturePresentation() - const submitted = readNativeChatComposerDraft(draftScopeKey) void threadGoal.setObjective(objective).then((accepted) => { if (!accepted) { return diff --git a/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx index 2ce9bf3d4f47..34bcca171052 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx @@ -22,6 +22,7 @@ function Chat(): React.JSX.Element { composerElementRef.current?.focus() return true }, + insertAgentReferences: () => false, insertTypedText: () => true, acceptsText: () => true, appendText: () => {}, diff --git a/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx index 9cf9572dd8ea..745e572c3319 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx @@ -55,6 +55,7 @@ function Chat({ const rootRef = useRef(null) const composerRef = useRef({ focus: () => true, + insertAgentReferences: () => false, insertTypedText: () => true, acceptsText: () => acceptsText, appendText: mocks.appendText, diff --git a/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx index 2fb8de24d0d0..04d4b2423e5b 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx @@ -37,6 +37,7 @@ function composerHandle(): Composer { handle.element.focus() return true }), + insertAgentReferences: () => false, insertTypedText: vi.fn(() => true), appendText: vi.fn(), acceptsText: () => true, diff --git a/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts index ef9ccb137e1d..d302e79d547d 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts @@ -1,7 +1,6 @@ -import { - admitNativeChatPastedText, - resolveNativeChatPastedText -} from './native-chat-composer-pasted-text-references' +import { readNativeChatComposerDraft } from './native-chat-composer-draft-store' +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' +import { admitNativeChatPastedText } from './native-chat-composer-pasted-text-references' import { useCallback, type Dispatch, type SetStateAction } from 'react' import type { AgentType } from '../../../../shared/agent-status-types' import type { NativeChatLaunchDraft } from '@/lib/native-chat-launch-prompt' @@ -74,7 +73,8 @@ export function useNativeChatPtyComposerSend(args: { if (!admitNativeChatPastedText(args.draftScopeKey, text, args.setNotice)) { return } - text = resolveNativeChatPastedText(args.draftScopeKey, text) + const submitted = readNativeChatComposerDraft(args.draftScopeKey) + text = serializeNativeChatAgentReferences(text, submitted.document, submitted.pastedTextFiles) const { sendOptions: launchSendOptions } = resolveNativeChatLaunchDraftSend({ launchDraft: args.launchDraft, launchDraftResolved: args.launchDraftResolved, diff --git a/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx index 6d1ee8a99e40..cd6b9bd7f798 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx @@ -13,6 +13,7 @@ vi.mock('@/lib/visible-overlay', () => ({ hasVisibleOverlay: () => overlay.visib const insertTypedText = vi.fn(() => true) const composer: NativeChatComposerHandle = { focus: () => true, + insertAgentReferences: () => false, insertTypedText, appendText: () => {}, acceptsText: () => true, diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.test.tsx index e9574c4efb52..a22aca6f83ee 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.test.tsx @@ -8,7 +8,7 @@ import { nativeChatComposerDraftWritesSettled, updateNativeChatComposerDraft } from './native-chat-composer-draft-store' -import { act, cleanup, render, renderHook, screen } from '@testing-library/react' +import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react' import { createRef } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dispatchStructuredAgentSessionComposerCommand } from '../../../../shared/agent-session/view/structured-agent-session-composer' @@ -309,7 +309,9 @@ import { import { useNativeChatDraft } from './use-native-chat-draft' import { NativeChatPromptEditor } from './NativeChatPromptEditor' import { promptEditor } from './native-chat-prompt-editor.test-support' -import { promptSkillRefs } from './native-chat-prompt-document' +import { promptSkillRefs, promptText } from './native-chat-prompt-document' +import { mountNativeChatQueuedEditLifetime } from './native-chat-queued-edit-lifetime.test-fixture' +import type { NativeChatComposerInput } from './native-chat-composer-input' describe('complete handback acceptance', () => { const scope = 'agent-session:rich-return' @@ -418,6 +420,103 @@ describe('complete handback acceptance', () => { } } + it('keeps agent-offset handback after queued-edit lifetime cleanup, obsolete Goal acceptance and editor remount/next Send', async () => { + const fixture = acceptanceFixture() + const submitted = '/goal @Worker (Orca agent term_worker) ship' + updateNativeChatComposerDraft( + scope, + { + text: submitted, + document: { + type: 'doc', + content: [ + { + type: 'paragraph', + content: [ + { type: 'text', text: '/goal ' }, + { + type: 'nativeChatAgentReference', + attrs: { label: 'Worker', address: 'term_worker', hostKey: 'local' } + }, + { type: 'text', text: ' ship' } + ] + } + ] + } + }, + 'immediate' + ) + const hook = fixture.mount() + let pending: Promise | undefined + act(() => { + pending = hook.result.current.send(submitted, []) + }) + const draft = createNativeChatQueuedEditDraft( + { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'queued' }] + }, + scope + ) + updateNativeChatComposerDraft( + draft.scopeKey, + { + text: 'later', + document: { + type: 'doc', + content: [{ type: 'paragraph', content: [{ type: 'text', text: 'later' }] }] + } + }, + 'immediate' + ) + const { lifetime, edit, close, active } = mountNativeChatQueuedEditLifetime(draft, scope) + // The actual effect cleanup returns dirty work; explicit Cancel would discard it. + act(() => lifetime.unmount()) + expect(close).toHaveBeenCalledWith(edit) + expect(active.current).toBeNull() + expect(readNativeChatComposerDraft(scope).text).toBe(`${submitted}\n\nlater`) + fixture.depart() + hook.unmount() + await act(async () => { + fixture.goal.resolve(true) + await pending + }) + expect(readNativeChatComposerDraft(scope).text).toBe('\n\nlater') + expect(fixture.caret).not.toHaveBeenCalled() + expect(fixture.transport.send).not.toHaveBeenCalled() + fixture.arrive() + const inputRef = createRef() + function Reopened() { + const next = fixture.useSend(scope) + return ( + <> + next.setDraft(input.value)} + onSelect={() => {}} + /> + + + ) + } + render() + const editor = promptEditor(screen.getByRole('textbox')) + expect(promptText(editor.state.doc)).toBe('\n\nlater') + act(() => { + editor.commands.insertContentAt(editor.state.doc.content.size - 1, ' edited') + }) + expect(inputRef.current?.value).toBe('\n\nlater edited') + fireEvent.click(screen.getByRole('button', { name: 'Send returned work' })) + await vi.waitFor(() => + expect(fixture.transport.send).toHaveBeenCalledExactlyOnceWith('\n\nlater edited', []) + ) + }) + it.each(['current', 'obsolete'] as const)( 'retains accepted handback node identity through %s presentation and the next actual Send', async (presentation) => { diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts index 25d75c69cbcd..8bb0a37de656 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts @@ -1,3 +1,5 @@ +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' +import { mayHoldAgentReferences } from '../../../../shared/orchestration-agent-reference' import { getAgentLabel } from '@/lib/agent-catalog' import { formatAgentTypeLabel } from '../../../../shared/agent-type-label' import { isTuiAgent } from '../../../../shared/tui-agent-config' @@ -8,6 +10,7 @@ import { useCallback } from 'react' import { completeNativeChatStructuredUserAction } from './native-chat-structured-user-action' import { isStructuredAgentSessionHostCommand, + isStructuredAgentSessionGoalCommand, structuredAgentSessionCommandChangesConversation } from '../../../../shared/agent-session/view/structured-agent-session-composer' import type { AgentType } from '../../../../shared/agent-status-types' @@ -29,7 +32,7 @@ import { import { nativeChatComposerDraftLeftAfterSend } from './native-chat-composer-draft-comparison' import { admitNativeChatPastedText, - resolveNativeChatPastedText + projectNativeChatPastedText } from './native-chat-composer-pasted-text-references' export type UseNativeChatStructuredComposerSendArgs = { @@ -69,7 +72,9 @@ export function useNativeChatStructuredComposerSend({ if (!admitNativeChatPastedText(draftScopeKey, text, structuredTransport.onError)) { return false } - text = resolveNativeChatPastedText(draftScopeKey, text) + const submitted = readNativeChatComposerDraft(draftScopeKey) + const submittedText = text + text = projectNativeChatPastedText(text, submitted.pastedTextFiles) const hostCommand = isStructuredAgentSessionHostCommand( text, structuredTransport.threadGoal !== undefined @@ -101,7 +106,18 @@ export function useNativeChatStructuredComposerSend({ structuredTransport.onSubmitted?.() } const isCurrent = structuredTransport.capturePresentation() - const submitted = readNativeChatComposerDraft(draftScopeKey) + if ( + mayHoldAgentReferences(submittedText) && + (!hostCommand || + (structuredTransport.threadGoal && isStructuredAgentSessionGoalCommand(text))) + ) { + text = serializeNativeChatAgentReferences( + submittedText, + submitted.document, + submitted.pastedTextFiles, + hostCommand ? 'goal' : 'message' + ) + } let completeAddition = false const stopObservingAppend = subscribeToNativeChatComposerDraftAppend( draftScopeKey, diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-queued-edit.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-queued-edit.test.tsx index d9ac5aa5101d..3a6880f33a28 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-queued-edit.test.tsx +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-queued-edit.test.tsx @@ -577,6 +577,7 @@ it.each(['updated', 'not-editable', 'clean-gone', 'cancel'] as const)( current: { focus: () => true, acceptsText: () => !editor?.saving, + insertAgentReferences: () => false, insertTypedText: (text) => { if (!editor || editor.saving) { return false diff --git a/src/renderer/src/components/orchestration-crew/CrewAgentIcons.test.tsx b/src/renderer/src/components/orchestration-crew/CrewAgentIcons.test.tsx index 97e68a86234b..2b5c2ca958a6 100644 --- a/src/renderer/src/components/orchestration-crew/CrewAgentIcons.test.tsx +++ b/src/renderer/src/components/orchestration-crew/CrewAgentIcons.test.tsx @@ -48,6 +48,8 @@ function panel(rows: OrchestrationCrewRow[], target: RuntimeClientTarget = local { expect(screen.queryByRole('img', { name: 'Working' })).toBeNull() }) +it('follows a terminal into retained state and falls back only after its local pane disappears', () => { + render() + expect(screen.getByRole('img', { name: 'Working' })).toBeInTheDocument() + const entry = { ...status(0), state: 'done' as const } + act(() => + useAppStore.setState({ + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: { + [entry.paneKey]: { + entry, + tab: makeTab({ id: 'tab-0', worktreeId: 'workspace' }), + worktreeId: 'workspace', + agentType: 'claude', + startedAt: 1 + } + } + }) + ) + expect(screen.getByRole('img', { name: 'Done' })).toBeInTheDocument() + act(() => useAppStore.setState({ retainedAgentsByPaneKey: {} })) + expect(screen.getByRole('img', { name: 'Needs permission' })).toBeInTheDocument() +}) + it('keeps imported, missing, dispatch and failed-task peers on the Crew snapshot despite matching local handles', () => { const base = row() const rows = [ @@ -194,7 +219,7 @@ it.each([10, 100])( const listeners = readStoreListenerCount() ?? 0 const mounted = render(panel(Array.from({ length: n }, (_, i) => row(i)))) await act(async () => {}) - expect(readStoreListenerCount()).toBe(listeners + 1) + expect(readStoreListenerCount()).toBe((listeners ?? 0) + 1) fireEvent.click(screen.getByRole('button', { name: /^Show orchestration:/ })) expect(normalize).toHaveBeenCalledTimes(n) visits = 0 diff --git a/src/renderer/src/components/orchestration-crew/CrewRowMenu.tsx b/src/renderer/src/components/orchestration-crew/CrewRowMenu.tsx index ea6361c239ba..e6d730a26e66 100644 --- a/src/renderer/src/components/orchestration-crew/CrewRowMenu.tsx +++ b/src/renderer/src/components/orchestration-crew/CrewRowMenu.tsx @@ -11,7 +11,17 @@ import { translate } from '@/i18n/i18n' import type { OrchestrationCrewRow } from '../../../../shared/orchestration-crew' import { useCrewMenuFocus } from './use-crew-menu-focus' -export function CrewRowMenu({ row, open }: { row: OrchestrationCrewRow; open: () => void }) { +export function CrewRowMenu({ + row, + open, + canMention, + mention +}: { + row: OrchestrationCrewRow + open: () => void + canMention: boolean + mention: () => void +}) { const menu = useCrewMenuFocus() return ( @@ -33,6 +43,9 @@ export function CrewRowMenu({ row, open }: { row: OrchestrationCrewRow; open: () onPointerDownOutside={menu.onPointerDownOutside} onCloseAutoFocus={menu.onCloseAutoFocus} > + + {translate('components.orchestrationCrew.mentionInMessage', 'Mention in message')} + {translate('components.orchestrationCrew.openChat', 'Open its chat')} diff --git a/src/renderer/src/components/orchestration-crew/CrewRowView.tsx b/src/renderer/src/components/orchestration-crew/CrewRowView.tsx index 37a98c4cef8f..37ecf30f69a4 100644 --- a/src/renderer/src/components/orchestration-crew/CrewRowView.tsx +++ b/src/renderer/src/components/orchestration-crew/CrewRowView.tsx @@ -36,12 +36,16 @@ export const CrewRowView = memo(function CrewRowView({ row, look, target, - isVisible + isVisible, + canMention, + mention: mentionRows }: { row: OrchestrationCrewRow look: CrewRowLook target: RuntimeClientTarget isVisible: boolean + canMention: boolean + mention: (rows: OrchestrationCrewRow[]) => void }) { // memo() skips the parent re-render a language switch relies on. useUiLanguageRevision() @@ -51,14 +55,30 @@ export const CrewRowView = memo(function CrewRowView({ void openOrchestrationCrewAgent(row, target) } const toggle = () => setExpanded((value) => !value) + const mention = () => mentionRows([row]) + const mentionable = canMention && Boolean(row.sendAddress) return ( -
+
+ {/* Without Mention the row's status and question stay at full strength; only the click goes away. */}
- + {}} + snapshot={snapshot('Beta')} + />
) @@ -219,7 +231,13 @@ function pane(value: OrchestrationCrewSnapshot) { /> ))} - + {}} + snapshot={value} + /> ) }) @@ -232,7 +250,13 @@ function nativeChat(value: OrchestrationCrewSnapshot) { render: () => (
- + {}} + />
{Array.from({ length: 12 }, (_, index) => (
({ snapshot: {}, open: vi.fn(), copy: vi.fn(), success: vi.fn() })) +const rig = vi.hoisted(() => ({ + snapshot: {}, + open: vi.fn(), + copy: vi.fn(), + success: vi.fn(), + mention: vi.fn() +})) vi.mock('../native-chat/use-orchestration-crew', () => ({ useOrchestrationCrew: () => rig.snapshot })) @@ -30,7 +36,7 @@ const worker: OrchestrationCrewRow = { sequence: 1 } } -function mount(row = worker, section: 'managing' | 'talkingWith' = 'managing') { +function mount(row = worker, section: 'managing' | 'talkingWith' = 'managing', canMention = false) { rig.snapshot = { ...emptyCrew('ok'), sections: { @@ -48,7 +54,12 @@ function mount(row = worker, section: 'managing' | 'talkingWith' = 'managing') {
- +
@@ -60,37 +71,66 @@ afterEach(() => { vi.clearAllMocks() }) -it('keeps keyboard/body disclosure, chevron, Open, Copy, Escape and collapse independent', async () => { +it('keeps disabled/enabled mentions, keyboard disclosure, Open, Copy, Escape and collapse independent', async () => { const user = userEvent.setup() - mount() + const view = mount() const tab = screen.getByRole('button', { name: 'Show orchestration: 1 worker, 1 working' }) tab.focus() await user.keyboard('{Enter}') expect(screen.getByRole('button', { name: 'Collapse orchestration panel' })).toHaveFocus() expect(screen.getByText('Orchestration')).toBeInTheDocument() - const body = screen.getByRole('button', { name: /Check the result The result is ready\./ }) - expect(body).toHaveAttribute('aria-expanded', 'false') - body.focus() + const body = screen.getByRole('button', { name: /^Mention Worker: .*Check the result/ }) + const chevron = screen.getByRole('button', { name: "Show Worker's task and latest message" }) + expect(body).toBeDisabled() + expect(body).not.toHaveAttribute('aria-expanded') + expect(screen.getByRole('button', { name: 'Mention all' })).toBeDisabled() + await user.click(body) + expect(rig.mention).not.toHaveBeenCalled() + expect(chevron).toHaveAttribute('aria-expanded', 'false') + chevron.focus() await user.keyboard(' ') - expect(body).toHaveAttribute('aria-expanded', 'true') + expect(chevron).toHaveAttribute('aria-expanded', 'true') expect(screen.getByText('Latest')).toBeInTheDocument() expect(rig.open).not.toHaveBeenCalled() expect(rig.copy).not.toHaveBeenCalled() - await user.click(screen.getByRole('button', { name: "Show Worker's task and latest message" })) - expect(body).toHaveAttribute('aria-expanded', 'false') + await user.click(chevron) + expect(chevron).toHaveAttribute('aria-expanded', 'false') + view.rerender( + +
+
+ +
+
+
+ ) + expect(body).toBeEnabled() + expect(screen.getByRole('button', { name: 'Mention all' })).toBeEnabled() + body.focus() + await user.keyboard(' ') + expect(rig.mention).toHaveBeenCalledExactlyOnceWith([worker]) + expect(chevron).toHaveAttribute('aria-expanded', 'false') + await user.click(chevron) await user.click(body) - expect(body).toHaveAttribute('aria-expanded', 'true') + expect(rig.mention).toHaveBeenCalledTimes(2) + expect(rig.mention).toHaveBeenLastCalledWith([worker]) + expect(chevron).toHaveAttribute('aria-expanded', 'true') const open = screen.getByRole('button', { name: 'Open Worker' }) open.focus() await user.keyboard('{Enter}') expect(rig.open).toHaveBeenCalledExactlyOnceWith(worker, host) - expect(body).toHaveAttribute('aria-expanded', 'true') + expect(chevron).toHaveAttribute('aria-expanded', 'true') await user.click(screen.getByRole('button', { name: 'More for Worker' })) await user.click(screen.getByRole('menuitem', { name: 'Copy address' })) expect(rig.copy).toHaveBeenCalledExactlyOnceWith('dispatch:d1') expect(rig.success).toHaveBeenCalledExactlyOnceWith("Copied Worker's address") expect(rig.open).toHaveBeenCalledOnce() - expect(body).toHaveAttribute('aria-expanded', 'true') + expect(chevron).toHaveAttribute('aria-expanded', 'true') await user.click(screen.getByRole('button', { name: 'More for Worker' })) const menuOpen = screen.getByRole('menuitem', { name: 'Open its chat' }) menuOpen.focus() @@ -98,7 +138,7 @@ it('keeps keyboard/body disclosure, chevron, Open, Copy, Escape and collapse ind expect(rig.open).toHaveBeenCalledTimes(2) expect(rig.open).toHaveBeenLastCalledWith(worker, host) await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument()) - expect(body).toHaveAttribute('aria-expanded', 'true') + expect(chevron).toHaveAttribute('aria-expanded', 'true') screen.getByRole('button', { name: 'Collapse orchestration panel' }).focus() expect(await screen.findByRole('tooltip')).toHaveTextContent('Collapse orchestration panel') await user.keyboard('{Escape}') @@ -114,6 +154,65 @@ it('keeps keyboard/body disclosure, chevron, Open, Copy, Escape and collapse ind expect(rig.copy).toHaveBeenCalledOnce() }) +it('mentions exactly the eligible Managing workers once in section order', async () => { + const user = userEvent.setup() + const managing: OrchestrationCrewRow[] = [ + { + ...worker, + partyKey: 'dispatched-unknown', + sendAddress: 'dispatch:unknown', + status: 'unknown', + task: { title: 'Dispatched work', state: 'dispatched' } + }, + { + ...worker, + partyKey: 'ready-waiting', + sendAddress: 'dispatch:waiting', + status: 'waiting', + task: { title: 'Ready work', state: 'ready' } + }, + { + ...worker, + partyKey: 'completed-working', + sendAddress: 'dispatch:completed', + status: 'working', + task: { title: 'Completed work', state: 'completed' } + }, + { + ...worker, + partyKey: 'dispatched-no-address', + sendAddress: undefined, + task: { title: 'Unavailable work', state: 'dispatched' } + } + ] + const peer: OrchestrationCrewRow = { + ...worker, + partyKey: 'sendable-peer', + role: 'peer', + sendAddress: 'dispatch:peer' + } + rig.snapshot = { + ...emptyCrew('ok'), + sections: { managedBy: [], managing, talkingWith: [peer] } + } + render( + + + + ) + await user.click(screen.getByRole('button', { name: /^Show orchestration: 4 workers,/ })) + await user.click(screen.getByRole('button', { name: 'Mention all' })) + expect(rig.mention).toHaveBeenCalledExactlyOnceWith([ + expect.objectContaining({ partyKey: 'dispatched-unknown', sendAddress: 'dispatch:unknown' }), + expect.objectContaining({ partyKey: 'ready-waiting', sendAddress: 'dispatch:waiting' }) + ]) +}) + it('shows a pending question on the row and in its details without navigating or copying', async () => { const user = userEvent.setup() mount({ ...worker, pendingQuestion: { preview: 'Which option?', at: '2026-10-28T01:00:00Z' } }) @@ -150,7 +249,12 @@ it('names the Orchestration disclosure and expands every manager', async () => { } render( - + ) const tab = screen.getByRole('button', { name: 'Show orchestration: 2 working' }) @@ -176,7 +280,12 @@ it('shows one collapsed avatar and question per party with reverse-role relation } render( - + ) const tab = screen.getByRole('button', { @@ -199,12 +308,17 @@ it('retains an unavailable peer’s Open/latest/disclosure with one reason and u const user = userEvent.setup() const { sendAddress, ...peer } = { ...worker, role: 'peer' as const, hostLabel: 'Remote host' } expect(sendAddress).toBe('dispatch:d1') - mount(peer, 'talkingWith') + mount(peer, 'talkingWith', true) await user.click(screen.getByRole('button', { name: 'Show orchestration: 1 working' })) expect(screen.getAllByText('Sending unavailable')).toHaveLength(1) - const body = screen.getByRole('button', { name: /Check the result/ }) + const body = screen.getByRole('button', { name: /^Mention Worker:/ }) + expect(body).toBeDisabled() await user.click(body) - expect(body).toHaveAttribute('aria-expanded', 'true') + expect(rig.mention).not.toHaveBeenCalled() + expect(body).not.toHaveAttribute('aria-expanded') + const chevron = screen.getByRole('button', { name: "Show Worker's task and latest message" }) + await user.click(chevron) + expect(chevron).toHaveAttribute('aria-expanded', 'true') expect(screen.getByText('Latest')).toBeInTheDocument() expect(screen.getAllByText('Sending unavailable')).toHaveLength(1) await user.hover(screen.getByRole('img', { name: 'Codex · Remote host' })) @@ -213,6 +327,10 @@ it('retains an unavailable peer’s Open/latest/disclosure with one reason and u await user.click(screen.getByRole('button', { name: 'Open Worker' })) expect(rig.open).toHaveBeenCalledExactlyOnceWith(peer, host) await user.click(screen.getByRole('button', { name: 'More for Worker' })) + expect(screen.getByRole('menuitem', { name: 'Mention in message' })).toHaveAttribute( + 'aria-disabled', + 'true' + ) const copy = screen.getByRole('menuitem', { name: 'Copy address' }) expect(copy).toHaveAttribute('aria-disabled', 'true') await user.click(copy) @@ -260,7 +378,12 @@ it('groups the closed tab by status with three icons and +n, and sorts rows by l } render( - + ) const tab = screen.getByRole('button', { diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx index bf35f1f8e79f..3b2039ed3646 100644 --- a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { PanelRight, PanelRightClose, Workflow } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' @@ -24,9 +24,20 @@ import { type CrewStatusGroup } from './CrewAgentIcons' +function runningWorker(row: OrchestrationCrewRow): boolean { + return Boolean( + row.sendAddress && + row.task && + !['completed', 'failed'].includes(row.task.state) && + (row.task.state === 'dispatched' || ['working', 'waiting', 'blocked'].includes(row.status)) + ) +} + type PanelProps = { target: RuntimeClientTarget party: string + canMention: boolean + mention: (rows: OrchestrationCrewRow[]) => void isVisible?: boolean } @@ -99,6 +110,8 @@ export function OrchestrationCrewPanel(props: PanelProps): React.JSX.Element | n export function CrewPanelContent({ target, + canMention, + mention, snapshot, isVisible = true }: PanelProps & { snapshot: OrchestrationCrewSnapshot }): React.JSX.Element | null { @@ -107,6 +120,15 @@ export function CrewPanelContent({ const tab = useRef(null) const collapse = useRef(null) const restore = useRef(false) + // Hosts pass a new mention function each render; rows get one stable function so their memo holds. + const latestMention = useRef(mention) + useLayoutEffect(() => { + latestMention.current = mention + }) + const stableMention = useCallback( + (rows: OrchestrationCrewRow[]) => latestMention.current(rows), + [] + ) useLayoutEffect(() => { if (open) { collapse.current?.focus({ preventScroll: true }) @@ -216,9 +238,20 @@ export function CrewPanelContent({ {sections.map(([key, sectionTitle, rows]) => rows.length > 0 ? (
-
- {sectionTitle} - {rows.length} +
+ {sectionTitle} + {rows.length} + {key === 'Managing' ? ( + + ) : null}
{rows.map((row) => ( ))}
diff --git a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx index 51149fdf5794..9e99961c1234 100644 --- a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx +++ b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx @@ -1,16 +1,15 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' import type { ComponentProps } from 'react' -import { act, cleanup, render, screen, within } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, within, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it, vi } from 'vitest' +import { toast } from 'sonner' +import { PaneManager } from '@/lib/pane-manager/pane-manager' import { useAppStore } from '@/store' import { getDefaultSettings } from '../../../../shared/constants' -import { - initialStore, - resetSenderStore -} from '../native-chat/native-chat-agent-sender.test-fixture' import { TooltipProvider } from '@/components/ui/tooltip' +import type { PtyTransport } from '../terminal-pane/pty-transport-types' import { emptyCrew, type OrchestrationCrewRow } from '../../../../shared/orchestration-crew' import { makePaneKey } from '../../../../shared/stable-pane-id' import { createIpcPtyTransport } from '../terminal-pane/pty-transport' @@ -27,7 +26,10 @@ vi.mock('./use-terminal-crew-identity', () => ({ vi.mock('../native-chat/use-orchestration-crew', () => ({ useOrchestrationCrew: () => { rig.crew() - return { ...emptyCrew('ok'), sections: { managedBy: [], managing: [worker], talkingWith: [] } } + return { + ...emptyCrew('ok'), + sections: { managedBy: [], managing: [currentWorker], talkingWith: [] } + } } })) // Render the real panel synchronously; the lazy chunk boundary is the app's load detail. @@ -35,12 +37,11 @@ vi.mock('./LazyOrchestrationCrewPanel', async () => ({ LazyOrchestrationCrewPanel: (await import('./OrchestrationCrewPanel')).OrchestrationCrewPanel })) vi.mock('@/lib/open-agent-message-sender', () => ({ openOrchestrationCrewAgent: rig.open })) -// happy-dom has no canvas; actual PaneManager identity/layout does not need xterm opened. vi.mock('@/lib/pane-manager/pane-lifecycle', async (importOriginal) => { const actual: object = await importOriginal() return { ...actual, openTerminal: vi.fn() } }) -const { PaneManager } = await import('@/lib/pane-manager/pane-manager') +vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) const worker: OrchestrationCrewRow = { partyKey: 'worker', @@ -57,34 +58,102 @@ const worker: OrchestrationCrewRow = { sequence: 1 } } +let currentWorker = worker type Controller = ComponentProps['controller'] -const managers: InstanceType[] = [] -const transports: ReturnType[] = [] -const roots: HTMLElement[] = [] -function mount() { +const managers = new Set() +const ipcTransports: ReturnType[] = [] +function resetFixture() { + cleanup() + for (const transport of ipcTransports.splice(0)) { + transport.destroy?.() + } + for (const manager of managers) { + manager.destroy() + } + managers.clear() + document.body.replaceChildren() + vi.restoreAllMocks() + vi.unstubAllGlobals() + useAppStore.setState(useAppStore.getInitialState(), true) +} +afterEach(() => { + resetFixture() + vi.clearAllMocks() +}) + +function mount(insertion?: { + acceptance: boolean | Promise | undefined + split?: boolean + restored?: boolean +}) { + // On unless the test turned it off first. + if (useAppStore.getState().settings?.experimentalOrchestrationPanel === undefined) { + useAppStore.setState({ + settings: { ...getDefaultSettings('/home/test'), experimentalOrchestrationPanel: true } + }) + } + const link = { connected: !insertion?.restored } + currentWorker = insertion + ? { ...worker, task: { title: 'Inspect', state: 'dispatched' }, sendAddress: 'term_worker' } + : worker + if (insertion) { + vi.stubGlobal('requestAnimationFrame', () => 1) + vi.stubGlobal('cancelAnimationFrame', () => {}) + } const root = document.createElement('div') document.body.appendChild(root) - roots.push(root) const manager = new PaneManager(root, { linkOpenHint: () => '' }) - managers.push(manager) - const first = manager.createInitialPane() - const second = manager.splitPane(first.id, 'vertical') + managers.add(manager) + const first = manager.createInitialPane( + insertion ? { focus: false, leafId: '11111111-1111-4111-8111-111111111111' } : undefined + ) + const second = insertion && !insertion.split ? first : manager.splitPane(first.id, 'vertical') if (!second) { throw new Error('fixture split failed') } - const panes = [first, second] + const panes = insertion && !insertion.split ? [first] : [first, second] + const input = document.createElement('textarea') + const secondInput = document.createElement('textarea') + input.value = 'existing suffix' + input.setSelectionRange(8, 8) + const sendInput = vi.fn(() => true) + const accepted = vi.fn(async () => insertion?.acceptance ?? true) + const transport: PtyTransport = { + connect: vi.fn(), + attach: vi.fn(), + disconnect: vi.fn(), + sendInputImmediate: vi.fn(() => true), + resize: vi.fn(() => true), + getPtyId: () => (link.connected ? 'pty-captured' : null), + isConnected: () => link.connected, + sendInput, + ...(insertion?.acceptance === undefined ? {} : { sendInputAccepted: accepted }) + } + const transports = new Map( + panes.map((pane) => { + if (insertion) { + return [pane.id, transport] as const + } + const ipc = createIpcPtyTransport() + ipcTransports.push(ipc) + return [pane.id, ipc] as const + }) + ) + if (insertion) { + first.container.append(input) + vi.spyOn(first.terminal, 'focus').mockImplementation(() => input.focus()) + if (insertion.split) { + second.container.append(secondInput) + vi.spyOn(second.terminal, 'focus').mockImplementation(() => secondInput.focus()) + } + manager.setActivePane(first.id, { focus: false }) + vi.spyOn(manager, 'setActivePane') + } const controller: Controller = { - tabId: 'retained-tab', - worktreeId: 'worktree', - paneTransportsRef: { - current: new Map( - panes.map((pane) => { - const transport = createIpcPtyTransport() - transports.push(transport) - return [pane.id, transport] - }) - ) - }, + tabId: insertion ? 'tab' : 'retained-tab', + worktreeId: insertion ? 'workspace' : 'worktree', + managerRef: { current: manager }, + paneTransportsRef: { current: transports }, managedPanes: panes, effectiveChatViewMode: false, chatPane: null, @@ -103,30 +172,184 @@ function mount() { ) const view = render(content()) - return { controller, first, second, manager, update: () => view.rerender(content()) } + return { + controller, + first, + second, + manager, + input, + secondInput, + transport, + transports, + link, + accepted, + sendInput, + update: () => view.rerender(content()) + } } -beforeEach(() => { - resetSenderStore() - useAppStore.setState({ - settings: { ...getDefaultSettings('/home/test'), experimentalOrchestrationPanel: true } - }) -}) -afterEach(() => { - cleanup() - for (const transport of transports.splice(0)) { - transport.destroy?.() +function fixture(acceptance: boolean | Promise | undefined, split = false) { + const test = mount({ acceptance, split }) + const pane = test.first + fireEvent.click( + within(pane.container).getByRole('button', { name: /^Show orchestration: 1 worker,/ }) + ) + return { + ...test, + pane, + more: within(pane.container).getByRole('button', { name: 'More for Worker' }), + mention: () => + fireEvent.click(within(pane.container).getByRole('button', { name: 'Mention all' })) } - for (const manager of managers.splice(0)) { - manager.destroy() +} + +it.each(['row', 'all', 'menu'] as const)( + 'focuses captured input at the pointer and keyboard %s press before pending paste, keeping the panel open', + async (route) => { + for (const method of ['pointer', 'keyboard'] as const) { + const tasks = holdPhysicalCloseTasks() + const user = userEvent.setup() + const delivery = Promise.withResolvers() + const test = fixture(delivery.promise, true) + const pane = within(test.pane.container) + test.accepted.mockImplementationOnce(async () => { + expect(test.input).toHaveFocus() + expect(test.manager.getActivePane()?.id).toBe(test.pane.id) + return delivery.promise + }) + const button = + route === 'row' + ? pane.getByRole('button', { name: /^Mention Worker:/ }) + : route === 'all' + ? pane.getByRole('button', { name: 'Mention all' }) + : test.more + if (method === 'keyboard') { + act(() => button.focus()) + await user.keyboard('{Enter}') + } else { + await user.click(button) + } + if (route === 'menu') { + const item = screen.getByRole('menuitem', { name: 'Mention in message' }) + if (method === 'keyboard') { + await waitFor(() => expect(item).toHaveFocus()) + await user.keyboard('{Enter}') + } else { + await user.click(item) + } + } + expect(test.accepted).toHaveBeenCalledExactlyOnceWith( + 'Worker (Orca agent term_worker) ', + 'driving' + ) + expect(test.input).toHaveFocus() + expect(pane.getByRole('button', { name: 'Collapse orchestration panel' })).toBeInTheDocument() + const returned = vi.spyOn(test.more, 'focus') + if (route === 'menu') { + expect(tasks).toHaveLength(1) + act(tasks[0]) + expect(returned).not.toHaveBeenCalled() + expect(test.input).toHaveFocus() + } + vi.mocked(test.manager.setActivePane).mockClear() + await act(async () => delivery.resolve(true)) + expect(test.manager.setActivePane).not.toHaveBeenCalled() + expect(test.input).toHaveFocus() + expect(test.input.value).toBe('existing suffix') + expect(test.input.selectionStart).toBe(8) + expect(test.sendInput).not.toHaveBeenCalled() + expect(toast.error).not.toHaveBeenCalled() + resetFixture() + vi.clearAllMocks() + } } - for (const root of roots.splice(0)) { - root.remove() +) + +it('does not focus or activate after ACK over a later pointer choice of another pane', async () => { + const tasks = holdPhysicalCloseTasks() + const user = userEvent.setup() + const delivery = Promise.withResolvers() + const test = fixture(delivery.promise, true) + await user.click(test.more) + await user.click(screen.getByRole('menuitem', { name: 'Mention in message' })) + expect(test.input).toHaveFocus() + fireEvent.pointerDown(test.second.container) + const destination = document.activeElement + act(tasks[0]) + expect(document.activeElement).toBe(destination) + vi.mocked(test.manager.setActivePane).mockClear() + const focus = vi.mocked(test.pane.terminal.focus) + focus.mockClear() + await act(async () => delivery.resolve(false)) + expect(test.manager.setActivePane).not.toHaveBeenCalled() + expect(focus).not.toHaveBeenCalled() + expect(document.activeElement).toBe(destination) + expect(test.accepted).toHaveBeenCalledExactlyOnceWith( + 'Worker (Orca agent term_worker) ', + 'driving' + ) + expect(test.sendInput).not.toHaveBeenCalled() + expect(toast.error).toHaveBeenCalledOnce() +}) + +it('focuses the captured pane before acceptance, preserves caret/no Enter, and uses the legacy input fallback', async () => { + for (const acceptance of [true, undefined]) { + const test = fixture(acceptance) + expect(document.activeElement).not.toBe(test.input) + await act(async () => test.mention()) + expect(test.manager.setActivePane).toHaveBeenCalledExactlyOnceWith(test.pane.id, { + focus: false + }) + expect(document.activeElement).toBe(test.input) + expect(test.input.selectionStart).toBe(8) + expect(test.input.value).toBe('existing suffix') + const writer = acceptance === undefined ? test.sendInput : test.accepted + expect(writer).toHaveBeenCalledExactlyOnceWith('Worker (Orca agent term_worker) ', 'driving') + expect(toast.error).not.toHaveBeenCalled() + resetFixture() + vi.clearAllMocks() } - useAppStore.setState(initialStore, true) - vi.restoreAllMocks() - vi.clearAllMocks() }) +it('mentions into a restored pane whose terminal connects after the panel first rendered', async () => { + const test = mount({ acceptance: true, restored: true }) + fireEvent.click( + within(test.first.container).getByRole('button', { name: /^Show orchestration: 1 worker,/ }) + ) + // The transport binds without any React update, as a restored pane's reattach does. + test.link.connected = true + await act(async () => + fireEvent.click(within(test.first.container).getByRole('button', { name: 'Mention all' })) + ) + expect(test.accepted).toHaveBeenCalledExactlyOnceWith( + 'Worker (Orca agent term_worker) ', + 'driving' + ) +}) + +it.each(['retired pane', 'disconnected terminal'] as const)( + 'refuses an invocation into a %s without focusing or writing', + async (kind) => { + const test = fixture(true) + if (kind === 'retired pane') { + test.manager.createInitialPane({ focus: false }) + test.manager.retirePanePreservingPty(test.pane.id) + } else { + test.link.connected = false + } + vi.mocked(test.manager.setActivePane).mockClear() + const focus = vi.mocked(test.pane.terminal.focus) + focus.mockClear() + await act(async () => test.mention()) + expect(test.accepted).not.toHaveBeenCalled() + expect(test.sendInput).not.toHaveBeenCalled() + expect(test.manager.setActivePane).not.toHaveBeenCalled() + expect(focus).not.toHaveBeenCalled() + expect(toast.error).toHaveBeenCalledExactlyOnceWith( + 'The terminal did not accept the agent reference. Try again.' + ) + } +) + it('mounts no pane panel, identity lookup or crew read while the setting is off, live both ways', () => { useAppStore.setState({ settings: { ...getDefaultSettings('/home/test'), experimentalOrchestrationPanel: false } @@ -161,7 +384,7 @@ it('retires only the hidden menu before deferred physical close and never replay const { controller, first, update } = mount() const pane = within(first.container) await user.click(pane.getByRole('button', { name: /^Show orchestration: 1 worker,/ })) - const disclosure = pane.getByRole('button', { name: /Worker Keep this disclosure/ }) + const disclosure = pane.getByRole('button', { name: "Show Worker's task and latest message" }) await user.click(disclosure) const oldMore = pane.getByRole('button', { name: 'More for Worker' }) await user.click(oldMore) diff --git a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx index cf83a12351bc..6ba7b5932d00 100644 --- a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx +++ b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx @@ -1,16 +1,24 @@ import { createPortal } from 'react-dom' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' import type { ManagedPane } from '@/lib/pane-manager/pane-manager' import type { TerminalPaneController } from '../terminal-pane/use-terminal-pane-controller' import { makePaneKey } from '../../../../shared/stable-pane-id' +import { + captureTerminalDropTarget, + getCurrentTerminalDropTransport +} from '../terminal-pane/terminal-drop-target' +import { insertTerminalCrewMention } from '../terminal-pane/terminal-crew-mention' import { useTerminalCrewIdentity } from './use-terminal-crew-identity' import { LazyOrchestrationCrewPanel } from './LazyOrchestrationCrewPanel' import { useOrchestrationPanelEnabled } from './use-orchestration-panel-enabled' -type CrewPortalController = Pick< +type CrewPaneController = Pick< TerminalPaneController, | 'tabId' | 'worktreeId' + | 'managerRef' | 'paneTransportsRef' | 'isRendererVisible' | 'expandedPaneId' @@ -25,9 +33,9 @@ function TerminalCrewPortal({ controller }: { pane: ManagedPane - controller: CrewPortalController + controller: CrewPaneController }) { - const { tabId, worktreeId, paneTransportsRef } = controller + const { tabId, worktreeId, managerRef, paneTransportsRef } = controller const paneKey = makePaneKey(tabId, pane.leafId) const boundPtyId = useAppStore( (state) => state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[pane.leafId] ?? null @@ -41,6 +49,7 @@ function TerminalCrewPortal({ if (!target || !party || !transport) { return null } + const hostKey = target.kind === 'local' ? 'local' : target.environmentId return createPortal( { + const manager = managerRef.current + const live = paneTransportsRef.current.get(pane.id) + const references = rows.flatMap((row) => + row.sendAddress ? [{ label: row.label, address: row.sendAddress, hostKey }] : [] + ) + if (manager) { + const rejected = () => + toast.error( + translate( + 'components.orchestrationCrew.mentionRejected', + 'The terminal did not accept the agent reference. Try again.' + ) + ) + const captured = live && captureTerminalDropTarget(pane, live) + if ( + !captured || + !pane.container.isConnected || + !getCurrentTerminalDropTransport(manager, paneTransportsRef.current, captured) + ) { + rejected() + return + } + manager.setActivePane(captured.paneId, { focus: false }) + pane.terminal.focus() + void insertTerminalCrewMention( + manager, + paneTransportsRef.current, + captured, + references + ).then((accepted) => { + if (!accepted) { + rejected() + } + }, rejected) + } + }} />, pane.container, `crew-${pane.id}` ) } -export function TerminalCrewPortals({ controller }: { controller: CrewPortalController }) { +export function TerminalCrewPortals({ controller }: { controller: CrewPaneController }) { // Gate before any pane mounts: an off panel resolves no identities and opens no subscriptions. const enabled = useOrchestrationPanelEnabled() if (!enabled) { diff --git a/src/renderer/src/components/terminal-pane/terminal-crew-mention.ts b/src/renderer/src/components/terminal-pane/terminal-crew-mention.ts new file mode 100644 index 000000000000..a3ec445b12c7 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-crew-mention.ts @@ -0,0 +1,25 @@ +import type { PaneManager } from '@/lib/pane-manager/pane-manager' +import { + terminalAgentReference, + type OrchestrationAgentReference +} from '../../../../shared/orchestration-agent-reference' +import { + getCurrentTerminalDropTransport, + type CapturedTerminalDropTarget +} from './terminal-drop-target' +import { writeTerminalPastePtyInput } from './terminal-pty-paste-writer' +import type { PtyTransport } from './pty-transport-types' + +export async function insertTerminalCrewMention( + manager: PaneManager, + transports: Map, + target: CapturedTerminalDropTarget, + references: OrchestrationAgentReference[] +): Promise { + const parts = references.map(terminalAgentReference) + if (parts.length === 0 || parts.some((part) => part === null)) { + return false + } + const transport = getCurrentTerminalDropTransport(manager, transports, target) + return transport ? await writeTerminalPastePtyInput(transport, parts.join(''), 'driving') : false +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3c59a806ece0..0ff323d6f0e0 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20855,6 +20855,10 @@ "stepCheck": "Check" }, "orchestrationCrew": { + "mentionAll": "Mention all", + "mentionAgent": "Mention {{name}}:", + "mentionInMessage": "Mention in message", + "mentionRejected": "The terminal did not accept the agent reference. Try again.", "title": "Orchestration", "sendingUnavailable": "Sending unavailable", "workers_one": "{{count}} worker", diff --git a/src/renderer/src/lib/pane-manager/pane-manager-host.ts b/src/renderer/src/lib/pane-manager/pane-manager-host.ts index 3a4cd8909e34..8d557d163b4a 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-host.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-host.ts @@ -1,5 +1,6 @@ import type { ManagedPaneInternal, + PaneActivationOptions, PaneManagerOptions, PaneStyleOptions } from './pane-manager-types' @@ -25,7 +26,7 @@ export type PaneManagerHost = { spawnHints?: Parameters>[1] ) => void getDragCallbacks: () => DragReorderCallbacks - setActivePane: (paneId: number, opts?: { focus?: boolean }) => void + setActivePane: (paneId: number, opts?: PaneActivationOptions) => void setActivePaneId: (paneId: number | null) => void requestPaneReparentFrame: (callback: FrameRequestCallback) => void } diff --git a/src/renderer/src/lib/pane-manager/pane-manager-pane-creation.ts b/src/renderer/src/lib/pane-manager/pane-manager-pane-creation.ts index 030757dafc09..4325c34bfdb6 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-pane-creation.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-pane-creation.ts @@ -1,12 +1,41 @@ import { focusPanePreservingOverlays } from './pane-overlay-focus' -import type { ManagedPane, ManagedPaneInternal, PaneManagerOptions } from './pane-manager-types' +import type { + ManagedPane, + ManagedPaneInternal, + PaneManagerOptions, + PaneActivationOptions +} from './pane-manager-types' import type { PaneManagerHost } from './pane-manager-host' -import { applyPaneOpacity } from './pane-divider' +import { applyPaneOpacity, applyDividerStyles, applyRootBackground } from './pane-divider' import { createPaneDOM, openTerminal } from './pane-lifecycle' import { suspendTerminalCursorBlink } from './pane-cursor-blink-suspension' import { shouldFollowMouseFocus } from './focus-follows-mouse' import { toPublicPane } from './pane-public-view' +export function applyManagedPaneStyles(host: PaneManagerHost): void { + applyPaneOpacity(host.panes.values(), host.getActivePaneId(), host.getStyleOptions()) + applyDividerStyles(host.root, host.getStyleOptions()) + applyRootBackground(host.root, host.getStyleOptions()) +} + +export function activateManagedPane( + host: PaneManagerHost, + pane: ManagedPaneInternal, + opts?: PaneActivationOptions +): void { + const changed = host.getActivePaneId() !== pane.id + host.setActivePaneId(pane.id) + applyPaneOpacity(host.panes.values(), host.getActivePaneId(), host.getStyleOptions()) + + if (opts?.focus !== false) { + focusPanePreservingOverlays(pane) + } + + if (changed) { + host.options.onActivePaneChange?.(toPublicPane(pane)) + } +} + export function createInitialManagedPane( host: PaneManagerHost, opts?: { focus?: boolean; leafId?: string } @@ -49,7 +78,9 @@ export function createManagedPaneInternal( // Refocus even when already active: browser textarea focus can lag activePaneId after splits. (paneId, options) => { if (!host.isDestroyed()) { - host.setActivePane(paneId, { focus: options?.focusTerminal !== false }) + host.setActivePane(paneId, { + focus: options?.focusTerminal !== false + }) } }, (paneId, event) => { diff --git a/src/renderer/src/lib/pane-manager/pane-manager-spawn-placement.test.ts b/src/renderer/src/lib/pane-manager/pane-manager-spawn-placement.test.ts index d3d871f3ab5b..9247871d6729 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-spawn-placement.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-spawn-placement.test.ts @@ -18,6 +18,7 @@ const LEAF_C = '33333333-3333-4333-8333-333333333333' describe('PaneManager spawn placement hints', () => { let root: HTMLDivElement let onPaneCreated: Mock> + let onActivePaneChange: Mock> let manager: InstanceType beforeEach(() => { @@ -26,13 +27,15 @@ describe('PaneManager spawn placement hints', () => { root = document.createElement('div') document.body.appendChild(root) onPaneCreated = vi.fn() - manager = new PaneManager(root, { linkOpenHint: () => '', onPaneCreated }) + onActivePaneChange = vi.fn() + manager = new PaneManager(root, { linkOpenHint: () => '', onPaneCreated, onActivePaneChange }) }) afterEach(() => { manager.destroy() root.remove() vi.unstubAllGlobals() + vi.restoreAllMocks() }) it('publishes a split placed before a mounted subtree with its final order', () => { diff --git a/src/renderer/src/lib/pane-manager/pane-manager-types.ts b/src/renderer/src/lib/pane-manager/pane-manager-types.ts index fce93dec2c7b..e5f07de3908b 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager-types.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager-types.ts @@ -14,6 +14,8 @@ import type { TerminalWebglAutoDecision } from './terminal-webgl-auto-policy' export type { TerminalScrollIntentTarget } from './terminal-scroll-intent' +export type PaneActivationOptions = { focus?: boolean } + /** One-shot spawn/adoption hints belong to creation, separate from persistent ManagedPane state. */ export type PaneSpawnHints = { cwd?: string diff --git a/src/renderer/src/lib/pane-manager/pane-manager.ts b/src/renderer/src/lib/pane-manager/pane-manager.ts index 5c15b31abdb4..bfffe9001586 100644 --- a/src/renderer/src/lib/pane-manager/pane-manager.ts +++ b/src/renderer/src/lib/pane-manager/pane-manager.ts @@ -1,20 +1,15 @@ -import { focusPanePreservingOverlays } from './pane-overlay-focus' import type { PaneManagerOptions, PaneStyleOptions, ManagedPane, ManagedPaneInternal, PaneRenderingDiagnostics, - DropZone + DropZone, + PaneActivationOptions } from './pane-manager-types' import type { SplitPaneAroundLeafIdsOptions } from './pane-subtree-split' import type { PaneManagerHost } from './pane-manager-host' -import { - applyDividerStyles, - applyPaneOpacity, - applyRootBackground, - disposeDividersIn -} from './pane-divider' +import { disposeDividersIn } from './pane-divider' import { cancelActivePaneDrag, createDragReorderState, handlePaneDrop } from './pane-drag-reorder' import { beginPaneDragFromPointerDown } from './pane-drag-pointer' import { setLigaturesEnabled, disposePane } from './pane-lifecycle' @@ -46,6 +41,8 @@ import { splitPaneOnManager } from './pane-manager-tree-mutations' import { + activateManagedPane, + applyManagedPaneStyles, createInitialManagedPane, createManagedPaneInternal, publishManagedPaneCreated @@ -223,29 +220,17 @@ export class PaneManager { return this.identities.adoptPaneLeafId(numericPaneId, pane, leafId) } - setActivePane(paneId: number, opts?: { focus?: boolean }): void { + setActivePane(paneId: number, opts?: PaneActivationOptions): void { const pane = this.panes.get(paneId) if (!pane) { return } - const changed = this.activePaneId !== paneId - this.activePaneId = paneId - applyPaneOpacity(this.panes.values(), this.activePaneId, this.styleOptions) - - if (opts?.focus !== false) { - focusPanePreservingOverlays(pane) - } - - if (changed) { - this.options.onActivePaneChange?.(toPublicPane(pane)) - } + activateManagedPane(this.host, pane, opts) } setPaneStyleOptions(opts: PaneStyleOptions): void { this.styleOptions = { ...opts } - applyPaneOpacity(this.panes.values(), this.activePaneId, this.styleOptions) - applyDividerStyles(this.root, this.styleOptions) - applyRootBackground(this.root, this.styleOptions) + applyManagedPaneStyles(this.host) } private withPane(paneId: number, apply: (pane: ManagedPaneInternal) => T): T | undefined { diff --git a/src/renderer/src/lib/pane-manager/pane-overlay-focus.test.ts b/src/renderer/src/lib/pane-manager/pane-overlay-focus.test.ts index d335ce829a46..7ba5d03db28e 100644 --- a/src/renderer/src/lib/pane-manager/pane-overlay-focus.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-overlay-focus.test.ts @@ -31,23 +31,43 @@ function fixture() { const panes = new Map([[pane.id, pane]]) const publishPaneCreated = vi.fn() const onActivePaneChange = vi.fn() + function unexpectedHostOperation(): never { + throw new Error('Unexpected host operation in overlay focus fixture') + } + const options = { onActivePaneChange, linkOpenHint: unexpectedHostOperation } const manager = Object.create(PaneManager.prototype) as PaneManager Object.assign(manager, { panes, activePaneId: null, styleOptions: {}, - options: { onActivePaneChange } + options }) - const host = { - options: {}, + const host: PaneManagerHost = { + options, root, panes, + get identities() { + return unexpectedHostOperation() + }, + get dragState() { + return unexpectedHostOperation() + }, + isDestroyed: unexpectedHostOperation, + isRenderingSuspended: unexpectedHostOperation, + allocatePaneId: unexpectedHostOperation, + createDivider: unexpectedHostOperation, + getDragCallbacks: unexpectedHostOperation, + setActivePane: (paneId, opts) => manager.setActivePane(paneId, opts), + requestPaneReparentFrame: unexpectedHostOperation, createPaneInternal: () => pane, - setActivePaneId: vi.fn(), - getActivePaneId: () => pane.id, + setActivePaneId: vi.fn((activePaneId: number | null) => { + Object.assign(manager, { activePaneId }) + }), + getActivePaneId: () => manager.getActivePane()?.id ?? null, getStyleOptions: () => ({}), publishPaneCreated - } as unknown as PaneManagerHost + } + Object.assign(manager, { host }) return { root, container, textarea, pane, host, manager, publishPaneCreated, onActivePaneChange } } diff --git a/src/shared/orchestration-agent-reference.test-fixture.ts b/src/shared/orchestration-agent-reference.test-fixture.ts new file mode 100644 index 000000000000..f1a10a4ee18a --- /dev/null +++ b/src/shared/orchestration-agent-reference.test-fixture.ts @@ -0,0 +1,2 @@ +export const agentReferenceDeliveryText = + 'Hello @Same name (2) @Same name (3) @"/tmp/Same name (1).txt"\n\n[Orca agent "Same name (2)": term_first — message it with orca orchestration send --to term_first]\n[Orca agent "Same name (3)": dispatch:ctx_second — message it with orca orchestration send --to dispatch:ctx_second]' diff --git a/src/shared/orchestration-agent-reference.ts b/src/shared/orchestration-agent-reference.ts index de75c73bfcd7..e56eec1cfeb3 100644 --- a/src/shared/orchestration-agent-reference.ts +++ b/src/shared/orchestration-agent-reference.ts @@ -1,8 +1,41 @@ import { parseOrcaSessionAddress } from './orca-session-address' +export type OrchestrationAgentReference = { label: string; address: string; hostKey: string } + export function isPublicOrchestrationAddress(address: string): boolean { return ( /^(?:term_[a-zA-Z0-9_-]+|(?:dispatch|run):[a-zA-Z0-9_-]+)$/.test(address) || parseOrcaSessionAddress(address) !== null ) } + +export function printableAgentLabel(label: string): string { + return [...label.replace(/[\r\n\u2028\u2029]/g, ' ')] + .filter( + (char) => + char.charCodeAt(0) >= 32 && !(char.charCodeAt(0) >= 127 && char.charCodeAt(0) <= 159) + ) + .join('') +} + +// Every printed reference carries this; a draft without it holds no agent reference. +const AGENT_REFERENCE_MARK = ' (Orca agent ' + +export function mayHoldAgentReferences(text: string): boolean { + return text.includes(AGENT_REFERENCE_MARK) +} + +export function agentReferenceToken(reference: OrchestrationAgentReference): string { + return `@${reference.label}${AGENT_REFERENCE_MARK}${reference.address})` +} + +/** The routing line a sent message ends with, one per mentioned agent. */ +export function agentReferenceNote(label: string, address: string): string { + return `[Orca agent "${label}": ${address} — message it with orca orchestration send --to ${address}]` +} + +export function terminalAgentReference(reference: OrchestrationAgentReference): string | null { + return isPublicOrchestrationAddress(reference.address) + ? `${printableAgentLabel(reference.label)}${AGENT_REFERENCE_MARK}${reference.address}) ` + : null +}