Skip to content

The agent that grows with you

fix: stage and retain canonical Ink image submissions

Teknium33622c040958
diff --git a/ui-tui/src/__tests__/canonicalImages.test.ts b/ui-tui/src/__tests__/canonicalImages.test.ts
new file mode 100644
index 00000000000..a69df33e1d2
--- /dev/null
+++ b/ui-tui/src/__tests__/canonicalImages.test.ts
@@ -0,0 +1,84 @@
+import { randomUUID } from 'node:crypto'
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+
+import { expect, it, vi } from 'vitest'
+
+import { submitPrompt } from '../app/submissionCore.js'
+import { captureDestination } from '../app/submissionDestination.js'
+import { patchUiState, resetUiState } from '../app/uiStore.js'
+import { stageImagePath } from '../lib/imageAttachments.js'
+import { loadPendingInputs } from '../lib/pendingInputs.js'
+
+const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII=', 'base64')
+
+it('stages private immutable local bytes, uploads remote bytes, and never falls back to a client path', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-images-'))
+ vi.stubEnv('HERMES_HOME', home)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', '')
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const source = join(home, 'my shot.png')
+ writeFileSync(source, png)
+ const request = vi.fn(async () => ({ path: '/owner/cache/images/upload.png' }))
+ const gw = { request, isCanonical: true } as any
+
+ try {
+ const image = await stageImagePath(`"${source}" caption`, gw, captureDestination())
+ expect(dirname(image.path)).toBe(join(home, 'cache', 'images'))
+ expect(image).toMatchObject({ mime: 'image/png', remainder: 'caption' })
+ expect(statSync(image.path).mode & 0o777).toBe(0o600)
+ writeFileSync(source, 'changed')
+ expect(readFileSync(image.path)).toEqual(png)
+ expect(request).not.toHaveBeenCalled()
+ writeFileSync(source, png)
+ const prompt = vi.fn(async (_method: string, _params: any) => ({ status: 'started' }))
+ submitPrompt(source, { gw: { isCanonical: true, request: prompt } as any, appendMessage: vi.fn(), enqueue: vi.fn(), expand: s => s, setLastUserMsg: vi.fn(), sys: vi.fn() })
+ await vi.waitFor(() => expect(prompt).toHaveBeenCalledWith('prompt.submit', expect.objectContaining({ attachments: [{ path: expect.any(String), mime: 'image/png' }] })))
+ expect(readFileSync(prompt.mock.calls.find(([method]) => method === 'prompt.submit')![1].attachments[0].path)).toEqual(png)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', 'wss://owner.example/ws')
+ const remote = await stageImagePath(source, gw, captureDestination())
+ expect(remote.path).toBe('/owner/cache/images/upload.png')
+ expect(request).toHaveBeenCalledWith('image.attach_bytes', expect.objectContaining({
+ content_base64: png.toString('base64'), session_id: 'owner'
+ }))
+ request.mockRejectedValueOnce(new Error('upload refused'))
+ await expect(stageImagePath(source, gw, captureDestination())).rejects.toThrow('upload refused')
+ writeFileSync(source, 'not an image')
+ await expect(stageImagePath(source, gw, captureDestination())).rejects.toThrow(/image/i)
+ } finally { resetUiState(); vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) }
+})
+
+it('journals canonical attachment payload before sending and replays it unchanged after a lost acknowledgement', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-image-retry-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ patchUiState({ sid: 'owner' })
+ const destination = captureDestination()
+ const attachments = [{ path: join(home, 'cache/images/shot.png'), mime: 'image/png' }]
+ const item = { text: 'caption', display: 'caption [[ Image 1 ]]', attachments, submissionId: randomUUID(), destination, inFlight: true }
+ const wires: any[] = []
+
+ const request = vi.fn(async (method, params) => {
+ expect(method).toBe('prompt.submit')
+ const retained = loadPendingInputs(destination)[0]!
+ expect(retained.attachments).toEqual(attachments)
+ wires.push(params)
+ throw new Error('lost acknowledgement')
+ })
+
+ const deps = { gw: { isCanonical: true, request } as any, appendMessage: vi.fn(), enqueue: vi.fn(), expand: (s: string) => s, setLastUserMsg: vi.fn(), sys: vi.fn() }
+
+ try {
+ submitPrompt(item.text, deps, true, item.display, { skipDetectDrop: true, queueItem: item })
+ await new Promise(resolve => setImmediate(resolve))
+ const recovered = loadPendingInputs(destination)[0]!
+ expect(recovered.attachments).toEqual(attachments)
+ submitPrompt(recovered.text, deps, true, recovered.display, { queueItem: recovered })
+ await new Promise(resolve => setImmediate(resolve))
+ expect(wires).toHaveLength(2)
+ expect(wires[0]).toEqual(wires[1])
+ expect(wires[0].attachments).toEqual(attachments)
+ } finally { resetUiState(); vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) }
+})
diff --git a/ui-tui/src/app/interfaces.ts b/ui-tui/src/app/interfaces.ts
index c41cdb3c217..83d971d69d2 100644
--- a/ui-tui/src/app/interfaces.ts
+++ b/ui-tui/src/app/interfaces.ts
@@ -659,5 +659,5 @@ export interface AppOverlaysProps {
* path, used to detach the image when its token is deleted.
*/
export type ComposerToken =
- | { index: number; kind: 'image'; label: string; path: string; text?: undefined }
+ | { index: number; kind: 'image'; label: string; path: string; mime?: string; text?: undefined }
| { index?: undefined; kind: 'paste'; label: string; path?: string; text: string }
diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.ts
index 74354f4eade..82c18a8fedb 100644
--- a/ui-tui/src/app/submissionCore.ts
+++ b/ui-tui/src/app/submissionCore.ts
@@ -1,6 +1,7 @@
import type { GatewayClient } from '../gatewayClient.js'
import type { InputDetectDropResponse, PromptSubmitResponse, SessionActivateResponse } from '../gatewayTypes.js'
import type { QueueItem } from '../hooks/useQueue.js'
+import { stageImagePath } from '../lib/imageAttachments.js'
import { pendingInputOwner, savePendingInput } from '../lib/pendingInputs.js'
import type { Msg } from '../types.js'
@@ -54,7 +55,7 @@ export function submitPrompt(
deps: SubmitPromptDeps,
showUserMessage = true,
displayOverride?: string,
- opts: { skipDetectDrop?: boolean; destination?: SubmissionDestination; queueItem?: QueueItem; behindTurn?: boolean } = {}
+ opts: { attachments?: Array<{ path: string; mime: string }>; skipDetectDrop?: boolean; destination?: SubmissionDestination; queueItem?: QueueItem; behindTurn?: boolean } = {}
): void {
const destination = opts.destination ?? captureDestination()
const owner = pendingInputOwner(opts.queueItem?.ownerDestination ?? destination)
@@ -104,6 +105,7 @@ export function submitPrompt(
if (item) {
item.preparedText ??= submitText
+ item.attachments ??= opts.attachments?.map(attachment => ({ ...attachment }))
if (opts.behindTurn) { item.queued = true }
@@ -115,6 +117,7 @@ export function submitPrompt(
.request<PromptSubmitResponse>('prompt.submit', {
session_id: sid,
text: item?.preparedText ?? submitText,
+ ...((item?.attachments ?? opts.attachments)?.length ? { attachments: item?.attachments ?? opts.attachments } : {}),
...(item ? { submission_id: item.submissionId, queued: item.queued !== false } : {})
})
.then(r => {
@@ -177,7 +180,7 @@ export function submitPrompt(
// 4094 is a pre-admission refusal, not an ambiguous write. Special
// compute modes still support legacy submit; retry only this refusal,
// keeping the prepared payload, destination and queue mode unchanged.
- if (item && e.code === 4094) {
+ if (item && e.code === 4094 && !deps.gw.isCanonical && !item.attachments?.length) {
if (focused()) {deps.sys('durable admission unavailable for this session — using legacy delivery')}
try {
@@ -265,6 +268,27 @@ export function submitPrompt(
return startSubmit(text, deps.expand(text), showUserMessage)
}
+ if (deps.gw.isCanonical) {
+ if (/^(?:["']?(?:[/.~]|[A-Za-z]:[/\\])|file:\/\/)/.test(text) && /\.(?:png|jpe?g|gif|webp)(?:["']?)(?:\s|$)/i.test(text)) {
+ void stageImagePath(text, deps.gw, destination).then(image => {
+ opts.attachments = [{ path: image.path, mime: image.mime }]
+ startSubmit(text, image.remainder || 'What do you see in this image?', showUserMessage)
+ }).catch((error: Error) => {
+ opts.queueItem?.settle?.(false)
+
+ if (focused()) {
+ deps.sys(`image not submitted: ${error.message} — input retained`)
+
+ if (ownsTurn()) { patchUiState({ busy: false, status: 'image not submitted' }) }
+ }
+ })
+
+ return
+ }
+
+ return startSubmit(text, deps.expand(text), showUserMessage)
+ }
+
deps.gw
.request<InputDetectDropResponse>('input.detect_drop', { session_id: sid, text })
.then(r => {
diff --git a/ui-tui/src/app/useComposerState.ts b/ui-tui/src/app/useComposerState.ts
index c4d23db7fdb..b56fd664fa8 100644
--- a/ui-tui/src/app/useComposerState.ts
+++ b/ui-tui/src/app/useComposerState.ts
@@ -15,6 +15,7 @@ import { useInputHistory } from '../hooks/useInputHistory.js'
import { useQueue } from '../hooks/useQueue.js'
import { isUsableClipboardText, readClipboardText } from '../lib/clipboard.js'
import { resolveEditor } from '../lib/editor.js'
+import { stageImagePath } from '../lib/imageAttachments.js'
import { readOsc52Clipboard } from '../lib/osc52.js'
import { isRemoteShellSession } from '../lib/terminalSetup.js'
import { pasteTokenLabel, stripTrailingPasteNewlines } from '../lib/text.js'
@@ -179,7 +180,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
}
for (const token of gone) {
- if (token.kind === 'image') {
+ if (token.kind === 'image' && !gw.isCanonical) {
void gw.request('image.detach', { path: token.path, session_id: getUiState().sid }).catch(() => {})
}
}
@@ -195,11 +196,11 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
* of `~/shot.png look at this` keeps the caption).
*/
const attachImageToken = useCallback(
- (attached: ImageAttachResponse & { path?: string }, value: string, cursor: number): ComposerPasteResult => {
+ (attached: ImageAttachResponse & { path?: string; mime?: string }, value: string, cursor: number): ComposerPasteResult => {
const index = nextImageIndex(tokensRef.current)
const label = imageToken(index)
- setComposerTokens(prev => trimTokens([...prev, { index, kind: 'image', label, path: attached.path ?? '' }]))
+ setComposerTokens(prev => trimTokens([...prev, { index, kind: 'image', label, path: attached.path ?? '', ...(attached.mime ? { mime: attached.mime } : {}) }]))
const withToken = insertAtCursor(value, cursor, label)
const remainder = attached.remainder?.trim() ?? ''
@@ -228,7 +229,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return accept(attached)
}
- if (attached?.path) {
+ if (attached?.path && !gw.isCanonical) {
staleAttachments.current.push({ destination, path: attached.path })
}
@@ -307,10 +308,11 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
if (sid && looksLikeDroppedPath(cleanedText)) {
try {
- const next = await resolveAttachment(
+ const next = await resolveAttachment<ImageAttachResponse & { path?: string; mime?: string }>(
destination,
revision,
- gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path: cleanedText, session_id: sid }),
+ gw.isCanonical ? stageImagePath(cleanedText, gw, destination)
+ : gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path: cleanedText, session_id: sid }),
attached => attached?.name ? attachImageToken(attached, value, cursor) : null
)
@@ -455,10 +457,11 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return null
}
- return resolveAttachment(
+ return resolveAttachment<ImageAttachResponse & { path?: string; mime?: string }>(
destination,
revision,
- gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path, session_id: sid })
+ (gw.isCanonical ? stageImagePath(path, gw, destination)
+ : gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path, session_id: sid }))
.catch((e: Error) => {
if (isCurrentDestination(destination) && revision === composerRevision.current) {
sys(`error: ${e.message}`)
diff --git a/ui-tui/src/domain/attachments.ts b/ui-tui/src/domain/attachments.ts
index 7894cf170a0..1a80067066c 100644
--- a/ui-tui/src/domain/attachments.ts
+++ b/ui-tui/src/domain/attachments.ts
@@ -1,4 +1,5 @@
import type { ComposerToken } from '../app/interfaces.js'
+import type { ImageAttachment } from '../lib/imageAttachments.js'
import { PASTE_SNIPPET_RE } from '../protocol/paste.js'
/**
@@ -15,6 +16,10 @@ import { PASTE_SNIPPET_RE } from '../protocol/paste.js'
*/
export const imageToken = (index: number) => `[[ Image ${index} ]]`
+export const imageAttachments = (value: string, tokens: ComposerToken[]): ImageAttachment[] =>
+ tokens.flatMap(token => token.kind === 'image' && token.mime && value.includes(token.label)
+ ? [{ path: token.path, mime: token.mime }] : [])
+
/** Highest image token index handed out so far, so a new one never collides. */
export const nextImageIndex = (tokens: ComposerToken[]) =>
tokens.reduce((max, t) => (t.kind === 'image' ? Math.max(max, t.index) : max), 0) + 1
@@ -32,8 +37,8 @@ export const droppedTokens = (tokens: ComposerToken[], value: string) => {
* Repeated identical labels expand in submission order (left to right), which
* is why this walks matches instead of doing a global replace per token.
*
- * An image token expands to nothing: the gateway already holds the file in
- * `session.attached_images` and splices the real vision content in at submit.
+ * An image token expands to nothing: its staged path and MIME travel in the
+ * identified prompt's attachments payload, independently of display text.
* The token's job was to show the user where it landed, so it also eats one
* adjacent space to avoid leaving a gap in the middle of a sentence.
*/
diff --git a/ui-tui/src/lib/imageAttachments.ts b/ui-tui/src/lib/imageAttachments.ts
new file mode 100644
index 00000000000..3e0962140d2
--- /dev/null
+++ b/ui-tui/src/lib/imageAttachments.ts
@@ -0,0 +1,97 @@
+import { randomUUID } from 'node:crypto'
+import { mkdir, open, readFile, stat } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import { basename, join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import type { SubmissionDestination } from '../app/submissionDestination.js'
+import type { GatewayClient } from '../gatewayClient.js'
+
+export interface ImageAttachment { path: string; mime: string }
+export interface StagedImage extends ImageAttachment { name: string; remainder?: string }
+
+const MAX_IMAGE_BYTES = 20 * 1024 * 1024
+
+function imageFormat(bytes: Buffer): { mime: string; ext: string } {
+ if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
+ return { mime: 'image/png', ext: '.png' }
+ }
+
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
+ return { mime: 'image/jpeg', ext: '.jpg' }
+ }
+
+ if (/^GIF8[79]a$/.test(bytes.subarray(0, 6).toString('ascii'))) {
+ return { mime: 'image/gif', ext: '.gif' }
+ }
+
+ if (bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP') {
+ return { mime: 'image/webp', ext: '.webp' }
+ }
+
+ throw new Error('Unsupported image: expected PNG, JPEG, GIF, or WebP bytes')
+}
+
+// Match an existing whole path first, so unquoted filenames with spaces survive.
+async function resolveImagePath(raw: string): Promise<{ path: string; remainder: string }> {
+ const value = raw.trim()
+ const quoted = /^(["'])(.*?)\1(?:\s+([\s\S]*))?$/.exec(value)
+
+ const candidates = quoted ? [[quoted[2]!, quoted[3] ?? '']] : [
+ [value, ''],
+ ...[...value.matchAll(/\s+/g)].reverse().map(match => [value.slice(0, match.index), value.slice(match.index).trim()])
+ ]
+
+ for (const [candidate, remainder] of candidates) {
+ let path = candidate!.replace(/\\([ ()'"[\]])/g, '$1')
+
+ if (path.startsWith('file://')) { path = fileURLToPath(path) }
+
+ if (path.startsWith('~/')) { path = join(homedir(), path.slice(2)) }
+ path = resolve(path)
+
+ try {
+ const info = await stat(path)
+
+ if (!info.isFile()) { continue }
+
+ if (info.size > MAX_IMAGE_BYTES) { throw new Error('Image exceeds 20 MiB upload limit') }
+
+ return { path, remainder: remainder! }
+ } catch (error) {
+ if (!['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) { throw error }
+ }
+ }
+
+ throw new Error(`Image not found: ${value}`)
+}
+
+export async function stageImagePath(raw: string, gw: GatewayClient, destination: SubmissionDestination): Promise<StagedImage> {
+ const source = await resolveImagePath(raw)
+ const bytes = await readFile(source.path)
+
+ if (bytes.length > MAX_IMAGE_BYTES) { throw new Error('Image exceeds 20 MiB upload limit') }
+ const { mime, ext } = imageFormat(bytes)
+ const name = basename(source.path)
+
+ // Explicit URL attachments may target another machine, even a loopback SSH
+ // tunnel. Only discovery-owned local connections share our profile filesystem.
+ if (process.env.HERMES_TUI_GATEWAY_URL?.trim()) {
+ const result = await gw.request<{ path?: string }>('image.attach_bytes', {
+ session_id: destination.sid, filename: `${randomUUID()}${ext}`, content_base64: bytes.toString('base64')
+ })
+
+ if (!result?.path) { throw new Error('Image upload did not return an owner path') }
+
+ return { path: result.path, mime, name, remainder: source.remainder }
+ }
+
+ const directory = join(destination.profileHome, 'cache', 'images')
+ await mkdir(directory, { recursive: true, mode: 0o700 })
+ const path = join(directory, `${randomUUID()}${ext}`)
+ const file = await open(path, 'wx', 0o600)
+
+ try { await file.writeFile(bytes); await file.sync() } finally { await file.close() }
+
+ return { path, mime, name, remainder: source.remainder }
+}
diff --git a/ui-tui/src/lib/pendingInputs.ts b/ui-tui/src/lib/pendingInputs.ts
index ad9d713d67b..c0bc3e8bb3e 100644
--- a/ui-tui/src/lib/pendingInputs.ts
+++ b/ui-tui/src/lib/pendingInputs.ts
@@ -94,7 +94,7 @@ export function savePendingInput(item: QueueItem): void {
const path = join(dir, `${item.submissionId}.json`)
const temporary = `${path}.${process.pid}.tmp`
const ownerDestination = pendingInputOwner(item.ownerDestination ?? item.destination)
- const { submissionId, display, text, preparedText, inFlight, failed, createdAt, queued, legacyAttempted } = item
+ const { submissionId, display, text, preparedText, attachments, inFlight, failed, createdAt, queued, legacyAttempted } = item
const destination = inFlight || failed ? item.destination : ownerDestination
writeFileSync(
temporary,
@@ -105,6 +105,7 @@ export function savePendingInput(item: QueueItem): void {
display,
text,
preparedText,
+ attachments,
legacyAttempted,
createdAt,
queued,