The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): stop giving terminal drops POSIX quoting in shells it does not know
unsupportedpastels60c7921bd3a7
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 e82fe2e28a3..84d6161f23d 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@@ -366,11 +366,135 @@ function fishWords(text: string): string[] {return words}+// POSIX sh (and bash, zsh, ksh, dash): inside '...' every character is literal and nothing escapes+// a quote; outside quotes a backslash escapes the next character, ';' '&' '|' end a command, '#'+// starts a comment, and '$' or '`' starts an expansion.+function posixWords(text: string): string[] {+ const words: string[] = []+ let word = ''+ let i = 0++ const flush = () => {+ if (word) {+ words.push(word)+ }++ word = ''+ }++ while (i < text.length) {+ const c = text[i]++ if (c === "'") {+ const end = text.indexOf("'", i + 1)++ if (end === -1) {+ return [...words, `${word}<unterminated>`]+ }++ word += text.slice(i + 1, end)+ i = end + 1+ } else if (c === '\\') {+ word += text[i + 1] ?? ''+ i += 2+ } else if (';&|'.includes(c)) {+ flush()+ words.push(c)+ i += 1+ } else if (c === '#' && !word) {+ words.push('#comment')++ break+ } else if (c === '$' || c === '`' || c === '"') {+ words.push('<expansion>')+ i += 1+ } else if (/\s/.test(c)) {+ flush()+ i += 1+ } else {+ word += c+ i += 1+ }+ }++ flush()++ return words+}++// csh and tcsh: as POSIX sh, except that '!' starts a history substitution everywhere, inside+// single quotes too, unless a backslash escapes it (csh(1), "History substitution").+function cshWords(text: string): string[] {+ const words: string[] = []+ let word = ''+ let i = 0++ const flush = () => {+ if (word) {+ words.push(word)+ }++ word = ''+ }++ while (i < text.length) {+ const c = text[i]++ if (c === "'") {+ i += 1++ while (i < text.length && text[i] !== "'") {+ if (text[i] === '\\' && text[i + 1] === '!') {+ i += 1+ } else if (text[i] === '!') {+ return [...words, '<history>']+ }++ word += text[i]+ i += 1+ }++ if (i >= text.length) {+ return [...words, `${word}<unterminated>`]+ }++ i += 1+ } else if (c === '\\') {+ word += text[i + 1] ?? ''+ i += 2+ } else if (c === '!') {+ return [...words, '<history>']+ } else if (';&|'.includes(c)) {+ flush()+ words.push(c)+ i += 1+ } else if (/\s/.test(c)) {+ flush()+ i += 1+ } else {+ word += c+ i += 1+ }+ }++ flush()++ return words+}+// cmd.exe at its prompt first replaces %NAME% of every defined variable, inside double quotes too,// and leaves an undefined one as typed; then a '"' toggles quoting, '^' outside quotes takes the-// next character literally and '&' outside quotes starts a new command.-function cmdWords(text: string, env: Record<string, string>): string[] {- const expanded = text.replace(/%([^%]+)%/g, (whole, name: string) => env[name.toUpperCase()] ?? whole)+// next character literally and '&' outside quotes starts a new command. With delayed expansion on+// (cmd /V:ON, or DelayedExpansion in the registry) a line that still holds a '!' is read once more:+// !NAME! is replaced by its value inside quotes too, a lone '!' is dropped, and '^' escapes.+function cmdWords(text: string, env: Record<string, string>, { delayed = false } = {}): string[] {+ const percent = text.replace(/%([^%]+)%/g, (whole, name: string) => env[name.toUpperCase()] ?? whole)++ const expanded =+ delayed && percent.includes('!')+ ? percent.replace(/!([^!]*)!|!/g, (whole, name?: string) => (name ? (env[name.toUpperCase()] ?? '') : ''))+ : percent+const words: string[] = []let word = ''let quoted = false@@ -472,4 +596,107 @@ describe("terminal drop types each path as one literal word of the terminal's shexpect(droppedText(shell, "/work/it's \\ a\u2019b!.txt")).toBe("'/work/it'\\''s \\ a\u2019b!.txt' ")}})++ const HOSTILE_POSIX_PATHS = [+ "/work/it's; touch PWNED; '.txt",+ '/work/$(touch PWNED) `id` $HOME.txt',+ '/work/a\\b \\\' & | # " !!.txt',+ '/work/plain.txt'+ ]++ it.each(['sh', 'ash', 'bash', 'dash', 'ksh', 'mksh', 'zsh', '/bin/bash', '-zsh', 'bash.exe'])(+ 'types every path as one literal POSIX word for %s',+ shell => {+ for (const path of HOSTILE_POSIX_PATHS) {+ expect(posixWords(droppedText(shell, path))).toEqual([path])+ }+ }+ )++ it.each(['csh', 'tcsh', '/bin/tcsh'])('types every path as one literal word with no history substitution for %s', shell => {+ for (const path of [...HOSTILE_POSIX_PATHS, '/home/me/x!!:s^e^;touch PWNED;^.txt', '/home/me/!-2']) {+ expect(cshWords(droppedText(shell, path))).toEqual([path])+ }+ })++ it('matches a shell by its program name, not by a directory or a longer name', () => {+ // A directory named like cmd must not give bash the cmd quoting.+ expect(posixWords(droppedText('/opt/cmd-tools/bin/bash', "/work/it's.txt"))).toEqual(["/work/it's.txt"])+ expect(droppedText('C:\\Windows\\System32\\cmd.exe', 'C:\\work\\a b.txt')).toBe('"C:\\work\\a b.txt" ')+ expect(droppedText('C:\\Program Files\\PowerShell\\7\\pwsh.exe', "C:\\it's.txt")).toBe("'C:\\it''s.txt' ")+ })+})++describe('terminal drop in cmd with delayed expansion', () => {+ const env = { HERMESPROBE: 'X"&calc&"Y', PATH: 'C:\\Windows\\system32' }++ it('types the same words whether delayed expansion is on or off', () => {+ for (const path of ['C:\\work\\a%HERMESPROBE%b.txt', 'C:\\work\\a^b & c.txt', 'C:\\work\\100%', 'C:\\work\\a b (1).txt']) {+ const typed = droppedText('cmd.exe', path)+ expect(cmdWords(typed, env)).toEqual([path])+ expect(cmdWords(typed, env, { delayed: true })).toEqual([path])+ }+ })++ // cmd can't be asked whether delayed expansion is on, and no quoting keeps a '!' literal in both+ // modes: with it on, !HERMESPROBE! is replaced inside the quotes and a lone '!' is dropped.+ it('never types a path holding "!" and names it in a warning', () => {+ const { host, unbind, write } = bind('cmd.exe')++ drop(host, transfer([], ['C:\\work\\a!HERMESPROBE!b.txt', 'C:\\work\\wow!.txt', 'C:\\work\\ok.txt']))++ expect(typedText(write)).toBe('"C:\\work\\ok.txt" ')+ const [warning] = $notifications.get()+ expect(warning?.kind).toBe('warning')+ expect(warning?.message).toContain('C:\\work\\a!HERMESPROBE!b.txt')+ expect(warning?.message).toContain('C:\\work\\wow!.txt')+ expect(warning?.message).not.toContain('ok.txt')+ unbind()+ })+})++// A shell the quoter does not name (nu, xonsh, elvish, an SSH session's remote shell) has quoting+// rules of its own, so POSIX quotes could end early there. Only a path every shell reads as one+// plain word is typed, as it is; any other is left out and named in a warning.+describe('terminal drop into a shell the quoter does not name', () => {+ it.each(['nu', 'xonsh', 'elvish', 'ssh', 'C:\\tools\\nu.exe', '/usr/local/bin/xonsh'])('types only plain paths for %s', shell => {+ const { host, unbind, write } = bind(shell)++ drop(+ host,+ transfer([], ['/home/me/notes_v2.md', '/home/me/a b.txt', "/home/me/it's.txt", '/home/me/$HOME', '~/x', '-rf', 'C:\\x'])+ )++ expect(typedText(write)).toBe('/home/me/notes_v2.md ')+ const [warning] = $notifications.get()+ expect(warning?.kind).toBe('warning')++ for (const path of ['/home/me/a b.txt', "/home/me/it's.txt", '/home/me/$HOME', '~/x', '-rf', 'C:\\x']) {+ expect(warning?.message).toContain(path)+ }++ expect(warning?.message).not.toContain('notes_v2.md')+ unbind()+ })++ it('types nothing and focuses nothing when no dropped path is plain', () => {+ const { focus, host, unbind, write } = bind('nu')++ drop(host, transfer([], ['/home/me/a b.txt']))++ expect(write).not.toHaveBeenCalled()+ expect(focus).not.toHaveBeenCalled()+ expect($notifications.get()[0]?.message).toContain('nu')+ unbind()+ })++ it('reads a plain path as the same one word in every named shell', () => {+ const path = '/home/me/v1.2/notes_v2-final.md'++ expect(posixWords(`${path} `)).toEqual([path])+ expect(cshWords(`${path} `)).toEqual([path])+ expect(fishWords(`${path} `)).toEqual([path])+ expect(powershellWords(`${path} `)).toEqual([path])+ expect(cmdWords(`${path} `, {}, { delayed: true })).toEqual([path])+ })})diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.tsindex f5559131fc0..bc1f18dd386 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts@@ -142,19 +142,42 @@ async function stageDroppedEntries(entries: DroppedEntry[]): Promise<string[]> {return paths.filter(Boolean)}+const POSIX_SHELLS = new Set(['ash', 'bash', 'dash', 'ksh', 'mksh', 'sh', 'zsh'])++// Every shell reads a path made only of these as one plain word, so a shell the quoter does not+// name still gets it as typed. A leading - or ~ would read as an option or a home directory.+const PLAIN_PATH = /^[\w./:][\w./:-]*$/++/** The shell's program name: `C:\...\pwsh.exe` is `pwsh`, a login shell's `-zsh` is `zsh`. */+function shellProgram(shellName: string): string {+ return shellName+ .toLowerCase()+ .replace(/^.*[\\/]/, '')+ .replace(/^-/, '')+ .replace(/\.exe$/, '')+}+// The path quoted so the terminal's shell reads it as one literal argument, whatever characters-// the name holds: a name must never end the quoting and add a command for the next Enter. Shells-// not named here get POSIX quoting.-function quotePathForShell(path: string, shellName: string): string {- const shell = shellName.toLowerCase()+// the name holds: a name must never end the quoting and add a command for the next Enter. Null+// when this shell has no quoting that does that: a shell not named here (nu, xonsh, elvish, the+// remote shell of an SSH tab) gets only a plain path, typed as it is.+function quotePathForShell(path: string, shellName: string): null | string {+ const name = shellProgram(shellName)- if (shell.includes('powershell') || shell.includes('pwsh')) {+ if (name.startsWith('pwsh') || name.startsWith('powershell')) {// PowerShell reads the typographic quotes U+2018..U+201B as single quotes too; doubling any of// them keeps it literal.return `'${path.replace(/['\u2018\u2019\u201a\u201b]/g, '$&$&')}'`}- if (shell.includes('cmd')) {+ if (name === 'cmd') {+ // With delayed expansion on (cmd /V:ON, or set in the registry) cmd replaces !NAME! inside+ // double quotes too and drops a lone !. Nothing tells the terminal whether it is on, and no+ // quoting keeps a ! literal both ways.+ if (path.includes('!')) {+ return null+ }+// cmd expands %NAME% inside double quotes before it reads them, and a value holding a quote// would end the quoting. Each % goes outside the quotes as ^%, which no variable name matches.return path@@ -163,8 +186,6 @@ function quotePathForShell(path: string, shellName: string): string {.join('^%')}- const name = shell.replace(/^.*[\\/]/, '').replace(/\.exe$/, '')-if (name === 'fish') {// Inside fish's single quotes \' and \\ are escapes.return `'${path.replace(/[\\']/g, '\\$&')}'`@@ -172,8 +193,16 @@ function quotePathForShell(path: string, shellName: string): string {const quoted = `'${path.replace(/'/g, "'\\''")}'`- // csh and tcsh expand !-history even inside single quotes; \! is the escape there.- return name === 'csh' || name === 'tcsh' ? quoted.replace(/!/g, '\\!') : quoted+ if (name === 'csh' || name === 'tcsh') {+ // csh and tcsh expand !-history even inside single quotes; \! is the escape there.+ return quoted.replace(/!/g, '\\!')+ }++ if (POSIX_SHELLS.has(name)) {+ return quoted+ }++ return PLAIN_PATH.test(path) ? path : null}// C0 controls, DEL and C1 controls. A line editor acts on them inside any quoting (^U erases the@@ -233,7 +262,23 @@ export function bindTerminalDrop(const typePaths = (paths: string[]) => {const refused = paths.filter(hasControlCharacter)- const typed = paths.filter(path => !hasControlCharacter(path))+ const shellName = getShellName()+ const typed: string[] = []+ const unquotable: string[] = []++ for (const path of paths) {+ if (hasControlCharacter(path)) {+ continue+ }++ const quoted = quotePathForShell(path, shellName)++ if (quoted === null) {+ unquotable.push(path)+ } else {+ typed.push(quoted)+ }+ }if (refused.length) {notify({@@ -243,12 +288,20 @@ export function bindTerminalDrop(})}+ if (unquotable.length) {+ notify({+ kind: 'warning',+ title: translateNow('rightSidebar.terminalDropControlTitle'),+ message: translateNow('rightSidebar.terminalDropUnquotable', shellProgram(shellName), unquotable.join(', '))+ })+ }+if (!typed.length) {return}markActivity()- term.paste(`${typed.map(p => quotePathForShell(p, getShellName())).join(' ')} `)+ term.paste(`${typed.join(' ')} `)term.focus()triggerHaptic('selection')}diff --git a/apps/desktop/src/i18n/ar_chrome.ts b/apps/desktop/src/i18n/ar_chrome.tsindex 0e28a140ee6..32af052ebcb 100644--- a/apps/desktop/src/i18n/ar_chrome.ts+++ b/apps/desktop/src/i18n/ar_chrome.ts@@ -475,6 +475,7 @@ export const arChrome = {}},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `لا يمكن كتابة هذه الأسماء بأمان في ${shell}: ${paths}`,terminalReadOnly: 'مخرجات للقراءة فقط',terminalReadOnlyHelp:'للرد على المطالبات، أوقف الأمر الذي يعمل في الخلفية وشغّله في طرفية جديدة. تفتح الطرفية الجديدة صدفة منفصلة ولا تتصل بهذه العملية.',diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex d366f8701df..5520b71483e 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -4616,6 +4616,7 @@ export const deOverrides = {}},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `Diese Namen lassen sich in ${shell} nicht sicher eintippen: ${paths}`,aria: 'Rechte Sidebar',panelsAria: 'Panels der rechten Sidebar',files: 'Dateisystem',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex abaf846b37e..6da10ac5b1e 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4234,6 +4234,7 @@ export const en: Translations = {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}`,+ terminalDropUnquotable: (shell, paths) => `No safe way to type these names in ${shell}: ${paths}`,addToChat: 'Add to chat'},diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex 214fe509e83..c31277768a2 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -4600,6 +4600,7 @@ export const esOverrides = {}},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `Estos nombres no se pueden escribir de forma segura en ${shell}: ${paths}`,aria: 'Barra lateral derecha',panelsAria: 'Paneles de la barra lateral derecha',files: 'Sistema de archivos',diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex c7234f2a21b..c99e4b09319 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -4624,6 +4624,7 @@ export const frOverrides = {}},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `Impossible de saisir ces noms en toute sécurité dans ${shell} : ${paths}`,aria: 'Barre latérale droite',panelsAria: 'Panneaux de la barre latérale droite',files: 'Système de fichiers',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 656c08d6b4b..934661e6e55 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3028,6 +3028,7 @@ export const jaOverrides = {},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `これらの名前は ${shell} に安全に入力できません: ${paths}`,terminalReadOnly: '読み取り専用の出力',terminalReadOnlyHelp:'プロンプトに応答するには、バックグラウンドのコマンドを停止し、新しいターミナルで実行してください。新しいターミナルは別のシェルを開き、このプロセスには接続しません。',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 1fa8127263a..56e66486e90 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -3283,6 +3283,7 @@ export const ruOverrides = {}},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `Эти имена нельзя безопасно ввести в ${shell}: ${paths}`,terminalReadOnly: 'Вывод только для чтения',terminalReadOnlyHelp:'Чтобы ответить на запрос, остановите фоновую команду и запустите её в новом терминале. Он откроет отдельную оболочку и не подключится к этому процессу.',diff --git a/apps/desktop/src/i18n/types_right_sidebar.ts b/apps/desktop/src/i18n/types_right_sidebar.tsindex f7e5440bc64..083901ea1da 100644--- a/apps/desktop/src/i18n/types_right_sidebar.ts+++ b/apps/desktop/src/i18n/types_right_sidebar.ts@@ -48,5 +48,6 @@ export interface RightSidebarTranslations {terminalDropTooLarge: (names: string, limit: string) => stringterminalDropControlTitle: stringterminalDropControl: (paths: string) => string+ terminalDropUnquotable: (shell: string, paths: string) => stringaddToChat: string}diff --git a/apps/desktop/src/i18n/zh-hant_chrome.ts b/apps/desktop/src/i18n/zh-hant_chrome.tsindex 682771d20b4..07a0a9b3ece 100644--- a/apps/desktop/src/i18n/zh-hant_chrome.ts+++ b/apps/desktop/src/i18n/zh-hant_chrome.ts@@ -421,6 +421,7 @@ export const zhHantChrome = {},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `無法在 ${shell} 中安全地輸入這些名稱:${paths}`,terminalReadOnly: '唯讀輸出',terminalReadOnlyHelp:'如需回應提示,請停止背景命令,再於新終端機中執行。新終端機會開啟獨立的 shell,不會連線至此程序。',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 3ae27ad9899..a69d95df46a 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4030,6 +4030,7 @@ export const zhOverrides = {},rightSidebar: {+ terminalDropUnquotable: (shell, paths) => `无法在 ${shell} 中安全地输入这些名称:${paths}`,terminalReadOnly: '只读输出',terminalReadOnlyHelp:'如需回应提示,请停止后台命令,再在新终端中运行。新终端会打开独立的 shell,不会连接到此进程。',diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 32c0634695c..a4e286b542a 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -2688,6 +2688,7 @@"rightSidebar.terminalDropControlTitle","rightSidebar.terminalDropTooLarge","rightSidebar.terminalDropTooLargeTitle",+ "rightSidebar.terminalDropUnquotable","rightSidebar.terminalDropUploadFailed","rightSidebar.terminalHide","rightSidebar.terminalNew",