The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): type a dropped file's host path into the browser terminal
emozilla3e7838570458
diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.test.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.test.tsnew file mode 100644index 00000000000..2361c1988ab--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.test.ts@@ -0,0 +1,162 @@+import type { Terminal } from '@xterm/xterm'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { $notifications, clearNotifications } from '@/store/notifications'++import { bindTerminalDrop } from './terminal-drop'++const desktopWindow = window as unknown as { hermesDesktop?: Partial<Window['hermesDesktop']> }+const MIB = 1024 * 1024++function file(name: string, size = 4): File {+ const value = new File(['data'], name, { type: 'text/plain' })+ Object.defineProperty(value, 'size', { value: size })++ return value+}++function transfer(files: File[], hermesPaths?: string[]): DataTransfer {+ const list = Object.assign([...files], { item: (index: number) => files[index] ?? null })++ return {+ files: list,+ getData: (type: string) =>+ type === 'application/x-hermes-paths' && hermesPaths ? JSON.stringify(hermesPaths.map(path => ({ path }))) : '',+ items: files.map(entry => ({ getAsFile: () => entry, kind: 'file' })),+ types: [...(hermesPaths ? ['application/x-hermes-paths'] : []), ...(files.length ? ['Files'] : [])]+ } as unknown as DataTransfer+}++function drop(host: HTMLElement, data: DataTransfer): Event {+ const event = new Event('drop', { bubbles: true, cancelable: true })+ Object.defineProperty(event, 'dataTransfer', { value: data })+ host.dispatchEvent(event)++ return event+}++function bind(shellName = 'bash') {+ const host = document.createElement('div')+ const write = vi.fn().mockResolvedValue(undefined)+ const focus = vi.fn()++ const unbind = bindTerminalDrop(host, {+ getSessionId: () => 'term-1',+ getShellName: () => shellName,+ markActivity: () => undefined,+ term: { focus } as unknown as Terminal,+ terminalApi: { write } as unknown as Window['hermesDesktop']['terminal']+ })++ return { focus, host, unbind, write }+}++afterEach(() => {+ Reflect.deleteProperty(desktopWindow, 'hermesDesktop')+ clearNotifications()+ vi.restoreAllMocks()+})++describe('terminal drop in the browser-hosted Desktop', () => {+ function browserBridge(stage: (file: File) => Promise<string>) {+ const stageFileForAttach = vi.fn(stage)+ desktopWindow.hermesDesktop = { getPathForFile: () => '', stageFileForAttach }++ return stageFileForAttach+ }++ it('stages each dropped file on the host and types its quoted host path', async () => {+ const stage = browserBridge(async entry => `/srv/hermes/uploads/${entry.name}`)+ const { host, unbind, write } = bind('bash')++ const event = drop(host, transfer([file("it's.txt"), file('b c.log')]))++ expect(event.defaultPrevented).toBe(true)+ await vi.waitFor(() => expect(write).toHaveBeenCalledTimes(1))+ expect(write).toHaveBeenCalledWith('term-1', "'/srv/hermes/uploads/it'\\''s.txt' '/srv/hermes/uploads/b c.log' ")+ expect(stage).toHaveBeenCalledTimes(2)+ unbind()+ })++ it("quotes staged paths for the terminal's own shell", async () => {+ browserBridge(async () => 'C:\\Users\\me\\.hermes\\uploads\\it\'s.txt')+ const { host, unbind, write } = bind('powershell.exe')++ drop(host, transfer([file("it's.txt")]))++ await vi.waitFor(() => expect(write).toHaveBeenCalledWith('term-1', "'C:\\Users\\me\\.hermes\\uploads\\it''s.txt' "))+ unbind()+ })++ it('keeps in-app paths and staged files in drop order', async () => {+ browserBridge(async entry => `/srv/hermes/uploads/${entry.name}`)+ const { host, unbind, write } = bind('zsh')++ drop(host, transfer([file('notes.md')], ['/work/project/src']))++ await vi.waitFor(() =>+ expect(write).toHaveBeenCalledWith('term-1', "'/work/project/src' '/srv/hermes/uploads/notes.md' ")+ )+ unbind()+ })++ it('never uploads a file over 16 MiB and names it in a warning', async () => {+ const stage = browserBridge(async entry => `/srv/hermes/uploads/${entry.name}`)+ const { host, unbind, write } = bind('bash')++ drop(host, transfer([file('huge.iso', 16 * MIB + 1), file('small.txt', 16 * MIB)]))++ await vi.waitFor(() => expect(write).toHaveBeenCalledWith('term-1', "'/srv/hermes/uploads/small.txt' "))+ expect(stage).toHaveBeenCalledTimes(1)+ expect(stage.mock.calls[0][0].name).toBe('small.txt')+ const [warning] = $notifications.get()+ expect(warning?.kind).toBe('warning')+ expect(`${warning?.title} ${warning?.message}`).toContain('huge.iso')+ expect(`${warning?.title} ${warning?.message}`).toContain('16 MiB')+ unbind()+ })++ it("reports a failed upload with the host's reason and types nothing for it", async () => {+ browserBridge(async () => {+ throw new Error('File upload failed (502)')+ })+ const { focus, host, unbind, write } = bind('bash')++ drop(host, transfer([file('report.pdf')]))++ await vi.waitFor(() => expect($notifications.get()).toHaveLength(1))+ const [error] = $notifications.get()+ expect(error?.kind).toBe('error')+ expect(`${error?.title} ${error?.message}`).toContain('report.pdf')+ expect(`${error?.title} ${error?.message}`).toContain('502')+ expect(write).not.toHaveBeenCalled()+ expect(focus).not.toHaveBeenCalled()+ unbind()+ })+})++describe('terminal drop in Electron Desktop', () => {+ it('types the native path of each dropped file without uploading it', async () => {+ const getPathForFile = vi.fn((entry: File) => `/home/me/${entry.name}`)+ desktopWindow.hermesDesktop = { getPathForFile }+ const { focus, host, unbind, write } = bind('bash')++ drop(host, transfer([file('a.txt'), file('b c.txt')]))++ expect(write).toHaveBeenCalledWith('term-1', "'/home/me/a.txt' '/home/me/b c.txt' ")+ expect(focus).toHaveBeenCalled()+ unbind()+ })++ it('ignores a dropped file Electron cannot resolve to a path', async () => {+ desktopWindow.hermesDesktop = { getPathForFile: () => '' }+ const { host, unbind, write } = bind('bash')++ drop(host, transfer([file('from-a-web-page.png')]))+ await Promise.resolve()++ expect(write).not.toHaveBeenCalled()+ expect($notifications.get()).toHaveLength(0)+ unbind()+ })+})diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.tsindex da7634b1747..ac4b01c068c 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts@@ -1,11 +1,17 @@import type { Terminal } from '@xterm/xterm'+import { translateNow } from '@/i18n'+import { BROWSER_UPLOAD_MAX_BYTES } from '@/lib/browser-uploads'import { triggerHaptic } from '@/lib/haptics'+import { notify, notifyError } from '@/store/notifications'type TerminalApi = Window['hermesDesktop']['terminal']const HERMES_PATHS_MIME = 'application/x-hermes-paths'+/** A host path, or an OS file with no path the browser must upload to get one. */+type DroppedEntry = File | string+function transferHasDropCandidates(t: DataTransfer): boolean {if (t.types?.includes(HERMES_PATHS_MIME)) {return true@@ -24,8 +30,9 @@ function transferHasDropCandidates(t: DataTransfer): boolean {return false}-function collectDroppedPaths(t: DataTransfer): string[] {+function collectDroppedEntries(t: DataTransfer): DroppedEntry[] {const seen = new Set<string>()+ const entries: DroppedEntry[] = []const push = (value: unknown) => {if (typeof value !== 'string') {@@ -34,8 +41,9 @@ function collectDroppedPaths(t: DataTransfer): string[] {const path = value.trim()- if (path) {+ if (path && !seen.has(path)) {seen.add(path)+ entries.push(path)}}@@ -52,32 +60,88 @@ function collectDroppedPaths(t: DataTransfer): string[] {}const getPath = window.hermesDesktop?.getPathForFile-- const addFile = (file: File | null) => {- if (!file || !getPath) {+ // Only the browser-hosted Desktop stages bytes; Electron resolves an OS file to its own path.+ const canStage = Boolean(window.hermesDesktop?.stageFileForAttach)+ const fileCount = t.files?.length ?? 0++ // `items` repeats `files` with fresh File objects, so it supplies files to stage only when+ // `files` is empty.+ const addFile = (file: File | null, stageable: boolean) => {+ if (!file) {return}+ let path = ''+try {- push(getPath(file))+ path = getPath?.(file) ?? ''} catch {// File handle unavailable.}++ if (path) {+ push(path)+ } else if (canStage && stageable) {+ entries.push(file)+ }}- for (let i = 0; i < (t.files?.length ?? 0); i += 1) {- addFile(t.files.item(i))+ for (let i = 0; i < fileCount; i += 1) {+ addFile(t.files.item(i), true)}for (let i = 0; i < (t.items?.length ?? 0); i += 1) {const item = t.items[i]if (item?.kind === 'file') {- addFile(item.getAsFile())+ addFile(item.getAsFile(), fileCount === 0)}}- return [...seen]+ return entries+}++// The browser uploads each dropped file to the host (the composer's staged upload) and types the+// host path it gets back. A file over the upload limit is never sent; a warning names it.+async function stageDroppedEntries(entries: DroppedEntry[]): Promise<string[]> {+ const stage = window.hermesDesktop?.stageFileForAttach+ const tooLarge: string[] = []++ const paths = await Promise.all(+ entries.map(async entry => {+ if (typeof entry === 'string') {+ return entry+ }++ if (entry.size > BROWSER_UPLOAD_MAX_BYTES) {+ tooLarge.push(entry.name)++ return ''+ }++ try {+ return (await stage?.(entry)) ?? ''+ } catch (error) {+ notifyError(error, translateNow('rightSidebar.terminalDropUploadFailed', entry.name))++ return ''+ }+ })+ )++ if (tooLarge.length) {+ notify({+ kind: 'warning',+ title: translateNow('rightSidebar.terminalDropTooLargeTitle'),+ message: translateNow(+ 'rightSidebar.terminalDropTooLarge',+ tooLarge.join(', '),+ `${BROWSER_UPLOAD_MAX_BYTES / (1024 * 1024)} MiB`+ )+ })+ }++ return paths.filter(Boolean)}function quotePathForShell(path: string, shellName: string): string {@@ -103,7 +167,9 @@ interface TerminalDropOptions {}// Dropping files (from the OS or the app's file trees) types their shell-quoted-// paths at the prompt, like a native terminal. Returns the listener teardown.+// paths at the prompt, like a native terminal. In the browser-hosted Desktop an+// OS file is uploaded to the host first and its host path is typed. Returns the+// listener teardown.export function bindTerminalDrop(host: HTMLElement,{ getSessionId, getShellName, markActivity, term, terminalApi }: TerminalDropOptions@@ -127,16 +193,30 @@ export function bindTerminalDrop(e.preventDefault()e.stopPropagation()- const paths = collectDroppedPaths(e.dataTransfer)+ const entries = collectDroppedEntries(e.dataTransfer)++ if (!entries.length) {+ return+ }++ const typePaths = (paths: string[]) => {+ if (!paths.length) {+ return+ }++ markActivity()+ void terminalApi.write(id, `${paths.map(p => quotePathForShell(p, getShellName())).join(' ')} `)+ term.focus()+ triggerHaptic('selection')+ }++ if (entries.every((entry): entry is string => typeof entry === 'string')) {+ typePaths(entries)- if (!paths.length) {return}- markActivity()- void terminalApi.write(id, `${paths.map(p => quotePathForShell(p, getShellName())).join(' ')} `)- term.focus()- triggerHaptic('selection')+ void stageDroppedEntries(entries).then(typePaths)}host.addEventListener('dragenter', onDragOver)diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex c17158cbad8..55da905fabd 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4229,6 +4229,9 @@ export const en: Translations = {terminalNew: 'New terminal',terminalCloseOthers: 'Close others',terminalCloseAll: 'Close all',+ terminalDropUploadFailed: name => `Could not upload ${name}`,+ terminalDropTooLargeTitle: 'Too large to upload',+ terminalDropTooLarge: (names, limit) => `Each file can be up to ${limit}. Not uploaded: ${names}`,addToChat: 'Add to chat'},diff --git a/apps/desktop/src/i18n/overlay-gaps.json b/apps/desktop/src/i18n/overlay-gaps.jsonindex 5d8d77752ca..8b9f8f6d694 100644--- a/apps/desktop/src/i18n/overlay-gaps.json+++ b/apps/desktop/src/i18n/overlay-gaps.json@@ -1052,6 +1052,9 @@"prompts.vaultUnlockTitle": ["ru"],"rightSidebar.terminalCloseAll": ["ar"],"rightSidebar.terminalCloseOthers": ["ar"],+ "rightSidebar.terminalDropTooLarge": ["ar","de","es","fr","ja","ru","zh","zh-hant"],+ "rightSidebar.terminalDropTooLargeTitle": ["ar","de","es","fr","ja","ru","zh","zh-hant"],+ "rightSidebar.terminalDropUploadFailed": ["ar","de","es","fr","ja","ru","zh","zh-hant"],"rightSidebar.terminalNew": ["ar"],"rightSidebar.terminalOpenInteractive": ["de","es","fr"],"rightSidebar.terminalReadOnly": ["de","es","fr"],diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex b16c3b890a8..08a6ce86002 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -28,6 +28,7 @@ import type { OnboardingTranslations } from './types_onboarding'import type { PluginPreviewAccessTranslations } from './types_plugin_preview_access'import type { PluginUpdateTranslations } from './types_plugin_update'import type { SidebarProjectsTranslations } from './types_projects'+import type { RightSidebarTranslations } from './types_right_sidebar'import type { SharedMetricsTranslations } from './types_shared_metrics'import type { ThemePickerCopy } from './types_theme_picker'import type { UninstallSectionTranslations } from './types_uninstall_section'@@ -3653,52 +3654,7 @@ catalog: CatalogTranslations}}- rightSidebar: {- aria: string- panelsAria: string- files: string- terminal: string- noFolderSelected: string- changeCwdTitle: string- remotePickerTitle: string- remotePickerDescription: string- remotePickerSelect: string- remotePickerNewFolder: string- remotePickerFolderName: string- remotePickerCreateFolder: string- remotePickerInvalidFolderName: string- remotePickerCreateFolderFailed: (error: string) => string- folderTip: (cwd: string) => string- openFolder: string- refreshTree: string- collapseAll: string- showIgnored: string- hideIgnored: string- previewUnavailable: string- couldNotPreview: (path: string) => string- noProjectTitle: string- noProjectBody: string- noProjectOpen: string- noDiffs: string- unreadableTitle: string- unreadableBody: (error: string) => string- emptyTitle: string- emptyBody: string- treeErrorTitle: string- treeErrorBody: string- tryAgain: string- loadingTree: string- loadingFiles: string- terminalHide: string- terminalsAria: string- terminalNew: string- terminalReadOnly: string- terminalReadOnlyHelp: string- terminalOpenInteractive: string- terminalCloseOthers: string- terminalCloseAll: string- addToChat: string- }+ rightSidebar: RightSidebarTranslationspreview: {tab: stringdiff --git a/apps/desktop/src/i18n/types_right_sidebar.ts b/apps/desktop/src/i18n/types_right_sidebar.tsnew file mode 100644index 00000000000..96dedcca8f7--- /dev/null+++ b/apps/desktop/src/i18n/types_right_sidebar.ts@@ -0,0 +1,50 @@+// The right sidebar's copy (file tree, folder picker, terminals); `Translations.rightSidebar`.+export interface RightSidebarTranslations {+ aria: string+ panelsAria: string+ files: string+ terminal: string+ noFolderSelected: string+ changeCwdTitle: string+ remotePickerTitle: string+ remotePickerDescription: string+ remotePickerSelect: string+ remotePickerNewFolder: string+ remotePickerFolderName: string+ remotePickerCreateFolder: string+ remotePickerInvalidFolderName: string+ remotePickerCreateFolderFailed: (error: string) => string+ folderTip: (cwd: string) => string+ openFolder: string+ refreshTree: string+ collapseAll: string+ showIgnored: string+ hideIgnored: string+ previewUnavailable: string+ couldNotPreview: (path: string) => string+ noProjectTitle: string+ noProjectBody: string+ noProjectOpen: string+ noDiffs: string+ unreadableTitle: string+ unreadableBody: (error: string) => string+ emptyTitle: string+ emptyBody: string+ treeErrorTitle: string+ treeErrorBody: string+ tryAgain: string+ loadingTree: string+ loadingFiles: string+ terminalHide: string+ terminalsAria: string+ terminalNew: string+ terminalReadOnly: string+ terminalReadOnlyHelp: string+ terminalOpenInteractive: string+ terminalCloseOthers: string+ terminalCloseAll: string+ terminalDropUploadFailed: (name: string) => string+ terminalDropTooLargeTitle: string+ terminalDropTooLarge: (names: string, limit: string) => string+ addToChat: string+}diff --git a/apps/desktop/src/lib/browser-uploads.ts b/apps/desktop/src/lib/browser-uploads.tsindex 57216f85455..db44d2a18e2 100644--- a/apps/desktop/src/lib/browser-uploads.ts+++ b/apps/desktop/src/lib/browser-uploads.ts@@ -4,6 +4,9 @@ import { type BrowserBootstrap, browserFetch } from '@/lib/browser-transport'const STAGED_UPLOAD_CACHE_LIMIT = 256+/** The largest file the browser stages on the host; mirrors WEBAPP_ATTACHMENT_MAX_BYTES (hermes_constants.py). */+export const BROWSER_UPLOAD_MAX_BYTES = 16 * 1024 * 1024+const IMAGE_MIME_BY_EXTENSION: Record<string, string> = {'.bmp': 'image/bmp','.gif': 'image/gif',diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex e59d499192c..346c02bd5e1 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -2680,6 +2680,9 @@"rightSidebar.terminal","rightSidebar.terminalCloseAll","rightSidebar.terminalCloseOthers",+ "rightSidebar.terminalDropTooLarge",+ "rightSidebar.terminalDropTooLargeTitle",+ "rightSidebar.terminalDropUploadFailed","rightSidebar.terminalHide","rightSidebar.terminalNew","rightSidebar.terminalOpenInteractive",