Skip to content

The agent that grows with you

fix: preserve Ink slash attachments and reconcile stale images

Tekniumdbc7ffa80c3a
diff --git a/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx b/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx
new file mode 100644
index 00000000000..ad47051f15f
--- /dev/null
+++ b/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx
@@ -0,0 +1,151 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough } from 'node:stream'
+
+import { renderSync, Text } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { createSlashHandler } from '../app/createSlashHandler.js'
+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'
+import { useComposerState } from '../app/useComposerState.js'
+import { useSubmission } from '../app/useSubmission.js'
+
+const flush = () => new Promise<void>(resolve => setImmediate(resolve))
+
+function mount() {
+ const home = mkdtempSync(join(tmpdir(), 'ink-slash-attachment-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const images = new Map<string, string[]>()
+ const pending: Array<{ sid: string; finish: (path: string) => void }> = []
+ const request = vi.fn((method: string, params: any) => {
+ if (method === 'image.attach' || method === 'clipboard.paste') {
+ return new Promise(resolve => {
+ pending.push({ sid: params.session_id, finish(path) {
+ images.set(params.session_id, [...(images.get(params.session_id) ?? []), path])
+ resolve({ attached: true, name: 'image.png', path })
+ } })
+ })
+ }
+ if (method === 'image.detach') {
+ images.set(params.session_id, (images.get(params.session_id) ?? []).filter(path => path !== params.path))
+ } else if (!method.startsWith('complete.')) {
+ throw new Error(`Unexpected RPC: ${method}`)
+ }
+
+ return Promise.resolve({})
+ })
+ const gw = { request } as any
+ const submitRef = { current: (_value: string) => {} }
+ const slashRef = { current: (_value: string) => false }
+ const slashFlightRef = { current: 0 }
+ const sys = vi.fn()
+ let composer!: ReturnType<typeof useComposerState>
+ let submission!: ReturnType<typeof useSubmission>
+ const stdout = Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false })
+ let output = ''
+ stdout.on('data', chunk => { output += chunk.toString() })
+
+ function Harness() {
+ composer = useComposerState({ gw, submitRef, sys })
+ submission = useSubmission({ gw, submitRef, slashRef, sys, composerActions: composer.actions,
+ composerRefs: composer.refs, composerState: composer.state, appendMessage: vi.fn(), setLastUserMsg: vi.fn() })
+ slashRef.current = createSlashHandler({ gateway: { gw }, local: {}, transcript: { sys },
+ composer: composer.actions, slashFlightRef } as any)
+
+ return <Text>{composer.state.input}</Text>
+ }
+
+ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any, stdout: stdout as any,
+ stderr: new PassThrough() as any, patchConsole: false })
+
+ return {
+ images, pending, request,
+ get composer() { return composer },
+ get output() { return output },
+ async submit(command: string) {
+ composer.actions.setInput(command)
+ await flush()
+ submission.submit(command)
+ await flush()
+ },
+ close() {
+ instance.unmount()
+ instance.cleanup()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ }
+ }
+}
+
+it('slash attachment submission leaves a visible removable image in the cleared composer', async () => {
+ for (const command of ['/image /owned.png', '/paste']) {
+ const h = mount()
+ try {
+ await h.submit(command)
+ expect(h.pending).toHaveLength(1)
+ expect(h.composer.state.input).toBe('')
+ h.pending[0]!.finish('/owned.png')
+ await flush()
+ expect(h.composer.state.input).toContain('[[ Image 1 ]]')
+ expect(h.output).toContain('[[ Image 1 ]]')
+ expect(h.composer.refs.tokensRef.current).toEqual([
+ expect.objectContaining({ kind: 'image', path: '/owned.png' })
+ ])
+ expect(h.images.get('owner')).toEqual(['/owned.png'])
+ h.composer.actions.syncTokens('')
+ h.composer.actions.setInput('')
+ await flush()
+ expect(h.images.get('owner')).toEqual([])
+ } finally { h.close() }
+ }
+})
+
+it('stale attachment cleanup uses its captured owner and preserves a concurrent valid image', async () => {
+ for (const command of ['/image /owned.png', '/paste', 'drop']) {
+ for (const navigation of [false, true]) {
+ for (const samePath of [false, true]) {
+ for (const staleFirst of [false, true]) {
+ const h = mount()
+ try {
+ if (command === 'drop') {
+ void h.composer.actions.handleTextPaste({ text: '/owned.png', value: '', cursor: 0 })
+ } else {
+ await h.submit(command)
+ }
+ h.composer.actions.setInput('user edit')
+ if (navigation) {
+ patchUiState({ sid: 'other' })
+ h.composer.actions.clearIn()
+ }
+ await h.submit('/image /valid.png')
+ expect(h.pending).toHaveLength(2)
+ const validPath = samePath ? '/owned.png' : '/valid.png'
+ const first = staleFirst ? 0 : 1
+ h.pending[first]!.finish(first === 0 ? '/owned.png' : validPath)
+ await flush()
+ h.pending[1 - first]!.finish(first === 0 ? validPath : '/owned.png')
+ await flush()
+ const sid = getUiState().sid!
+ expect(h.composer.state.input).toBe('[[ Image 1 ]]')
+ expect(h.composer.refs.tokensRef.current).toEqual([
+ expect.objectContaining({ kind: 'image', path: validPath })
+ ])
+ expect(h.images.get(sid)).toContain(validPath)
+ const detach = h.request.mock.calls.filter(([method]) => method === 'image.detach')
+ if (samePath && !navigation) {
+ expect(detach).toEqual([])
+ } else {
+ expect(detach).toEqual([['image.detach', { session_id: 'owner', path: '/owned.png' }]])
+ expect(h.images.get('owner')).not.toContain('/owned.png')
+ }
+ } finally { h.close() }
+ }
+ }
+ }
+ }
+})
diff --git a/ui-tui/src/app/useComposerState.ts b/ui-tui/src/app/useComposerState.ts
index a4dd0300531..177b72b34a5 100644
--- a/ui-tui/src/app/useComposerState.ts
+++ b/ui-tui/src/app/useComposerState.ts
@@ -28,7 +28,7 @@ import type {
UseComposerStateResult
} from './interfaces.js'
import { $isBlocked } from './overlayStore.js'
-import { captureDestination, isCurrentDestination } from './submissionDestination.js'
+import { captureDestination, isCurrentDestination, type SubmissionDestination } from './submissionDestination.js'
import { getUiState } from './uiStore.js'
const TOKEN_MAX_COUNT = 32
@@ -206,6 +206,47 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
[setComposerTokens]
)
+ const attachmentFlights = useRef(0)
+ const staleAttachments = useRef<Array<{ destination: SubmissionDestination; path: string }>>([])
+ const resolveAttachment = useCallback(
+ async <T extends { path?: string }>(
+ destination: SubmissionDestination,
+ revision: number,
+ request: Promise<T | null>,
+ accept: (attached: T | null) => ComposerPasteResult | null
+ ): Promise<ComposerPasteResult | null> => {
+ attachmentFlights.current++
+ try {
+ const attached = await request
+
+ if (isCurrentDestination(destination) && revision === composerRevision.current) {
+ return accept(attached)
+ }
+ if (attached?.path) {
+ staleAttachments.current.push({ destination, path: attached.path })
+ }
+
+ return null
+ } finally {
+ attachmentFlights.current--
+ // Detach is path-based: wait for concurrent replies before deciding
+ // whether that path belongs to a surviving visible attachment.
+ if (!attachmentFlights.current) {
+ for (const stale of staleAttachments.current.splice(0)) {
+ if (
+ isCurrentDestination(stale.destination) &&
+ tokensRef.current.some(token => token.kind === 'image' && token.path === stale.path)
+ ) {
+ continue
+ }
+ void gw.request('image.detach', { session_id: stale.destination.sid, path: stale.path }).catch(() => {})
+ }
+ }
+ }
+ },
+ [gw]
+ )
+
/**
* Pull an image off the system clipboard into the composer as a token.
*
@@ -223,23 +264,24 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return null
}
- const r = await gw
- .request<ClipboardPasteResponse & { path?: string }>('clipboard.paste', { session_id: sid })
- .catch(() => null)
-
- if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
-
- if (r?.attached) {
- return attachImageToken(r, value, cursor)
- }
-
- if (!quiet) {
- sys(r?.message || 'No image found in clipboard')
- }
+ return resolveAttachment(
+ destination,
+ revision,
+ gw.request<ClipboardPasteResponse & { path?: string }>('clipboard.paste', { session_id: sid })
+ .catch(() => null),
+ r => {
+ if (r?.attached) {
+ return attachImageToken(r, value, cursor)
+ }
+ if (!quiet) {
+ sys(r?.message || 'No image found in clipboard')
+ }
- return null
+ return null
+ }
+ )
},
- [attachImageToken, gw, sys]
+ [attachImageToken, gw, resolveAttachment, sys]
)
const handleResolvedPaste = useCallback(
@@ -256,19 +298,15 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
if (sid && looksLikeDroppedPath(cleanedText)) {
try {
- const attached = await gw.request<ImageAttachResponse>('image.attach', {
- path: cleanedText,
- session_id: sid
- })
-
- if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
-
- if (attached?.name) {
- // Drop an `[[ Image N ]]` token where the path was typed. The old
- // path printed a notice above the status bar and left the composer
- // untouched, so the only trace of the attachment lived outside the
- // input the user was editing.
- return attachImageToken(attached, value, cursor)
+ const next = await resolveAttachment(
+ destination,
+ revision,
+ gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path: cleanedText, session_id: sid }),
+ attached => attached?.name ? attachImageToken(attached, value, cursor) : null
+ )
+
+ if (next) {
+ return next
}
} catch {
// Fall back to generic file-drop detection below.
@@ -328,7 +366,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return inserted
},
- [attachImageToken, gw, pasteClipboardImage, setComposerTokens]
+ [attachImageToken, gw, pasteClipboardImage, resolveAttachment, setComposerTokens]
)
const handleTextPaste = useCallback(
@@ -408,17 +446,21 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return null
}
- const attached = await gw
- .request<ImageAttachResponse & { path?: string }>('image.attach', { path, session_id: sid })
- .catch((e: Error) => {
- if ((isCurrentDestination(destination) && revision === composerRevision.current)) {sys(`error: ${e.message}`)}
-
- return null
- })
+ return resolveAttachment(
+ destination,
+ revision,
+ gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path, session_id: sid })
+ .catch((e: Error) => {
+ if (isCurrentDestination(destination) && revision === composerRevision.current) {
+ sys(`error: ${e.message}`)
+ }
- return (isCurrentDestination(destination) && revision === composerRevision.current) && attached?.name ? attachImageToken(attached, value, cursor) : null
+ return null
+ }),
+ attached => attached?.name ? attachImageToken(attached, value, cursor) : null
+ )
}),
- [appendAttachment, attachImageToken, gw, sys]
+ [appendAttachment, attachImageToken, gw, resolveAttachment, sys]
)
const openEditor = useCallback(async () => {
diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.ts
index 5bfb9134ca4..2697d9859d1 100644
--- a/ui-tui/src/app/useSubmission.ts
+++ b/ui-tui/src/app/useSubmission.ts
@@ -301,6 +301,9 @@ export function useSubmission(opts: UseSubmissionOptions) {
const queued =
parsed.name === 'queue' || parsed.name === 'q' ? queueItemFromSlash(slash.display, slash.command) : undefined
+ // Attachment commands capture the cleared composer's revision.
+ composerActions.clearIn()
+
if (queued) {
composerActions.enqueue(queued.text, queued.display)
sys(`queued: "${queued.display.slice(0, 50)}${queued.display.length > 50 ? '…' : ''}"`)
@@ -308,8 +311,6 @@ export function useSubmission(opts: UseSubmissionOptions) {
slashRef.current(slash.command)
}
- composerActions.clearIn()
-
return
}