The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): dropping a file into the terminal never types keystrokes into the shell
emozilla5b7086aff9e2
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.tsindex 2361c1988ab..17c115ec2a5 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.test.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.test.ts@@ -1,5 +1,5 @@-import type { Terminal } from '@xterm/xterm'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { Terminal } from '@xterm/xterm'+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'import { $notifications, clearNotifications } from '@/store/notifications'@@ -7,6 +7,27 @@ import { bindTerminalDrop } from './terminal-drop'const desktopWindow = window as unknown as { hermesDesktop?: Partial<Window['hermesDesktop']> }const MIB = 1024 * 1024+// eslint-disable-next-line no-control-regex -- the assertion is that none of these reach the shell+const CONTROL_CHARACTER = /[\u0000-\u001f\u007f-\u009f]/+const BRACKETED_PASTE_ON = '\x1b[?2004h'+const originalMatchMedia = window.matchMedia++// xterm measures the device pixel ratio through matchMedia when it opens; jsdom has none.+beforeAll(() => {+ window.matchMedia = (query: string) =>+ ({+ addEventListener: () => undefined,+ addListener: () => undefined,+ matches: false,+ media: query,+ removeEventListener: () => undefined,+ removeListener: () => undefined+ }) as unknown as MediaQueryList+})++afterAll(() => {+ window.matchMedia = originalMatchMedia+})function file(name: string, size = 4): File {const value = new File(['data'], name, { type: 'text/plain' })@@ -35,20 +56,36 @@ function drop(host: HTMLElement, data: DataTransfer): Event {return event}+// A real xterm, wired to the shell the way the session hook wires it: everything the terminal+// emits (keystrokes, pastes) is written to the PTY.function bind(shellName = 'bash') {const host = document.createElement('div')+ document.body.append(host)+ const term = new Terminal({ allowProposedApi: true, cols: 80, rows: 10 })+ term.open(host)const write = vi.fn().mockResolvedValue(undefined)- const focus = vi.fn()+ const input = term.onData(data => void write('term-1', data))+ const focus = vi.spyOn(term, 'focus')- const unbind = bindTerminalDrop(host, {+ const unbindDrop = bindTerminalDrop(host, {getSessionId: () => 'term-1',getShellName: () => shellName,markActivity: () => undefined,- term: { focus } as unknown as Terminal,- terminalApi: { write } as unknown as Window['hermesDesktop']['terminal']+ term})- return { focus, host, unbind, write }+ const unbind = () => {+ unbindDrop()+ input.dispose()+ term.dispose()+ host.remove()+ }++ return { focus, host, term, unbind, write }+}++function typedText(write: ReturnType<typeof vi.fn>): string {+ return write.mock.calls.map(([, data]) => String(data)).join('')}afterEach(() => {@@ -160,3 +197,48 @@ describe('terminal drop in Electron Desktop', () => {unbind()})})++describe('terminal drop never types keystrokes', () => {+ // A file name may hold bytes a shell reads as keys: ^U erases what was typed and CR runs the+ // line, so a planted name could run a command with no Enter pressed. No quoting stops a+ // line editor from acting on them, so such a path is never typed: a warning names it (control+ // characters spelled as \xNN) and the other dropped paths are still typed.+ it('skips an app file-tree path holding control characters and names it in a warning', () => {+ const { host, unbind, write } = bind('bash')++ drop(host, transfer([], ['/work/drop/notes\x15touch PWNED\r.txt', '/work/drop/ok.txt', '/work/c1\x9b.md', '/work/del\x7f']))++ expect(typedText(write)).not.toMatch(CONTROL_CHARACTER)+ expect(typedText(write)).toBe("'/work/drop/ok.txt' ")+ const [warning] = $notifications.get()+ expect(warning?.kind).toBe('warning')+ expect(warning?.message).toContain('/work/drop/notes\\x15touch PWNED\\x0d.txt')+ expect(warning?.message).toContain('/work/c1\\x9b.md')+ expect(warning?.message).toContain('/work/del\\x7f')+ unbind()+ })++ it('types nothing for an OS file whose native path holds a control character', () => {+ desktopWindow.hermesDesktop = { getPathForFile: (entry: File) => `/home/me/${entry.name}` }+ const { focus, host, unbind, write } = bind('zsh')++ drop(host, transfer([file('report\n.txt')]))++ expect(write).not.toHaveBeenCalled()+ expect(focus).not.toHaveBeenCalled()+ expect($notifications.get()[0]?.message).toContain('/home/me/report\\x0a.txt')+ unbind()+ })++ // A shell that turned bracketed paste on (bash 5.1+, zsh) inserts pasted text without acting+ // on it; the drop arrives the way a paste does, wrapped in the paste markers.+ it('types the paths as a bracketed paste when the shell turned bracketed paste on', async () => {+ const { host, term, unbind, write } = bind('bash')+ await new Promise<void>(resolve => term.write(BRACKETED_PASTE_ON, resolve))++ drop(host, transfer([], ['/work/a b.txt', "/work/it's.md"]))++ expect(write).toHaveBeenCalledExactlyOnceWith('term-1', "\x1b[200~'/work/a b.txt' '/work/it'\\''s.md' \x1b[201~")+ 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 ac4b01c068c..05d0b25eba6 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts@@ -5,8 +5,6 @@ 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. */@@ -158,21 +156,35 @@ function quotePathForShell(path: string, shellName: string): string {return `'${path.replace(/'/g, "'\\''")}'`}+// C0 controls, DEL and C1 controls. A line editor acts on them inside any quoting (^U erases the+// line typed so far, CR runs it), so a path holding one is never typed.+// eslint-disable-next-line no-control-regex -- matching control characters is the point+const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g++function hasControlCharacter(path: string): boolean {+ return path.search(CONTROL_CHARACTERS) !== -1+}++/** The path with each control character spelled `\xNN`, so a notice can name it. */+function printablePath(path: string): string {+ return path.replace(CONTROL_CHARACTERS, char => `\\x${char.charCodeAt(0).toString(16).padStart(2, '0')}`)+}+interface TerminalDropOptions {getSessionId: () => string | nullgetShellName: () => stringmarkActivity: () => voidterm: Terminal- terminalApi: TerminalApi}// Dropping files (from the OS or the app's file trees) types their shell-quoted// 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.+// OS file is uploaded to the host first and its host path is typed. The paths+// go through xterm's paste, so a shell that turned bracketed paste on inserts+// them without acting on them. Returns the listener teardown.export function bindTerminalDrop(host: HTMLElement,- { getSessionId, getShellName, markActivity, term, terminalApi }: TerminalDropOptions+ { getSessionId, getShellName, markActivity, term }: TerminalDropOptions): () => void {const onDragOver = (e: DragEvent) => {if (!e.dataTransfer || !transferHasDropCandidates(e.dataTransfer)) {@@ -200,12 +212,23 @@ export function bindTerminalDrop(}const typePaths = (paths: string[]) => {- if (!paths.length) {+ const refused = paths.filter(hasControlCharacter)+ const typed = paths.filter(path => !hasControlCharacter(path))++ if (refused.length) {+ notify({+ kind: 'warning',+ title: translateNow('rightSidebar.terminalDropControlTitle'),+ message: translateNow('rightSidebar.terminalDropControl', refused.map(printablePath).join(', '))+ })+ }++ if (!typed.length) {return}markActivity()- void terminalApi.write(id, `${paths.map(p => quotePathForShell(p, getShellName())).join(' ')} `)+ term.paste(`${typed.map(p => quotePathForShell(p, getShellName())).join(' ')} `)term.focus()triggerHaptic('selection')}diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.tsindex 0110eed5685..648d0d4f47d 100644--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts@@ -327,8 +327,7 @@ export function useTerminalSession({getSessionId: () => sessionIdRef.current,getShellName: () => shellNameRef.current,markActivity,- term,- terminalApi+ term}))diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 55da905fabd..14a6b4533b2 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4232,6 +4232,8 @@ export const en: Translations = {terminalDropUploadFailed: name => `Could not upload ${name}`,terminalDropTooLargeTitle: 'Too large to upload',terminalDropTooLarge: (names, limit) => `Each file can be up to ${limit}. Not uploaded: ${names}`,+ terminalDropControlTitle: 'Not typed into the terminal',+ terminalDropControl: paths => `These names hold control characters the shell would act on as keys: ${paths}`,addToChat: 'Add to chat'},diff --git a/apps/desktop/src/i18n/overlay-gaps.json b/apps/desktop/src/i18n/overlay-gaps.jsonindex 8b9f8f6d694..c28b5fdb0ea 100644--- a/apps/desktop/src/i18n/overlay-gaps.json+++ b/apps/desktop/src/i18n/overlay-gaps.json@@ -1052,6 +1052,8 @@"prompts.vaultUnlockTitle": ["ru"],"rightSidebar.terminalCloseAll": ["ar"],"rightSidebar.terminalCloseOthers": ["ar"],+ "rightSidebar.terminalDropControl": ["ar","de","es","fr","ja","ru","zh","zh-hant"],+ "rightSidebar.terminalDropControlTitle": ["ar","de","es","fr","ja","ru","zh","zh-hant"],"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"],diff --git a/apps/desktop/src/i18n/types_right_sidebar.ts b/apps/desktop/src/i18n/types_right_sidebar.tsindex 96dedcca8f7..f7e5440bc64 100644--- a/apps/desktop/src/i18n/types_right_sidebar.ts+++ b/apps/desktop/src/i18n/types_right_sidebar.ts@@ -46,5 +46,7 @@ export interface RightSidebarTranslations {terminalDropUploadFailed: (name: string) => stringterminalDropTooLargeTitle: stringterminalDropTooLarge: (names: string, limit: string) => string+ terminalDropControlTitle: string+ terminalDropControl: (paths: string) => stringaddToChat: string}diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 1c0d5c0bb27..d7944d68c27 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -2680,6 +2680,8 @@"rightSidebar.terminal","rightSidebar.terminalCloseAll","rightSidebar.terminalCloseOthers",+ "rightSidebar.terminalDropControl",+ "rightSidebar.terminalDropControlTitle","rightSidebar.terminalDropTooLarge","rightSidebar.terminalDropTooLargeTitle","rightSidebar.terminalDropUploadFailed",