Skip to content

The agent that grows with you

fix: stage clipboard images on the Ink client host

Teknium179a84734cdf
diff --git a/ui-tui/scripts/clipboard_image.py b/ui-tui/scripts/clipboard_image.py
new file mode 100644
index 00000000000..0862effad62
--- /dev/null
+++ b/ui-tui/scripts/clipboard_image.py
@@ -0,0 +1,9 @@
+"""Extract the Ink host clipboard without loading a session runtime."""
+import json
+import sys
+from pathlib import Path
+
+from hermes_cli.clipboard import save_clipboard_image
+
+if __name__ == "__main__":
+ print(json.dumps(bool(save_clipboard_image(Path(sys.argv[1])))))
diff --git a/ui-tui/src/__tests__/canonicalImages.test.ts b/ui-tui/src/__tests__/canonicalImages.test.ts
index a69df33e1d2..7942e65a07a 100644
--- a/ui-tui/src/__tests__/canonicalImages.test.ts
+++ b/ui-tui/src/__tests__/canonicalImages.test.ts
@@ -8,7 +8,7 @@ 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 { stageClipboardImage, stageImagePath } from '../lib/imageAttachments.js'
import { loadPendingInputs } from '../lib/pendingInputs.js'
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2nL8AAAAASUVORK5CYII=', 'base64')
@@ -50,6 +50,23 @@ it('stages private immutable local bytes, uploads remote bytes, and never falls
} finally { resetUiState(); vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) }
})
+it('extracts clipboard on the client and uploads only captured bytes to a remote owner', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ink-clipboard-'))
+ vi.stubEnv('HERMES_HOME', home)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', 'wss://remote.example')
+ resetUiState(); patchUiState({ sid: 'owner' })
+ const request = vi.fn(async () => ({ path: '/owner/cache/images/clip.png' }))
+ const extract = vi.fn(async (path: string) => { writeFileSync(path, png); return true })
+ try {
+ const image = await stageClipboardImage({ request } as any, captureDestination(), extract)
+ expect(image).toMatchObject({ path: '/owner/cache/images/clip.png', mime: 'image/png' })
+ expect(request).toHaveBeenCalledWith('image.attach_bytes', expect.objectContaining({ content_base64: png.toString('base64') }))
+ expect(() => readFileSync(extract.mock.calls[0]![0])).toThrow()
+ expect(await stageClipboardImage({ request } as any, captureDestination(), async () => false)).toBeNull()
+ expect(request).toHaveBeenCalledTimes(1)
+ } 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)
diff --git a/ui-tui/src/app/useComposerState.ts b/ui-tui/src/app/useComposerState.ts
index b56fd664fa8..04d55c104fa 100644
--- a/ui-tui/src/app/useComposerState.ts
+++ b/ui-tui/src/app/useComposerState.ts
@@ -15,7 +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 { stageClipboardImage, stageImagePath } from '../lib/imageAttachments.js'
import { readOsc52Clipboard } from '../lib/osc52.js'
import { isRemoteShellSession } from '../lib/terminalSetup.js'
import { pasteTokenLabel, stripTrailingPasteNewlines } from '../lib/text.js'
@@ -273,11 +273,13 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return null
}
- return resolveAttachment(
+ return resolveAttachment<ClipboardPasteResponse & { path?: string; mime?: string }>(
destination,
revision,
- gw.request<ClipboardPasteResponse & { path?: string }>('clipboard.paste', { session_id: sid })
- .catch(() => null),
+ (gw.isCanonical
+ ? stageClipboardImage(gw, destination).then(image => image ? { ...image, attached: true } : null)
+ : gw.request<ClipboardPasteResponse & { path?: string; mime?: string }>('clipboard.paste', { session_id: sid }))
+ .catch((error: Error) => { if (!quiet) { sys(`clipboard image failed: ${error.message}`) } return null }),
r => {
if (r?.attached) {
return attachImageToken(r, value, cursor)
diff --git a/ui-tui/src/lib/imageAttachments.ts b/ui-tui/src/lib/imageAttachments.ts
index 3e0962140d2..50c74724617 100644
--- a/ui-tui/src/lib/imageAttachments.ts
+++ b/ui-tui/src/lib/imageAttachments.ts
@@ -1,6 +1,8 @@
import { randomUUID } from 'node:crypto'
-import { mkdir, open, readFile, stat } from 'node:fs/promises'
-import { homedir } from 'node:os'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { mkdir, mkdtemp, open, readFile, rm, stat } from 'node:fs/promises'
+import { homedir, tmpdir } from 'node:os'
import { basename, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -66,6 +68,27 @@ async function resolveImagePath(raw: string): Promise<{ path: string; remainder:
throw new Error(`Image not found: ${value}`)
}
+async function extractClipboardImage(path: string): Promise<boolean> {
+ const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../..')
+ const python = process.env.HERMES_PYTHON?.trim() || process.env.PYTHON?.trim() ||
+ (process.platform === 'win32' ? 'python' : 'python3')
+ const { stdout } = await promisify(execFile)(python, [join(root, 'ui-tui/scripts/clipboard_image.py'), path],
+ { cwd: root, env: { ...process.env, PYTHONPATH: root }, timeout: 15_000, windowsHide: true })
+ return stdout.trim() === 'true'
+}
+
+export async function stageClipboardImage(
+ gw: GatewayClient, destination: SubmissionDestination,
+ extract: (path: string) => Promise<boolean> = extractClipboardImage
+): Promise<StagedImage | null> {
+ const directory = await mkdtemp(join(tmpdir(), 'hermes-clipboard-'))
+ const path = join(directory, 'clipboard.png')
+ try {
+ if (!await extract(path)) { return null }
+ return await stageImagePath(path, gw, destination)
+ } finally { await rm(directory, { recursive: true, force: true }) }
+}
+
export async function stageImagePath(raw: string, gw: GatewayClient, destination: SubmissionDestination): Promise<StagedImage> {
const source = await resolveImagePath(raw)
const bytes = await readFile(source.path)