From efe012e0c8a0d3a8676e2bee5de73d5d93a6768f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:44:37 +0800 Subject: [PATCH] feat(terminal): continue Directory Picker with OSC 7 and reconnect fixes (#4113) * feat(terminal): add Directory Picker context chip * fix(terminal): bind directory reads to the exact SSH session * fix(terminal): follow manually changed working directories * fix(terminal): isolate cwd updates and gate local platform support * docs(terminal): research Directory Picker cross-platform follow-up * fix(terminal): confirm OSC 7 navigation and reset picker loading * fix(terminal): preserve active shell OSC 7 during directory refresh * test(terminal): retain cross-session OSC 7 submission guard --------- Co-authored-by: Joseph Hau --- application/i18n/locales/en/terminal.ts | 18 ++ application/i18n/locales/es/terminal.ts | 18 ++ application/i18n/locales/ru/terminal.ts | 18 ++ application/i18n/locales/zh-CN/terminal.ts | 18 ++ application/i18n/locales/zh-TW/terminal.ts | 18 ++ application/state/terminalCwdStore.test.ts | 17 ++ application/state/terminalCwdStore.ts | 15 +- .../state/terminalDirectoryController.test.ts | 230 ++++++++++++++++++ .../state/terminalDirectoryController.ts | 162 ++++++++++++ .../state/terminalDirectoryRegistry.test.ts | 87 +++++++ .../state/terminalDirectoryRegistry.ts | 58 +++++ application/state/useComposeBarHeight.ts | 4 +- .../state/useComposeDirectoryPicker.test.ts | 106 ++++++++ .../state/useComposeDirectoryPicker.ts | 94 +++++++ .../state/useTerminalDirectorySession.test.ts | 95 ++++++++ .../state/useTerminalDirectorySession.ts | 56 +++++ components/Terminal.tsx | 15 ++ .../tabs/TerminalBehaviorSettings.test.ts | 11 + .../tabs/TerminalBehaviorSettings.tsx | 8 + .../terminal/ComposeDirectoryPicker.tsx | 129 ++++++++++ .../terminal/TerminalComposeBar.test.tsx | 45 ++++ components/terminal/TerminalComposeBar.tsx | 8 +- components/terminal/TerminalView.tsx | 1 + components/terminal/useTerminalEffects.ts | 2 + .../TerminalLayerWorkspaceSection.tsx | 1 + .../terminal-compose-context/README.md | 4 +- .../directory-picker-cross-platform.md | 150 ++++++++++++ .../directory-picker-follow-up.md | 97 ++++++++ .../directory-picker.md | 4 + domain/directoryPicker.test.ts | 29 +++ domain/directoryPicker.ts | 44 ++++ domain/models/terminal.ts | 4 + domain/settingsSearchCatalog.ts | 7 + electron/bridges/sftpBridge.cjs | 6 +- .../sftpBridge.singleChannelDial.test.cjs | 39 +++ electron/bridges/sshBridge/sessionOps.cjs | 1 + .../bridges/sshBridge/sessionOps.cwd.test.cjs | 10 + electron/preload/api.cjs | 4 +- electron/preload/api.stageUploadFile.test.cjs | 13 + global.d.ts | 2 + .../services/terminalDirectory.local.test.ts | 161 ++++++++++++ .../services/terminalDirectory.ssh.test.ts | 113 +++++++++ .../services/terminalDirectory.test.ts | 81 ++++++ infrastructure/services/terminalDirectory.ts | 69 ++++++ types/global/netcatty-bridge-session.d.ts | 1 + 45 files changed, 2064 insertions(+), 9 deletions(-) create mode 100644 application/state/terminalDirectoryController.test.ts create mode 100644 application/state/terminalDirectoryController.ts create mode 100644 application/state/terminalDirectoryRegistry.test.ts create mode 100644 application/state/terminalDirectoryRegistry.ts create mode 100644 application/state/useComposeDirectoryPicker.test.ts create mode 100644 application/state/useComposeDirectoryPicker.ts create mode 100644 application/state/useTerminalDirectorySession.test.ts create mode 100644 application/state/useTerminalDirectorySession.ts create mode 100644 components/terminal/ComposeDirectoryPicker.tsx create mode 100644 docs/research/terminal-compose-context/directory-picker-cross-platform.md create mode 100644 docs/research/terminal-compose-context/directory-picker-follow-up.md create mode 100644 domain/directoryPicker.test.ts create mode 100644 domain/directoryPicker.ts create mode 100644 infrastructure/services/terminalDirectory.local.test.ts create mode 100644 infrastructure/services/terminalDirectory.ssh.test.ts create mode 100644 infrastructure/services/terminalDirectory.test.ts create mode 100644 infrastructure/services/terminalDirectory.ts diff --git a/application/i18n/locales/en/terminal.ts b/application/i18n/locales/en/terminal.ts index 800059e43..c15608506 100644 --- a/application/i18n/locales/en/terminal.ts +++ b/application/i18n/locales/en/terminal.ts @@ -1,6 +1,24 @@ import type { Messages } from '../types'; export const enTerminalMessages: Messages = { + 'terminal.directory.open': 'Current directory: {path}. Change directory', + 'terminal.directory.unknown': 'Directory unknown', + 'terminal.directory.search': 'Search child directories...', + 'terminal.directory.directories': 'Directories', + 'terminal.directory.parent': '.. (Parent directory)', + 'terminal.directory.loading': 'Reading directories...', + 'terminal.directory.empty': 'No child directories', + 'terminal.directory.noMatches': 'No matching directories', + 'terminal.directory.hidden': 'Show hidden directories', + 'terminal.directory.refresh': 'Refresh', + 'terminal.directory.unavailable': 'Directory navigation is unavailable for this session.', + 'terminal.directory.busy': 'Wait for an empty shell prompt.', + 'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.', + 'terminal.directory.changeFailed': 'Could not confirm the directory change. Refresh before retrying.', + 'terminal.directory.unsupportedPath': 'This directory name cannot be sent safely to the terminal.', + 'settings.terminal.behavior.contextChips': 'Context Chips', + 'settings.terminal.behavior.contextChips.desc': 'Show the context toolbar below quick commands in the compose bar.', + 'terminal.toolbar.openSessionLog': 'Open session log', 'terminal.toolbar.sessionLogActions': 'Session log actions', 'terminal.toolbar.sessionLog.menu': 'Session log', diff --git a/application/i18n/locales/es/terminal.ts b/application/i18n/locales/es/terminal.ts index 7967f3e1e..be1b05dc1 100644 --- a/application/i18n/locales/es/terminal.ts +++ b/application/i18n/locales/es/terminal.ts @@ -1,6 +1,24 @@ import type { Messages } from '../types'; export const esTerminalMessages: Messages = { + 'terminal.directory.open': 'Directorio actual: {path}. Cambiar directorio', + 'terminal.directory.unknown': 'Directorio desconocido', + 'terminal.directory.search': 'Buscar subdirectorios...', + 'terminal.directory.directories': 'Directorios', + 'terminal.directory.parent': '.. (Directorio padre)', + 'terminal.directory.loading': 'Leyendo directorios...', + 'terminal.directory.empty': 'Sin subdirectorios', + 'terminal.directory.noMatches': 'Sin directorios coincidentes', + 'terminal.directory.hidden': 'Mostrar directorios ocultos', + 'terminal.directory.refresh': 'Actualizar', + 'terminal.directory.unavailable': 'La navegación de directorios no está disponible para esta sesión.', + 'terminal.directory.busy': 'Espera a que el prompt esté vacío.', + 'terminal.directory.readFailed': 'No se pudo leer el directorio. Actualiza e inténtalo de nuevo.', + 'terminal.directory.changeFailed': 'No se pudo confirmar el cambio. Actualiza antes de reintentar.', + 'terminal.directory.unsupportedPath': 'No se puede enviar este nombre de directorio de forma segura.', + 'settings.terminal.behavior.contextChips': 'Context Chips', + 'settings.terminal.behavior.contextChips.desc': 'Mostrar la barra de contexto debajo de los comandos rápidos.', + 'terminal.toolbar.openSessionLog': 'Abrir registro de sesión', 'terminal.toolbar.sessionLogActions': 'Acciones del registro', 'terminal.toolbar.sessionLog.menu': 'Registro de sesión', diff --git a/application/i18n/locales/ru/terminal.ts b/application/i18n/locales/ru/terminal.ts index fad036858..4e0465709 100644 --- a/application/i18n/locales/ru/terminal.ts +++ b/application/i18n/locales/ru/terminal.ts @@ -1,6 +1,24 @@ import type { Messages } from '../types'; export const ruTerminalMessages: Messages = { + 'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог', + 'terminal.directory.unknown': 'Каталог неизвестен', + 'terminal.directory.search': 'Поиск подкаталогов...', + 'terminal.directory.directories': 'Каталоги', + 'terminal.directory.parent': '.. (Родительский каталог)', + 'terminal.directory.loading': 'Чтение каталогов...', + 'terminal.directory.empty': 'Нет подкаталогов', + 'terminal.directory.noMatches': 'Нет подходящих каталогов', + 'terminal.directory.hidden': 'Показывать скрытые каталоги', + 'terminal.directory.refresh': 'Обновить', + 'terminal.directory.unavailable': 'Навигация по каталогам недоступна для этого сеанса.', + 'terminal.directory.busy': 'Дождитесь пустой командной строки.', + 'terminal.directory.readFailed': 'Не удалось прочитать каталог. Попробуйте обновить.', + 'terminal.directory.changeFailed': 'Не удалось подтвердить смену каталога. Обновите перед повтором.', + 'terminal.directory.unsupportedPath': 'Это имя каталога нельзя безопасно передать в терминал.', + 'settings.terminal.behavior.contextChips': 'Context Chips', + 'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами.', + 'terminal.toolbar.openSessionLog': 'Открыть журнал сессии', 'terminal.toolbar.sessionLogActions': 'Действия с журналом', 'terminal.toolbar.sessionLog.menu': 'Журнал сессии', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index ac590e3f8..5b126de33 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -1,6 +1,24 @@ import type { Messages } from '../types'; export const zhCNTerminalMessages: Messages = { + 'terminal.directory.open': '当前目录:{path}。更改目录', + 'terminal.directory.unknown': '目录未知', + 'terminal.directory.search': '搜索当前目录下的文件夹…', + 'terminal.directory.directories': '目录', + 'terminal.directory.parent': '..(父目录)', + 'terminal.directory.loading': '正在读取目录…', + 'terminal.directory.empty': '没有子目录', + 'terminal.directory.noMatches': '没有匹配的子目录', + 'terminal.directory.hidden': '显示隐藏目录', + 'terminal.directory.refresh': '刷新', + 'terminal.directory.unavailable': '此会话暂不支持目录导航。', + 'terminal.directory.busy': '请等待终端回到空命令提示符。', + 'terminal.directory.readFailed': '无法读取此目录,请刷新重试。', + 'terminal.directory.changeFailed': '未能确认目录切换,请刷新后重试。', + 'terminal.directory.unsupportedPath': '此目录名称暂不支持快捷切换。', + 'settings.terminal.behavior.contextChips': 'Context Chips 上下文工具栏', + 'settings.terminal.behavior.contextChips.desc': '在撰写栏的快捷命令下方显示上下文工具栏。', + 'terminal.toolbar.openSessionLog': '打开会话日志', 'terminal.toolbar.sessionLogActions': '会话日志操作', 'terminal.toolbar.sessionLog.menu': '会话日志', diff --git a/application/i18n/locales/zh-TW/terminal.ts b/application/i18n/locales/zh-TW/terminal.ts index 5f25a5ba5..9bd35a82f 100644 --- a/application/i18n/locales/zh-TW/terminal.ts +++ b/application/i18n/locales/zh-TW/terminal.ts @@ -1,6 +1,24 @@ import type { Messages } from '../types'; export const zhTWTerminalMessages: Messages = { + 'terminal.directory.open': '目前目錄:{path}。變更目錄', + 'terminal.directory.unknown': '目錄未知', + 'terminal.directory.search': '搜尋目前目錄下的資料夾…', + 'terminal.directory.directories': '目錄', + 'terminal.directory.parent': '..(父目錄)', + 'terminal.directory.loading': '正在讀取目錄…', + 'terminal.directory.empty': '沒有子目錄', + 'terminal.directory.noMatches': '沒有符合的子目錄', + 'terminal.directory.hidden': '顯示隱藏目錄', + 'terminal.directory.refresh': '重新整理', + 'terminal.directory.unavailable': '此工作階段暫不支援目錄導覽。', + 'terminal.directory.busy': '請等待終端回到空白命令提示字元。', + 'terminal.directory.readFailed': '無法讀取此目錄,請重新整理後重試。', + 'terminal.directory.changeFailed': '未能確認目錄切換,請重新整理後重試。', + 'terminal.directory.unsupportedPath': '此目錄名稱暫不支援快速切換。', + 'settings.terminal.behavior.contextChips': 'Context Chips 上下文工具列', + 'settings.terminal.behavior.contextChips.desc': '在撰寫列的快捷命令下方顯示上下文工具列。', + 'terminal.toolbar.openSessionLog': '開啟工作階段日誌', 'terminal.toolbar.sessionLogActions': '工作階段日誌操作', 'terminal.toolbar.sessionLog.menu': '工作階段日誌', diff --git a/application/state/terminalCwdStore.test.ts b/application/state/terminalCwdStore.test.ts index be2cb399a..999dcb247 100644 --- a/application/state/terminalCwdStore.test.ts +++ b/application/state/terminalCwdStore.test.ts @@ -30,3 +30,20 @@ test('terminalCwdStore bumps version only when cwd or provenance changes', () => unsubscribe(); assert.ok(versions.length >= 2); }); + +test('session revisions isolate terminals and retain identical OSC 7 reports without rerendering', () => { + const a = 'revision-a'; const b = 'revision-b'; + terminalCwdStore.setCwd(a, '/same', 'osc7'); + const revisionA = terminalCwdStore.getSessionRevision(a); + terminalCwdStore.setCwd(b, '/elsewhere', 'osc7'); + assert.equal(terminalCwdStore.getSessionRevision(a), revisionA); + const globalVersion = terminalCwdStore.getVersion(); + assert.equal(terminalCwdStore.setCwd(a, '/same', 'osc7'), false); + assert.ok(terminalCwdStore.getSessionRevision(a) > revisionA); + assert.equal(terminalCwdStore.getVersion(), globalVersion); + const revisionB = terminalCwdStore.getSessionRevision(b); + terminalCwdStore.prune(new Set([b])); + assert.equal(terminalCwdStore.getSessionRevision(a), 0); + assert.equal(terminalCwdStore.getSessionRevision(b), revisionB); + terminalCwdStore.prune(new Set()); +}); diff --git a/application/state/terminalCwdStore.ts b/application/state/terminalCwdStore.ts index 14162b2f9..53d642384 100644 --- a/application/state/terminalCwdStore.ts +++ b/application/state/terminalCwdStore.ts @@ -10,11 +10,16 @@ export type TerminalCwdSource = "osc7" | "inferred" | "backend-strict" | "backen class TerminalCwdStore { private cwdBySession = new Map(); private sourceBySession = new Map(); + private revisionBySession = new Map(); + private revision = 0; private version = 0; private listeners = new Set(); getVersion = (): number => this.version; + /** Tracks reports for one session, including unchanged authoritative OSC 7. */ + getSessionRevision = (sessionId: string): number => this.revisionBySession.get(sessionId) ?? 0; + getCwd = (sessionId: string | null | undefined): string | null => { if (!sessionId) return null; return this.cwdBySession.get(sessionId) ?? null; @@ -39,7 +44,10 @@ class TerminalCwdStore { const nextSource = next ? (source ?? (current === next ? currentSource : undefined) ?? "unknown") : undefined; - if (current === next && currentSource === nextSource) return false; + if (current === next && currentSource === nextSource) { + if (nextSource === 'osc7') this.revisionBySession.set(sessionId, ++this.revision); + return false; + } if (next) { this.cwdBySession.set(sessionId, next); @@ -48,6 +56,7 @@ class TerminalCwdStore { this.cwdBySession.delete(sessionId); this.sourceBySession.delete(sessionId); } + this.revisionBySession.set(sessionId, ++this.revision); this.version += 1; for (const listener of this.listeners) { listener(); @@ -61,9 +70,13 @@ class TerminalCwdStore { if (!validSessionIds.has(sessionId)) { this.cwdBySession.delete(sessionId); this.sourceBySession.delete(sessionId); + this.revisionBySession.delete(sessionId); changed = true; } } + for (const id of this.revisionBySession.keys()) { + if (!validSessionIds.has(id)) this.revisionBySession.delete(id); + } if (!changed) return; this.version += 1; for (const listener of this.listeners) { diff --git a/application/state/terminalDirectoryController.test.ts b/application/state/terminalDirectoryController.test.ts new file mode 100644 index 000000000..79108d052 --- /dev/null +++ b/application/state/terminalDirectoryController.test.ts @@ -0,0 +1,230 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createTerminalDirectoryController } from './terminalDirectoryController'; +import { terminalCwdStore } from './terminalCwdStore'; +import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory'; + +function setup(overrides: Partial = {}) { + let cwd = '/old'; let ready = true; let current = true; + const writes: string[] = []; + const published: string[] = []; + const controller = createTerminalDirectoryController({ + sessionId: 'test-directory', confirmationMs: 10, + io: { cwd: async () => cwd, list: async () => ({ entries: [], home: null }), realpath: async path => path, + write: data => { writes.push(data); cwd = '/next'; }, ...overrides }, + isCurrent: () => current, isReady: () => ready, + publish: value => { published.push(value); terminalCwdStore.setCwd('test-directory', value, 'backend-strict'); }, + }); + return { controller, writes, published, busy: () => { ready = false; }, stale: () => { current = false; } }; +} + +test('navigation writes one quoted cd and waits for actual cwd before confirming', async () => { + const ctx = setup(); const accepted: string[] = []; + await ctx.controller.change('/next', new AbortController().signal, () => accepted.push('accepted')); + assert.deepEqual(ctx.writes, ["cd -- '/next'\r"]); + assert.deepEqual(accepted, ['accepted']); + assert.deepEqual(ctx.published, ['/next']); + ctx.controller.dispose(); +}); + +test('busy, control-character and stale sessions never receive bytes', async () => { + const ctx = setup(); ctx.busy(); + await assert.rejects(ctx.controller.change('/next', new AbortController().signal, () => {}), { code: 'busy' }); + const invalid = setup(); + await assert.rejects(invalid.controller.change('/next\n', new AbortController().signal, () => {}), { code: 'unsupportedPath' }); + const stale = setup(); stale.stale(); + await assert.rejects(stale.controller.change('/next', new AbortController().signal, () => {}), { code: 'unavailable' }); + assert.deepEqual([...ctx.writes, ...invalid.writes, ...stale.writes], []); +}); + +test('rechecks readiness after async path resolution; double submission is rejected', async () => { + let finish!: (path: string) => void; + const ctx = setup({ realpath: () => new Promise(resolve => { finish = resolve; }) }); + const first = ctx.controller.change('/next', new AbortController().signal, () => {}); + await assert.rejects(ctx.controller.change('/other', new AbortController().signal, () => {}), { code: 'busy' }); + ctx.busy(); finish('/next'); + await assert.rejects(first, { code: 'busy' }); + assert.deepEqual(ctx.writes, []); +}); + +test('a disposed connection rejects delayed reads and cannot publish into a new generation', async () => { + let finish!: (cwd: string) => void; + const ctx = setup({ cwd: () => new Promise(resolve => { finish = resolve; }) }); + const read = ctx.controller.refresh(); + ctx.controller.dispose(); finish('/stale'); + await assert.rejects(read, { code: 'unavailable' }); + assert.deepEqual(ctx.published, []); +}); + +test('a failed cd keeps the observed cwd and never retries the write', async () => { + const ctx = setup({ write: () => {}, cwd: async () => '/old' }); + await assert.rejects(ctx.controller.change('/missing', new AbortController().signal, () => {}), { code: 'changeFailed' }); + assert.ok(ctx.published.every(value => value === '/old')); +}); + +test('directory symlinks confirm against physical cwd', async () => { + const ctx = setup({ realpath: async path => path === '/link' ? '/real' : path, cwd: async () => '/real' }); + await ctx.controller.change('/link', new AbortController().signal, () => {}); + assert.equal(ctx.published.at(-1), '/real'); +}); + +test('output arriving during an old cwd query retains one fresh follow-up query', async () => { + let finish!: (cwd: string) => void; + let reads = 0; + const ctx = setup({ cwd: () => { + reads++; + return reads === 1 ? new Promise(resolve => { finish = resolve; }) : Promise.resolve('/after-cd'); + } }); + const oldRead = ctx.controller.refresh(); + const queued = ctx.controller.refresh(); + finish('/before-cd'); + await Promise.all([oldRead, queued]); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(reads, 2); + assert.equal(ctx.published.at(-1), '/after-cd'); + ctx.controller.dispose(); +}); + +test('another terminal updating cannot override the current terminal strict cwd result', async t => { + const id = 'strict-after-other-session'; + let finish!: (cwd: string) => void; + const published: string[] = []; + terminalCwdStore.setCwd(id, '/stale-osc7', 'stale'); + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: () => new Promise(resolve => { finish = resolve; }), + list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} }, + publish: value => { published.push(value); terminalCwdStore.setCwd(id, value, 'backend-strict'); }, + }); + t.after(() => controller.dispose()); + const pending = controller.refresh(); + terminalCwdStore.setCwd('unrelated-session', '/other', 'osc7'); + finish('/actual-after-cd'); + assert.equal(await pending, '/actual-after-cd'); + assert.deepEqual(published, ['/actual-after-cd']); + assert.equal(terminalCwdStore.getCwd(id), '/actual-after-cd'); +}); + +test('another terminal cannot turn this submission pre-write OSC 7 into a fresh report', async t => { + const id = 'pre-write-osc7-after-other-session'; + let finish!: (cwd: string) => void; + const published: string[] = []; + terminalCwdStore.setCwd(id, '/before', 'osc7'); + const controller = createTerminalDirectoryController({ + sessionId: id, confirmationMs: 20, isCurrent: () => true, isReady: () => true, + io: { cwd: () => new Promise(resolve => { finish = resolve; }), + list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} }, + publish: cwd => { published.push(cwd); terminalCwdStore.setCwd(id, cwd, 'backend-strict'); }, + }); + t.after(() => controller.dispose()); + const changing = controller.change('/after', new AbortController().signal, () => {}); + await new Promise(resolve => setImmediate(resolve)); + terminalCwdStore.setCwd(id + '-other', '/other', 'osc7'); + finish('/after'); + await changing; + assert.deepEqual(published, ['/after']); + assert.equal(terminalCwdStore.getCwd(id), '/after'); +}); + +for (const nextCwd of ['/new-osc7', '/original']) { + test(`a later OSC 7 report from this terminal wins (${nextCwd})`, async t => { + const id = 'same-session-osc7-' + nextCwd; + let finish!: (cwd: string) => void; + const published: string[] = []; + terminalCwdStore.setCwd(id, '/original', 'stale'); + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: () => new Promise(resolve => { finish = resolve; }), + list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} }, + publish: value => { published.push(value); }, + }); + t.after(() => controller.dispose()); + const pending = controller.refresh(); + terminalCwdStore.setCwd(id, nextCwd, 'osc7'); + finish('/older-backend-result'); + assert.equal(await pending, nextCwd); + assert.deepEqual(published, []); + }); +} + +for (const probe of ['fails', 'stalls'] as const) { + test(`a fresh post-write OSC 7 confirms navigation when the strict cwd probe ${probe}`, { timeout: 2000 }, async t => { + const id = 'osc7-confirm-' + probe; + const writes: string[] = []; + terminalCwdStore.setCwd(id, '/old', 'osc7'); + const controller = createTerminalDirectoryController({ + sessionId: id, confirmationMs: 1000, isCurrent: () => true, isReady: () => true, + io: { + cwd: () => probe === 'fails' ? Promise.reject(new Error('no process cwd support')) : new Promise(() => {}), + list: async () => ({ entries: [], home: null }), realpath: async value => value, + write: data => { + writes.push(data); + setImmediate(() => terminalCwdStore.setCwd(id, '/next', 'osc7')); + }, + }, + publish() { assert.fail('an unavailable probe must not publish a guessed cwd'); }, + }); + t.after(() => controller.dispose()); + await controller.change('/next', new AbortController().signal, () => {}); + assert.deepEqual(writes, ["cd -- '/next'\r"]); + assert.equal(controller.hasConfirmedCwd(), true); + }); +} + +test('navigation can probe past its pre-write OSC 7 when the shell stops reporting', async t => { + const id = 'probe-after-pre-write-osc7'; + terminalCwdStore.setCwd(id, '/before', 'osc7'); + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => '/after', list: async () => ({ entries: [], home: null }), + realpath: async value => value, write() {} }, + publish: cwd => terminalCwdStore.setCwd(id, cwd, 'backend-strict'), + }); + t.after(() => controller.dispose()); + await controller.change('/after', new AbortController().signal, () => {}); + assert.equal(terminalCwdStore.getCwd(id), '/after'); + assert.equal(terminalCwdStore.getSource(id), 'backend-strict'); +}); + +for (const report of ['stale', 'other-session', 'other-source', 'fresh-unchanged'] as const) { + test(`OSC 7 confirmation uses this submission's session revision (${report})`, { timeout: 2000 }, async t => { + const id = 'osc7-revision-confirm-' + report; + terminalCwdStore.setCwd(id, '/next', 'osc7'); + const controller = createTerminalDirectoryController({ + sessionId: id, confirmationMs: 20, isCurrent: () => true, isReady: () => true, + io: { + cwd: async () => { throw new Error('no process cwd support'); }, + list: async () => ({ entries: [], home: null }), realpath: async value => value, + write() { + if (report !== 'stale') setImmediate(() => terminalCwdStore.setCwd( + report === 'other-session' ? id + '-other' : id, '/next', report === 'other-source' ? 'inferred' : 'osc7', + )); + }, + }, + publish() {}, + }); + t.after(() => controller.dispose()); + const change = controller.change('/next', new AbortController().signal, () => {}); + if (report === 'fresh-unchanged') await change; + else await assert.rejects(change, { code: 'changeFailed' }); + }); +} + +for (const cancellation of ['abort', 'dispose'] as const) { + test(`a fresh OSC 7 cannot confirm a cancelled directory change (${cancellation})`, { timeout: 2000 }, async t => { + const id = 'osc7-cancel-' + cancellation; + const abort = new AbortController(); + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: () => new Promise(() => {}), list: async () => ({ entries: [], home: null }), + realpath: async value => value, + write() { setImmediate(() => { + if (cancellation === 'abort') abort.abort(); else controller.dispose(); + terminalCwdStore.setCwd(id, '/next', 'osc7'); + }); } }, + publish() {}, + }); + t.after(() => controller.dispose()); + await assert.rejects(controller.change('/next', abort.signal, () => {}), { code: 'unavailable' }); + }); +} diff --git a/application/state/terminalDirectoryController.ts b/application/state/terminalDirectoryController.ts new file mode 100644 index 000000000..2436611a0 --- /dev/null +++ b/application/state/terminalDirectoryController.ts @@ -0,0 +1,162 @@ +import { DirectoryPickerError, isDirectoryPath } from '../../domain/directoryPicker'; +import { resolveInteractiveTerminalCdIntent } from '../../domain/sessionRestore'; +import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory'; +import { terminalCwdStore } from './terminalCwdStore'; + +export type TerminalDirectoryController = ReturnType; + +/** One registration represents one connected interactive shell generation. */ +export function createTerminalDirectoryController(options: { + sessionId: string; + io: TerminalDirectoryIO; + isCurrent: () => boolean; + isReady: () => boolean; + publish: (cwd: string) => void; + confirmationMs?: number; +}) { + let disposed = false; + let changing = false; + let confirmed = false; + let refreshing: Promise | null = null; + let refreshAgain = false; + const lifetime = new AbortController(); + const current = () => !disposed && options.isCurrent(); + function check(signal?: AbortSignal) { + if (!current() || signal?.aborted) throw new DirectoryPickerError('unavailable'); + } + function ready() { + check(); + if (!options.isReady()) throw new DirectoryPickerError('busy'); + } + function bounded(task: Promise, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const finish = (error?: unknown, value?: T) => { + clearTimeout(timer); + lifetime.signal.removeEventListener('abort', cancel); + signal?.removeEventListener('abort', cancel); + if (error) reject(error); else resolve(value!); + }; + const cancel = () => finish(new DirectoryPickerError('unavailable')); + const timer = setTimeout(() => finish(new DirectoryPickerError('readFailed')), 5000); + lifetime.signal.addEventListener('abort', cancel, { once: true }); + signal?.addEventListener('abort', cancel, { once: true }); + if (signal?.aborted || lifetime.signal.aborted) cancel(); + task.then(value => finish(undefined, value), error => finish(error)); + }); + } + async function refresh(submittedRevision?: number): Promise { + check(); + const activeShellCwd = () => { + const cwd = terminalCwdStore.getCwd(options.sessionId); + return cwd && terminalCwdStore.getSource(options.sessionId) === 'osc7' + && (submittedRevision === undefined || terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision) + ? cwd : null; + }; + // A process probe may read the outer PTY shell while a nested shell is + // active. OSC 7 remains authoritative across debounce delays, completion + // events and picker remounts. Only a cd submission may probe past its own + // pre-write report while waiting for fresh confirmation. + const reported = activeShellCwd(); + if (reported) { confirmed = true; return reported; } + if (refreshing) { + // Output may settle while a pre-cd query is still in flight. Keep one + // follow-up query so that its older result cannot be the last update. + refreshAgain = true; + return refreshing; + } + const pending = (async () => { + const cwd = await bounded(options.io.cwd()); + check(); + const reported = activeShellCwd(); + const live = terminalCwdStore.getCwd(options.sessionId); + confirmed = true; + if (reported) return reported; + if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale') options.publish(cwd); + return cwd; + })(); + refreshing = pending; + try { return await pending; } finally { + if (refreshing === pending) refreshing = null; + if (refreshAgain && current()) { + refreshAgain = false; + void refresh().catch(() => {}); + } + } + } + async function change(path: string, signal: AbortSignal, accepted: () => void, expectedCwd?: string) { + ready(); + if (changing) throw new DirectoryPickerError('busy'); + const intent = isDirectoryPath(path) ? resolveInteractiveTerminalCdIntent(path) : null; + if (!intent) throw new DirectoryPickerError('unsupportedPath'); + changing = true; + let confirmationFinished = false; + try { + const canonical = await bounded(options.io.realpath(path, signal), signal); + check(signal); + ready(); // The shell can become busy while resolving a remote symlink. + if (expectedCwd && terminalCwdStore.getCwd(options.sessionId) !== expectedCwd) throw new DirectoryPickerError('unavailable'); + const submittedRevision = terminalCwdStore.getSessionRevision(options.sessionId); + options.io.write(intent.command + '\r'); + accepted(); + const deadline = Date.now() + (options.confirmationMs ?? 8000); + const hasFreshOsc7 = () => { + const cwd = terminalCwdStore.getCwd(options.sessionId); + return terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision + && terminalCwdStore.getSource(options.sessionId) === 'osc7' + && (cwd === path || cwd === canonical); + }; + const pause = () => new Promise(resolve => { + const done = () => { clearTimeout(timer); lifetime.signal.removeEventListener('abort', done); resolve(); }; + const timer = setTimeout(done, 200); + lifetime.signal.addEventListener('abort', done, { once: true }); + }); + const confirmFromProbe = async () => { + while (!confirmationFinished && Date.now() < deadline) { + check(signal); + if (hasFreshOsc7()) return; + if (options.isReady()) { + try { + const cwd = await refresh(submittedRevision); + check(signal); + if (cwd === path || cwd === canonical || await bounded(options.io.realpath(cwd, signal), signal) === canonical) return; + } catch (error) { + if (!current() || signal.aborted) throw error; + } + } + await pause(); + } + if (!confirmationFinished) throw new DirectoryPickerError('changeFailed'); + }; + // OSC 7 is authoritative even when process cwd lookup is unavailable or + // stalled. Poll revisions too: an unchanged OSC 7 path emits no store event. + const confirmFromOsc7 = async () => { + while (!confirmationFinished) { + check(signal); + if (hasFreshOsc7()) return; + if (Date.now() >= deadline) throw new DirectoryPickerError('changeFailed'); + await pause(); + } + }; + await Promise.race([confirmFromProbe(), confirmFromOsc7()]); + check(signal); + confirmed = true; + } finally { confirmationFinished = true; changing = false; } + } + return { + refresh: () => refresh(), + hasConfirmedCwd: () => confirmed, + async home() { + check(); + const result = await bounded(options.io.home?.() ?? Promise.resolve(null)); + check(); return result; + }, + async list(path: string, signal: AbortSignal) { + check(signal); + const result = await bounded(options.io.list(path, signal), signal); + check(signal); + return result; + }, + change, + dispose() { disposed = true; lifetime.abort(); }, + }; +} diff --git a/application/state/terminalDirectoryRegistry.test.ts b/application/state/terminalDirectoryRegistry.test.ts new file mode 100644 index 000000000..0b7ac7e8f --- /dev/null +++ b/application/state/terminalDirectoryRegistry.test.ts @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createTerminalDirectoryController } from './terminalDirectoryController'; +import { terminalCwdStore } from './terminalCwdStore'; +import { + observeTerminalDirectory, registerTerminalDirectory, + refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh, +} from './terminalDirectoryRegistry'; + +test('manual terminal output refreshes cwd without a trusted command-completion event', async t => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + let cwd = '/before'; let reads = 0; + const published: string[] = []; + const controller = createTerminalDirectoryController({ + sessionId: 'unrecognized-prompt', isCurrent: () => true, isReady: () => false, + io: { cwd: async () => { reads++; return cwd; }, + list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} }, + publish: value => { published.push(value); }, + }); + const unregister = registerTerminalDirectory('unrecognized-prompt', controller); + const stopObserving = observeTerminalDirectory('unrecognized-prompt'); + t.after(() => { stopObserving(); unregister(); }); + cwd = '/after-manual-cd'; + // Multiple prompt/output chunks produce just one read. No trusted prompt + // detection, command-completed callback, or parsed `cd` is involved. + scheduleObservedTerminalDirectoryRefresh('unrecognized-prompt'); + t.mock.timers.tick(80); + scheduleObservedTerminalDirectoryRefresh('unrecognized-prompt'); + t.mock.timers.tick(149); + assert.equal(reads, 0); + t.mock.timers.tick(1); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(published, ['/after-manual-cd']); + assert.equal(reads, 1); + t.mock.timers.tick(60_000); + assert.equal(reads, 1, 'no polling after output has settled'); +}); + +test('settled output and prompt completion preserve the active nested shell OSC 7 cwd', async t => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const id = 'nested-shell-output'; + const published: string[] = []; + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + // The PTY process stays in its original directory while a child shell + // runs in /. Its cwd is only a fallback for shells without OSC 7. + io: { cwd: async () => '/outer-shell', list: async () => ({ entries: [], home: null }), + realpath: async value => value, write() {} }, + publish: cwd => { published.push(cwd); terminalCwdStore.setCwd(id, cwd, 'backend-strict'); }, + }); + const unregister = registerTerminalDirectory(id, controller); + const stopObserving = observeTerminalDirectory(id); + t.after(() => { stopObserving(); unregister(); }); + scheduleObservedTerminalDirectoryRefresh(id); + terminalCwdStore.setCwd(id, '/', 'osc7'); + t.mock.timers.tick(150); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(terminalCwdStore.getCwd(id), '/'); + // Later output chunks, prompt completion and reopening/manual refresh must + // not treat that same active-shell report as stale merely due to timing. + scheduleObservedTerminalDirectoryRefresh(id); + t.mock.timers.tick(150); + refreshObservedTerminalDirectory(id); + assert.equal(await controller.refresh(), '/'); + assert.deepEqual(published, []); + assert.equal(terminalCwdStore.getSource(id), 'osc7'); +}); + +test('disabling chips cancels a queued output refresh and ignores future terminal output', async t => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + let reads = 0; + const controller = createTerminalDirectoryController({ + sessionId: 'hidden-chips', isCurrent: () => true, isReady: () => true, + io: { cwd: async () => { reads++; return '/unused'; }, list: async () => ({ entries: [], home: null }), + realpath: async value => value, write() {} }, publish() {}, + }); + const unregister = registerTerminalDirectory('hidden-chips', controller); + t.after(unregister); + const stopObserving = observeTerminalDirectory('hidden-chips'); + scheduleObservedTerminalDirectoryRefresh('hidden-chips'); + stopObserving(); + t.mock.timers.tick(1000); + scheduleObservedTerminalDirectoryRefresh('hidden-chips'); + t.mock.timers.tick(1000); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(reads, 0); +}); diff --git a/application/state/terminalDirectoryRegistry.ts b/application/state/terminalDirectoryRegistry.ts new file mode 100644 index 000000000..3acc355d2 --- /dev/null +++ b/application/state/terminalDirectoryRegistry.ts @@ -0,0 +1,58 @@ +import type { TerminalDirectoryController } from './terminalDirectoryController'; + +const sessions = new Map(); +const consumers = new Map(); +const scheduledRefreshes = new Map>(); +const OUTPUT_SETTLE_MS = 150; + +function cancelScheduledRefresh(id: string) { + const timer = scheduledRefreshes.get(id); + if (timer !== undefined) clearTimeout(timer); + scheduledRefreshes.delete(id); +} +const listeners = new Set<() => void>(); +export const subscribeTerminalDirectories = (listener: () => void) => { + listeners.add(listener); + return () => { listeners.delete(listener); }; +}; +export const getTerminalDirectory = (id: string) => sessions.get(id) ?? null; +export function registerTerminalDirectory(id: string, controller: TerminalDirectoryController) { + cancelScheduledRefresh(id); + sessions.set(id, controller); + listeners.forEach(listener => listener()); + return () => { + controller.dispose(); + if (sessions.get(id) !== controller) return; + cancelScheduledRefresh(id); + sessions.delete(id); + listeners.forEach(listener => listener()); + }; +} +export function observeTerminalDirectory(id: string) { + consumers.set(id, (consumers.get(id) ?? 0) + 1); + return () => { + const next = (consumers.get(id) ?? 1) - 1; + if (next) consumers.set(id, next); + else { consumers.delete(id); cancelScheduledRefresh(id); } + }; +} +/** Called by the existing command completion path, only while chips are visible. */ +export function refreshObservedTerminalDirectory(id: string) { + cancelScheduledRefresh(id); + if (consumers.has(id)) void sessions.get(id)?.refresh().catch(() => {}); +} + +/** + * Shells with custom prompts may emit neither OSC 7/133 nor a trusted command + * completion. Debounce actual output/submission activity instead of polling or + * interpreting `cd` text. The controller prefers active-shell OSC 7 and uses + * the bound shell's process cwd only as a fallback. + */ +export function scheduleObservedTerminalDirectoryRefresh(id: string) { + if (!consumers.has(id) || !sessions.has(id)) return; + cancelScheduledRefresh(id); + scheduledRefreshes.set(id, setTimeout(() => { + scheduledRefreshes.delete(id); + refreshObservedTerminalDirectory(id); + }, OUTPUT_SETTLE_MS)); +} diff --git a/application/state/useComposeBarHeight.ts b/application/state/useComposeBarHeight.ts index 4f06377ae..8f89c6dd4 100644 --- a/application/state/useComposeBarHeight.ts +++ b/application/state/useComposeBarHeight.ts @@ -2,8 +2,8 @@ import { useCallback } from 'react'; import { STORAGE_KEY_COMPOSE_BAR_HEIGHT } from '../../infrastructure/config/storageKeys'; import { useStoredNumber } from './useStoredNumber'; -export const COMPOSE_BAR_HEIGHT_DEFAULT = 120; -export const COMPOSE_BAR_HEIGHT_MIN = 72; +export const COMPOSE_BAR_HEIGHT_DEFAULT = 144; +export const COMPOSE_BAR_HEIGHT_MIN = 104; export const COMPOSE_BAR_HEIGHT_MAX = 360; const HEIGHT_CLAMP = { min: COMPOSE_BAR_HEIGHT_MIN, max: COMPOSE_BAR_HEIGHT_MAX }; diff --git a/application/state/useComposeDirectoryPicker.test.ts b/application/state/useComposeDirectoryPicker.test.ts new file mode 100644 index 000000000..6d1c91e1e --- /dev/null +++ b/application/state/useComposeDirectoryPicker.test.ts @@ -0,0 +1,106 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import React from 'react'; +import { act, create, type ReactTestRenderer } from 'react-test-renderer'; +import { useComposeDirectoryPicker } from './useComposeDirectoryPicker'; +import { createTerminalDirectoryController } from './terminalDirectoryController'; +import { refreshObservedTerminalDirectory, registerTerminalDirectory } from './terminalDirectoryRegistry'; +import { terminalCwdStore } from './terminalCwdStore'; +import { DirectoryPickerError } from '../../domain/directoryPicker'; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +test('opening loads children once; search is local; unmount stops chip refresh demand', async () => { + let reads = 0; let probes = 0; + const id = 'hook-directory'; + const controller = createTerminalDirectoryController({ sessionId: id, + io: { cwd: async () => { probes++; return '/base'; }, realpath: async path => path, write() {}, + list: async () => { reads++; return { home: '/base', entries: [{ name: 'child', path: '/base/child', hidden: false }] }; } }, + isCurrent: () => true, isReady: () => true, + publish: cwd => { terminalCwdStore.setCwd(id, cwd, 'backend-strict'); }, + }); + const cleanup = registerTerminalDirectory(id, controller); + let model!: ReturnType; + function Harness() { model = useComposeDirectoryPicker(id); return null; } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness)); }); + assert.equal(model.cwd, '/base'); + await act(async () => { model.setOpen(true); }); + assert.equal(reads, 1); + await act(async () => { model.setQuery('CH'); }); + assert.equal(model.entries.length, 1); + assert.equal(reads, 1); + await act(async () => { root.unmount(); }); + const before = probes; + refreshObservedTerminalDirectory(id); + await Promise.resolve(); + assert.equal(probes, before); + cleanup(); +}); + +test('switching terminal cancels an old directory read and closes its popover', async () => { + let finish!: (value: { entries: { name: string; path: string; hidden: boolean }[]; home: null }) => void; + const cleanups = ['hook-a', 'hook-b'].map(id => registerTerminalDirectory(id, createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => '/' + id, realpath: async path => path, write() {}, + list: () => new Promise(resolve => { finish = resolve; }) }, + publish: cwd => { terminalCwdStore.setCwd(id, cwd, 'backend-strict'); }, + }))); + let model!: ReturnType; + function Harness({ id }: { id: string }) { model = useComposeDirectoryPicker(id); return null; } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness, { id: 'hook-a' })); }); + await act(async () => { model.setOpen(true); }); + await act(async () => { root.update(React.createElement(Harness, { id: 'hook-b' })); }); + await act(async () => { finish({ entries: [{ name: 'old', path: '/hook-a/old', hidden: false }], home: null }); }); + assert.equal(model.open, false); + assert.equal(model.cwd, '/hook-b'); + assert.deepEqual(model.entries, []); + await act(async () => { root.unmount(); }); + cleanups.forEach(cleanup => cleanup()); +}); + +test('reconnect after an aborted listing allows manual recovery from a failed cwd probe', async t => { + const id = 'hook-directory-reconnect'; + let finishOld!: (value: { entries: { name: string; path: string; hidden: boolean }[]; home: null }) => void; + const oldController = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => '/old', realpath: async value => value, write() {}, + list: () => new Promise(resolve => { finishOld = resolve; }) }, + publish: cwd => { terminalCwdStore.setCwd(id, cwd, 'backend-strict'); }, + }); + const unregisterOld = registerTerminalDirectory(id, oldController); + let model!: ReturnType; + function Harness() { model = useComposeDirectoryPicker(id); return null; } + let root!: ReactTestRenderer; + let unregisterNew = () => {}; + t.after(async () => { + await act(async () => { root.unmount(); }); + unregisterOld(); unregisterNew(); + }); + await act(async () => { root = create(React.createElement(Harness)); }); + await act(async () => { model.setOpen(true); }); + assert.equal(model.loading, true); + // Close while the request is pending, so the read is already aborted when + // the disconnect disposes its controller and settles the old promise. + await act(async () => { model.setOpen(false); }); + await act(async () => { unregisterOld(); terminalCwdStore.setCwd(id, null); }); + let failProbe = true; + const nextController = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => { if (failProbe) throw new DirectoryPickerError('unknown'); return '/recovered'; }, + realpath: async value => value, write() {}, + list: async () => ({ entries: [{ name: 'new', path: '/recovered/new', hidden: false }], home: null }) }, + publish: cwd => { terminalCwdStore.setCwd(id, cwd, 'backend-strict'); }, + }); + await act(async () => { unregisterNew = registerTerminalDirectory(id, nextController); }); + assert.equal(model.cwd, null); + assert.equal(model.error, 'unknown'); + assert.equal(model.loading, false, 'cancelled reads must not leave the manual Refresh action disabled'); + await act(async () => { failProbe = false; await model.refresh(); model.setOpen(true); }); + assert.equal(model.cwd, '/recovered'); + assert.equal(model.loading, false); + assert.deepEqual(model.entries.map(entry => entry.name), ['new']); + await act(async () => { finishOld({ entries: [{ name: 'stale', path: '/old/stale', hidden: false }], home: null }); }); + assert.deepEqual(model.entries.map(entry => entry.name), ['new']); +}); diff --git a/application/state/useComposeDirectoryPicker.ts b/application/state/useComposeDirectoryPicker.ts new file mode 100644 index 000000000..5ffcc0967 --- /dev/null +++ b/application/state/useComposeDirectoryPicker.ts @@ -0,0 +1,94 @@ +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; +import { DirectoryPickerError, directoryParent, filterDirectories, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker'; +import { terminalCwdStore } from './terminalCwdStore'; +import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry'; + +export function useComposeDirectoryPicker(sessionId: string) { + const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null); + useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion); + const [confirmed, setConfirmed] = useState(false); + const cwd = controller && (confirmed || controller.hasConfirmedCwd() || terminalCwdStore.getSource(sessionId) === 'osc7') + ? terminalCwdStore.getCwd(sessionId) : null; + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(''); + const [showHidden, setShowHidden] = useState(false); + const [entries, setEntries] = useState([]); + const [home, setHome] = useState(null); + const [loading, setLoading] = useState(false); + const [pending, setPending] = useState(false); + const listingBase = useRef(null); + const [error, setError] = useState(null); + const generation = useRef(0); + const lifetime = useRef(new AbortController()); + const read = useRef(null); + const sending = useRef(false); + const report = useCallback((failure: unknown, fallback: DirectoryPickerErrorCode) => { + setError(failure instanceof DirectoryPickerError ? failure.code : fallback); + }, []); + + useEffect(() => { + const id = ++generation.current; + const stopObserving = observeTerminalDirectory(sessionId); + lifetime.current = new AbortController(); + sending.current = false; + setConfirmed(false); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]); + listingBase.current = null; + if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => { + if (generation.current === id) { setConfirmed(true); setHome(nextHome); } + }).catch(failure => { if (generation.current === id) report(failure, 'unknown'); }); + return () => { + generation.current = id + 1; + lifetime.current.abort(); read.current?.abort(); stopObserving(); + }; + }, [sessionId, controller, report]); + + const refresh = useCallback(async () => { + if (!controller) { setError('unavailable'); return; } + const id = generation.current; + setError(null); + try { await controller.refresh(); if (generation.current === id) setConfirmed(true); } + catch (failure) { if (generation.current === id) report(failure, 'unknown'); } + }, [controller, report]); + + const load = useCallback(async () => { + if (!controller || !cwd) return; + read.current?.abort(); + const task = new AbortController(); read.current = task; + const id = generation.current; + setLoading(true); setEntries([]); setError(null); + try { + const result = await controller.list(cwd, task.signal); + if (!task.signal.aborted && id === generation.current) { + listingBase.current = cwd; setEntries(result.entries); setHome(result.home); + } + } catch (failure) { + if (!task.signal.aborted && id === generation.current) report(failure, 'readFailed'); + } finally { if (!task.signal.aborted && id === generation.current) setLoading(false); } + }, [controller, cwd, report]); + + useEffect(() => { + if (open) { setQuery(''); void load(); } + return () => { read.current?.abort(); }; + }, [open, load]); + + const change = useCallback(async (path: string) => { + if (!controller) { setError('unavailable'); return; } + if (sending.current) return; + if (!cwd || terminalCwdStore.getCwd(sessionId) !== cwd + || (path !== directoryParent(cwd) && listingBase.current !== cwd)) { setError('unavailable'); return; } + sending.current = true; setPending(true); setError(null); + const id = generation.current; + try { + await controller.change(path, lifetime.current.signal, () => { + if (id === generation.current) setOpen(false); + }, cwd ?? undefined); + } catch (failure) { if (id === generation.current) report(failure, 'changeFailed'); } + finally { + if (id === generation.current) { sending.current = false; setPending(false); } + } + }, [controller, report, cwd, sessionId]); + + const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]); + return { cwd, home, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered, + parent: cwd ? directoryParent(cwd) : null, loading, pending, error, available: !!controller, refresh, reload: load, change }; +} diff --git a/application/state/useTerminalDirectorySession.test.ts b/application/state/useTerminalDirectorySession.test.ts new file mode 100644 index 000000000..7875c7c07 --- /dev/null +++ b/application/state/useTerminalDirectorySession.test.ts @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict'; +import test, { type TestContext } from 'node:test'; +import React from 'react'; +import { act, create, type ReactTestRenderer } from 'react-test-renderer'; +import type { Host } from '../../domain/models'; +import { getTerminalDirectory, observeTerminalDirectory } from './terminalDirectoryRegistry'; +import { useTerminalDirectorySession } from './useTerminalDirectorySession'; +import { useComposeDirectoryPicker } from './useComposeDirectoryPicker'; + +type SessionProps = Parameters[0]; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo']) { + const previous = Object.getOwnPropertyDescriptor(globalThis, 'window'); + let probes = 0; let lists = 0; + Object.defineProperty(globalThis, 'window', { configurable: true, value: { netcatty: { + getAppInfo, + getSessionPwd: async () => { probes++; return { success: true, cwd: '/actual' }; }, + listLocalDir: async () => { lists++; return []; }, + } } }); + t.after(() => { + if (previous) Object.defineProperty(globalThis, 'window', previous); + else Reflect.deleteProperty(globalThis, 'window'); + }); + return { counts: () => ({ probes, lists }) }; +} + +const options = (id: string, protocol = 'local', shellType = 'posix'): SessionProps => ({ + sessionId: id, status: 'connected', + host: { id, label: 'Test', hostname: 'host', username: 'me', protocol } as Host, + shellType, getBackendId: () => id, isReady: () => true, publish() {}, +}); + +for (const wrapper of ['wsl-Ubuntu', 'git-bash', 'cygwin']) { + test(`Windows ${wrapper} reports directory navigation unavailable and performs no reads`, async t => { + const bridge = installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' })); + const id = 'windows-' + wrapper; + let model!: ReturnType; + function Harness() { + const props = options(id); + props.host = { ...props.host, localShell: wrapper }; + useTerminalDirectorySession(props); + model = useComposeDirectoryPicker(id); + return null; + } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness)); }); + t.after(async () => { await act(async () => { root.unmount(); }); }); + assert.equal(getTerminalDirectory(id), null); + assert.equal(model.available, false); + await act(async () => { model.setOpen(true); await model.refresh(); }); + assert.equal(model.error, 'unavailable'); + assert.deepEqual(bridge.counts(), { probes: 0, lists: 0 }); + }); +} + +for (const platform of ['linux', 'darwin']) { + test(`local POSIX directory controller registers on ${platform}`, async t => { + installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform })); + const id = 'local-' + platform; + function Harness() { useTerminalDirectorySession(options(id)); return null; } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness)); }); + t.after(async () => { await act(async () => { root.unmount(); }); }); + assert.ok(getTerminalDirectory(id)); + }); +} + +test('Windows SSH sessions do not inherit the local cwd platform limitation', async t => { + let platformQueries = 0; + installBridge(t, async () => { platformQueries++; return { name: 'Netcatty', version: 'test', platform: 'win32' }; }); + const id = 'windows-ssh'; + function Harness() { useTerminalDirectorySession(options(id, 'ssh')); return null; } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness)); }); + t.after(async () => { await act(async () => { root.unmount(); }); }); + assert.ok(getTerminalDirectory(id)); + assert.equal(platformQueries, 0); +}); + +test('a late platform query cannot register a disconnected terminal', async t => { + let finish!: (info: { name: string; version: string; platform: string }) => void; + installBridge(t, () => new Promise(resolve => { finish = resolve; })); + const id = 'disconnected-during-platform-query'; + const stopObserving = observeTerminalDirectory(id); + t.after(stopObserving); + function Harness({ status }: { status: string }) { useTerminalDirectorySession({ ...options(id), status }); return null; } + let root!: ReactTestRenderer; + await act(async () => { root = create(React.createElement(Harness, { status: 'connected' })); }); + await act(async () => { root.update(React.createElement(Harness, { status: 'disconnected' })); }); + await act(async () => { finish({ name: 'Netcatty', version: 'test', platform: 'linux' }); }); + assert.equal(getTerminalDirectory(id), null); + await act(async () => { root.unmount(); }); +}); diff --git a/application/state/useTerminalDirectorySession.ts b/application/state/useTerminalDirectorySession.ts new file mode 100644 index 000000000..85342cda2 --- /dev/null +++ b/application/state/useTerminalDirectorySession.ts @@ -0,0 +1,56 @@ +import { useEffect, useRef } from 'react'; +import type { Host } from '../../domain/models'; +import { classifyDistroId, hostRestrictsExtraSshChannels } from '../../domain/host'; +import { netcattyBridge } from '../../infrastructure/services/netcattyBridge'; +import { createTerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory'; +import { createTerminalDirectoryController } from './terminalDirectoryController'; +import { registerTerminalDirectory } from './terminalDirectoryRegistry'; + +export function useTerminalDirectorySession(options: { + sessionId: string; + status: string; + host: Host; + shellType?: string; + getBackendId: () => string | null; + isReady: () => boolean; + publish: (cwd: string) => void; +}) { + const live = useRef(options); + live.current = options; + const { sessionId, status, shellType, host } = options; + const local = host.protocol === 'local'; + const supported = (local || ((host.protocol ?? 'ssh') === 'ssh' && !host.moshEnabled && !host.etEnabled)) + && shellType !== 'powershell' && shellType !== 'cmd' + && host.deviceType !== 'network' && classifyDistroId(host.distro) !== 'network-device' + && !hostRestrictsExtraSshChannels(host); + useEffect(() => { + const bridge = netcattyBridge.get(); + const backendId = live.current.getBackendId(); + if (!bridge || !backendId || status !== 'connected' || !supported) return; + let active = true; + const isCurrent = () => active && live.current.status === 'connected' && live.current.getBackendId() === backendId; + let unregister = () => {}; + const register = () => { + if (!isCurrent()) return; + const controller = createTerminalDirectoryController({ + sessionId, + io: createTerminalDirectoryIO(bridge, backendId, { + local, hostname: host.hostname, username: host.username || 'root', port: host.port, + encoding: host.sftpEncoding, + }, isCurrent), + isCurrent, + isReady: () => live.current.isReady(), + publish: cwd => live.current.publish(cwd), + }); + unregister = registerTerminalDirectory(sessionId, controller); + }; + if (local) { + // POSIX wrappers on Windows still use win32 PTYs. Neither their cwd nor + // their path namespace is supported by readLocalSessionCwd/local FS. + void bridge.getAppInfo?.().then(info => { + if (info.platform === 'darwin' || info.platform === 'linux') register(); + }).catch(() => {}); + } else register(); + return () => { active = false; unregister(); }; + }, [sessionId, status, supported, local, host.hostname, host.username, host.port, host.sftpEncoding, shellType]); +} diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 5974f6542..468d563aa 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -1,3 +1,6 @@ +import { terminalCwdStore } from '../application/state/terminalCwdStore'; +import { useTerminalDirectorySession } from '../application/state/useTerminalDirectorySession'; +import { refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry'; import { publishTerminalSelectionTarget } from "../infrastructure/plugins/terminalSelectionRegistry"; import { usePluginTerminalSelection } from "../application/state/usePluginTerminalSelection"; import { clearTerminalBroadcastUserInput, markTerminalBroadcastUserInput } from "./terminal/runtime/terminalPacedBroadcast"; @@ -1246,6 +1249,7 @@ const TerminalComponent: React.FC = ({ const clearTerminalCwd = useCallback((options?: { persistRestoreMetadata?: boolean }) => { terminalCwdTracker.clearRendererCwd(); + terminalCwdStore.setCwd(sessionId, null); knownCwdRef.current = undefined; if (options?.persistRestoreMetadata === false) return; onTerminalCwdChange?.(sessionId, null); @@ -2590,6 +2594,7 @@ const TerminalComponent: React.FC = ({ const cwdAwareOnCommandSubmitted = useCallback(( ...args: Parameters> ) => { + scheduleObservedTerminalDirectoryRefresh(sessionId); if (!shouldPreserveTerminalCwdAcrossCommand(hostRestrictsExtraSshChannels(host))) { invalidateTerminalCwdAfterCommand( terminalCwdTracker, @@ -2603,6 +2608,7 @@ const TerminalComponent: React.FC = ({ }, [host, onCommandSubmitted, onTerminalCwdChange, sessionId, terminalCwdTracker]); const pluginAwareOnCommandCompleted = useCallback(() => { pluginTerminalLifecycle.onCommandCompleted(); + refreshObservedTerminalDirectory(sessionId); void xtermRuntimeRef.current?.pluginProviderHost?.commandCompleted(); // Hibernate wake builds its runtime from this callback. Same local // prompt-return refresh as useTerminalEffects (#1952). @@ -2615,6 +2621,7 @@ const TerminalComponent: React.FC = ({ cwd: string | null, meta?: TerminalCwdChangeMeta, ) => { + terminalCwdStore.setCwd(changedSessionId, cwd, meta?.source); pluginTerminalLifecycle.onCwdChanged(cwd); onTerminalCwdChange?.(changedSessionId, cwd, meta); }, [onTerminalCwdChange, pluginTerminalLifecycle]); @@ -2630,6 +2637,13 @@ const TerminalComponent: React.FC = ({ pluginAwareOnTerminalCwdChange(sessionId, normalizedCwd ?? null, meta); void refreshProviderOutputs('cwd-changed'); }, [pluginAwareOnTerminalCwdChange, refreshProviderOutputs, sessionId, terminalCwdTracker]); + useTerminalDirectorySession({ + sessionId, status, host, shellType, + getBackendId: () => sessionRef.current, + isReady: () => isTerminalReadyForCommandInjection(sessionId), + publish: cwd => pluginAwareOnRuntimeCwdChange(cwd, { source: 'backend-strict' }), + }); + const pluginAwareOnTerminalTitleChange = useCallback((changedSessionId: string, title: string | null) => { terminalTitleRef.current = title || undefined; pluginTerminalLifecycle.onTitleChanged(title); @@ -2771,6 +2785,7 @@ const TerminalComponent: React.FC = ({ onTerminalDataCapture: handleTerminalDataCaptureOnce, onTerminalOutput: (chunk: string, meta?: TerminalSessionDataMeta) => { observeTerminalInputPrompt(chunk, meta); + scheduleObservedTerminalDirectoryRefresh(sessionId); appendOutputTriggerOutputRef.current(chunk, meta); if (onTerminalOutput) { onTerminalOutput(sessionId, chunk); diff --git a/components/settings/tabs/TerminalBehaviorSettings.test.ts b/components/settings/tabs/TerminalBehaviorSettings.test.ts index 75bf52284..018c45a0c 100644 --- a/components/settings/tabs/TerminalBehaviorSettings.test.ts +++ b/components/settings/tabs/TerminalBehaviorSettings.test.ts @@ -35,6 +35,17 @@ test("terminal behavior settings expose disabled auto-close", () => { ); }); +test('Context Chips default on for old settings and preserve an explicit off preference', () => { + assert.equal(normalizeTerminalSettings({ scrollback: 5000 }).contextChipsEnabled, true); + const disabled = normalizeTerminalSettings({ contextChipsEnabled: false }); + assert.equal(normalizeTerminalSettings(JSON.parse(JSON.stringify(disabled))).contextChipsEnabled, false); + const markup = renderToStaticMarkup(React.createElement(TerminalBehaviorSettings, { + t: (key: string) => key, terminalSettings: disabled, updateTerminalSetting: () => {}, + })); + assert.match(markup, /settings-anchor-terminal-context-chips/); + assert.match(markup, /settings\.terminal\.behavior\.contextChips[\s\S]*?role="switch" aria-checked="false"/); +}); + test("terminal behavior settings expose OSC desktop notification mode", () => { const markup = renderSettings(true); assert.match(markup, /settings-anchor-terminal-osc-notifications/); diff --git a/components/settings/tabs/TerminalBehaviorSettings.tsx b/components/settings/tabs/TerminalBehaviorSettings.tsx index 5bbe62b81..ac17d4fb5 100644 --- a/components/settings/tabs/TerminalBehaviorSettings.tsx +++ b/components/settings/tabs/TerminalBehaviorSettings.tsx @@ -48,6 +48,14 @@ export const TerminalBehaviorSettings: React.FC = <>
+ + updateTerminalSetting("contextChipsEnabled", v)} /> + + void; +}) { + const { t } = useI18n(); + const model = useComposeDirectoryPicker(sessionId); + const [active, setActive] = useState(0); + const [scrollTop, setScrollTop] = useState(0); + const search = useRef(null); + const viewport = useRef(null); + const composing = useRef(false); + const outside = useRef(false); + const id = useId(); + const hasParent = model.parent !== null; + const count = model.entries.length + Number(hasParent); + const activeEntry = active === 0 && hasParent ? model.parent : model.entries[active - Number(hasParent)]?.path; + const errorText = model.error ? t('terminal.directory.' + model.error) : null; + useEffect(() => { + setActive(model.entries.length ? Number(hasParent) : -1); + setScrollTop(0); + if (viewport.current) viewport.current.scrollTop = 0; + }, [model.entries, hasParent, model.open]); + + const virtual = model.entries.length > 200; + const start = virtual ? Math.max(0, Math.floor(scrollTop / 32) - 4) : 0; + const visible = virtual ? model.entries.slice(start, start + 16) : model.entries; + const row = (name: string, path: string, index: number, parent = false) => ( +
setActive(index)} + onMouseDown={event => event.preventDefault()} + onClick={() => { if (!model.pending) void model.change(path); }} + > + {parent ? : } + {directoryDisplayName(name)} +
+ ); + return ( +
+ { if (value) outside.current = false; model.setOpen(value); }}> + + + + { event.preventDefault(); search.current?.focus(); }} + onInteractOutside={() => { outside.current = true; }} + onCloseAutoFocus={event => { event.preventDefault(); if (!outside.current) onReturnFocus(); }} + onKeyDown={event => { + event.stopPropagation(); + if (composing.current || event.nativeEvent.isComposing) return; + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault(); + const next = active < 0 ? (event.key === 'ArrowDown' ? 0 : count - 1) + : Math.max(0, Math.min(count - 1, active + (event.key === 'ArrowDown' ? 1 : -1))); + setActive(next); + const child = next - Number(hasParent); + if (viewport.current && child >= 0) { + const el = viewport.current; + if (child * 32 < el.scrollTop) el.scrollTop = child * 32; + else if ((child + 1) * 32 > el.scrollTop + el.clientHeight) el.scrollTop = (child + 1) * 32 - el.clientHeight; + } + } else if (event.key === 'Enter' && event.target === search.current) { + event.preventDefault(); if (activeEntry && !model.pending) void model.change(activeEntry); + } + }} + > +
+ model.setQuery(event.target.value)} + aria-label={t('terminal.directory.search')} aria-controls={`${id}-list`} + aria-activedescendant={activeEntry ? `${id}-${active}` : undefined} + placeholder={t('terminal.directory.search')} + className="w-full bg-transparent text-xs outline-none placeholder:opacity-60" + onCompositionStart={() => { composing.current = true; }} + onCompositionEnd={() => { composing.current = false; }} + /> +
+
+ {model.parent && row(t('terminal.directory.parent'), model.parent, 0, true)} +
setScrollTop(event.currentTarget.scrollTop)}> +
+
+ {visible.map((entry, index) => row(entry.name, entry.path, start + index + Number(hasParent)))} +
+
+ {model.loading &&

{t('terminal.directory.loading')}

} + {!model.loading && !errorText && model.cwd && !model.entries.length && ( +

{t(model.query ? 'terminal.directory.noMatches' : 'terminal.directory.empty')}

+ )} +
+
+ {(errorText || !model.available || !model.cwd) &&

+ {errorText ?? t(model.available ? 'terminal.directory.unknown' : 'terminal.directory.unavailable')} +

} +
+ + +
+
+
+ {!model.open && errorText && {errorText}} +
+ ); +} diff --git a/components/terminal/TerminalComposeBar.test.tsx b/components/terminal/TerminalComposeBar.test.tsx index 9ea69269d..dc03502e6 100644 --- a/components/terminal/TerminalComposeBar.test.tsx +++ b/components/terminal/TerminalComposeBar.test.tsx @@ -8,6 +8,51 @@ import { TerminalComposeBar } from './TerminalComposeBar'; import { TooltipProvider } from '../ui/tooltip'; import { getComposeBarHistory, pruneComposeBarHistory, recordComposeBarHistory } from '../../application/state/composeBarHistoryStore'; import { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry'; +import { createTerminalDirectoryController } from '../../application/state/terminalDirectoryController'; +import { registerTerminalDirectory, refreshObservedTerminalDirectory } from '../../application/state/terminalDirectoryRegistry'; +import { terminalCwdStore } from '../../application/state/terminalCwdStore'; + +test('disabling Context Chips preserves the compose draft and stops extra cwd refreshes', async (t) => { + const dom = new JSDOM('', { url: 'http://localhost' }); + const originals = new Map(); + for (const name of ['window', 'document', 'localStorage']) { + originals.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); + Object.defineProperty(globalThis, name, { configurable: true, value: dom.window[name as keyof Window] }); + } + t.after(() => { + dom.window.close(); + for (const [name, descriptor] of originals) { + if (descriptor) Object.defineProperty(globalThis, name, descriptor); + else Reflect.deleteProperty(globalThis, name); + } + }); + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + let probes = 0; + const cleanup = registerTerminalDirectory('toggle-test', createTerminalDirectoryController({ + sessionId: 'toggle-test', isCurrent: () => true, isReady: () => true, + io: { cwd: async () => { probes++; return '/project'; }, list: async () => ({ entries: [], home: null }), + realpath: async path => path, write() {} }, + publish: cwd => { terminalCwdStore.setCwd('toggle-test', cwd, 'backend-strict'); }, + })); + const textarea = { value: '', selectionStart: 0, selectionEnd: 0, focus() {}, + setSelectionRange(start: number, end: number) { this.selectionStart = start; this.selectionEnd = end; } }; + const render = (enabled: boolean) => true} onClose={() => {}} />; + let root!: ReactTestRenderer; + await act(async () => { root = create(render(true), { createNodeMock: el => el.type === 'textarea' ? textarea : null }); }); + assert.equal(probes, 1); + textarea.value = 'keep this draft'; textarea.selectionStart = 2; textarea.selectionEnd = 8; + await act(async () => { root.update(render(false)); }); + assert.equal(root.root.findAllByProps({ 'aria-label': 'Context Chips' }).length, 0); + const before = probes; + refreshObservedTerminalDirectory('toggle-test'); + await Promise.resolve(); + assert.equal(probes, before); + assert.equal(textarea.value, 'keep this draft'); + assert.deepEqual([textarea.selectionStart, textarea.selectionEnd], [2, 8]); + await act(async () => { root.unmount(); }); + cleanup(); +}); test('compose bar preserves a draft on pane focus and records only successful async sends', async (t) => { const dom = new JSDOM('', { url: 'http://localhost' }); diff --git a/components/terminal/TerminalComposeBar.tsx b/components/terminal/TerminalComposeBar.tsx index 777bd17bf..77a98b049 100644 --- a/components/terminal/TerminalComposeBar.tsx +++ b/components/terminal/TerminalComposeBar.tsx @@ -1,3 +1,4 @@ +import { ComposeDirectoryPicker } from './ComposeDirectoryPicker'; /** * Terminal Compose Bar * An immersive prompt bar below the terminal with a quick-snippet strip, @@ -29,7 +30,7 @@ import { const SNIPPET_STRIP_HEIGHT = 30; const RESIZE_HANDLE_HEIGHT = 6; -type ComposeBarTheme = { +export type ComposeBarTheme = { resolvedBg: string; resolvedFg: string; borderColor: string; @@ -273,6 +274,7 @@ const ComposeBarSnippetManagePopover = memo(function ComposeBarSnippetManagePopo }); export interface TerminalComposeBarProps { + contextChipsEnabled?: boolean; // Return false for rejected or sensitive input so it is not recalled. onSend: (text: string) => boolean | void | Promise; sessionId: string; @@ -291,6 +293,7 @@ export interface TerminalComposeBarProps { export const TerminalComposeBar: React.FC = ({ onSend, + contextChipsEnabled = true, sessionId, onClose, onSnippetClick, @@ -611,6 +614,9 @@ export const TerminalComposeBar: React.FC = ({ />
+ {contextChipsEnabled && textareaRef.current?.focus({ preventScroll: true })} />} +
{(onToggleComposeSendTarget || sendToAll) && ( diff --git a/components/terminal/TerminalView.tsx b/components/terminal/TerminalView.tsx index a76959933..973a0353c 100644 --- a/components/terminal/TerminalView.tsx +++ b/components/terminal/TerminalView.tsx @@ -1432,6 +1432,7 @@ function TerminalViewInner({ ctx, isPaneMagnified = false }: { ctx: TerminalView {/* Compose Bar (solo sessions only; workspace uses TerminalLayer's global bar) */} {isComposeBarOpen && !inWorkspace && ( { diff --git a/components/terminal/useTerminalEffects.ts b/components/terminal/useTerminalEffects.ts index 8dd6addbf..f8ef0578e 100644 --- a/components/terminal/useTerminalEffects.ts +++ b/components/terminal/useTerminalEffects.ts @@ -1,3 +1,4 @@ +import { refreshObservedTerminalDirectory } from '../../application/state/terminalDirectoryRegistry'; /* eslint-disable @typescript-eslint/no-explicit-any, react-hooks/exhaustive-deps */ import { useRef } from 'react'; import { publishTerminalSelectionTarget } from '../../infrastructure/plugins/terminalSelectionRegistry'; @@ -237,6 +238,7 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) { onCommandSettledRef.current = ctx.onCommandSettled; const pluginAwareOnCommandCompleted = () => { publishPluginTerminalRuntimeLifecycleEvent(pluginTerminalLifecycle, 'commandCompleted'); + refreshObservedTerminalDirectory(sessionId); void xtermRuntimeRef.current?.pluginProviderHost?.commandCompleted(); // Stock local shells update cwd when the command finishes, which can be // long after the 150ms post-submit probe. Prompt return (and OSC 133) diff --git a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx index d26a4d2f8..b5195813a 100644 --- a/components/terminalLayer/TerminalLayerWorkspaceSection.tsx +++ b/components/terminalLayer/TerminalLayerWorkspaceSection.tsx @@ -350,6 +350,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext }) {activeWorkspace && focusedSessionId && isComposeBarOpen && ( void handleSnippetFromPanel(snippet)} snippets={snippets} diff --git a/docs/research/terminal-compose-context/README.md b/docs/research/terminal-compose-context/README.md index 5731fd406..d0d4d77b9 100644 --- a/docs/research/terminal-compose-context/README.md +++ b/docs/research/terminal-compose-context/README.md @@ -15,9 +15,11 @@ Context Chips: [目录] [分支] [变更统计] [Node] [PR] 芯片显示上下文,点击就近操作。首期只显示已实现的目录芯片,其余按终端能力与上下文出现。共享终端主题、紧凑图标和文字、悬停说明及键盘焦点;不额外显示占据高度的行标题。窄分屏优先保留目录,长路径/分支名截断显示,完整值可查看。 +“设置 → 终端 → Context Chips”控制整行显示,默认开启;关闭时保留命令草稿,并停止芯片额外发起的目录读取与命令后刷新。 + | 功能 | 开发目标 | 调研与交互 | | --- | --- | --- | -| Directory Picker | 显示当前位置;搜索子目录、返回父目录、选择后立即切换并关闭菜单 | [directory-picker.md](directory-picker.md) · [交互示意](directory-picker-demo.html) | +| Directory Picker | 显示当前位置;搜索子目录、返回父目录、选择后立即切换并关闭菜单 | [功能规格](directory-picker.md) · [交互示意](directory-picker-demo.html) · [跨平台研究](directory-picker-cross-platform.md) · [后续计划](directory-picker-follow-up.md) | | Git Branch | 显示当前分支,搜索并切换其他分支 | [git-branch.md](git-branch.md) | | Git Changes | 显示改动文件数及增删行;预留变更文件面板入口 | [git-changes.md](git-changes.md) | | Node Version | 显示当前终端 Node 版本;支持的管理器可提供版本切换 | [node-version.md](node-version.md) | diff --git a/docs/research/terminal-compose-context/directory-picker-cross-platform.md b/docs/research/terminal-compose-context/directory-picker-cross-platform.md new file mode 100644 index 000000000..414255164 --- /dev/null +++ b/docs/research/terminal-compose-context/directory-picker-cross-platform.md @@ -0,0 +1,150 @@ +# Directory Picker:跨平台能力与 shell 集成研究 + +调研日期:2026-10-30。Netcatty 源码基线:`7f8f8d34687a1dbb94b16f314952bf25aac0d88d`。本文研究后续能力,**不表示当前 PR 已支持 Windows 本地目录导航**;实施顺序见 [后续计划](directory-picker-follow-up.md)。 + +## 1. 结论 + +保留绝对路径作为操作目标;依 shell 生成命令,依文件系统环境读取目录,依当前交互会话确认结果。跨平台的难点是这三项能力的组合,不是把 `cd --` 换成 `cd`。 + +建议优先补齐 Windows PowerShell 5.1/PowerShell 7,再推进 CMD。macOS 的 zsh/bash 和主流 Linux 的 bash/ash/zsh 保留已有进程 cwd 回退,并逐步增加可协商的 shell 上报。fish 独立处理引用与事件。WSL、Git Bash、Cygwin 按自己的路径空间接入,不因被分类为 `posix` 就复用 Windows 本地文件系统。 + +这里的“默认终端支持”指 **Netcatty 创建的交互 shell**。Windows Terminal、Terminal.app、GNOME Terminal 等窗口应用本身不是命令解释器;不能只按 OS 或发行版名称选择语法。 + +## 2. 当前实现与缺口 + +| 位置 | 已有能力 | 后续约束 | +| --- | --- | --- | +| `application/state/useTerminalDirectorySession.ts` | macOS/Linux 本地与符合条件的 SSH;Windows 本地主动禁用 | 当前平台门槛不能直接删除,必须先证明 cwd、路径、执行三者都适配 | +| `electron/bridges/localSessionCwd.cjs` | Linux 读 `/proc//cwd`;macOS 用 lsof | Windows 未实现;读到启动 PTY 的进程不等于能识别所有嵌套 shell | +| `infrastructure/services/terminalDirectory.ts` | 本地 FS 或 exact-session SFTP,严格 cwd 查询 | 远程不新建登录、不借用其他 session;SFTP 根与 shell 根未必相同 | +| `domain/directoryPicker.ts` | `/` 开头的路径、POSIX 父路径和拼接 | 不支持盘符、UNC、WSL 及 MSYS/Cygwin 路径转换 | +| `domain/sessionRestore.ts` | `resolveInteractiveTerminalCdIntent` 的 POSIX 引用、控制字节拒绝 | 扩展 Directory Picker 不应破坏已有恢复和 SFTP 定位调用者 | +| `terminalDirectoryController.ts`/`terminalCwdStore.ts` | 每会话 revision、严格结果确认、旧连接失效 | 加入 shell 报告也要保留这些顺序与身份约束 | +| `terminalDirectoryRegistry.ts`/`components/Terminal.tsx` | 芯片可见时按完成/输出事件刷新,不恒定轮询 | 集成有效时可以减少辅助探测;关闭 chips 要停止其额外需求 | +| `components/terminal/runtime/createXTermRuntime.ts` | OSC 7 上报路径;OSC 133 的 D 完成事件 | 当前 `URL.pathname` 结果仍按 POSIX 使用;不能把 `/C:/...` 当 POSIX 路径直接读盘 | +| `components/terminal/osc7Setup.ts` | 已有 bash/zsh/fish 目录跟踪配置及确认流程 | 会写 rc 文件并可能 reload;不能改成新功能的静默自动安装器 | +| `electron/bridges/ai/sessionShellKind.cjs`/`liveShellProbe.cjs` | shell 分类、远端登录 hint、当前 PTY 探测 | 登录 shell hint 不证明当前 shell;现有主动探测有输入和副作用,不能每次点菜单就执行 | +| `electron/bridges/ai/ptyExecHelpers.cjs` | POSIX/fish/PowerShell 各自的字符串引用 | 可提取纯引用逻辑;整个 AI exec 包装器不适合目录操作,有子进程、eval、环境及历史处理语义 | + +## 3. 绝对路径与 `--` + +菜单查询、点击、异步 realpath、写入终端之间存在时间差。即使 chip 自动跟随,列表也只代表查询时的目录。相对路径不能单独消除旧列表风险:仍要校验 session、连接代次、shell/文件系统身份及 cwd revision。 + +POSIX `cd` 的相对目录还可能受 `CDPATH` 影响;`./child` 能避开这一搜索规则,但仍依赖执行时 cwd。POSIX 文档规定 `cd` 改变的是当前 shell 的执行环境,因此独立 exec 的 cd 不能代替对用户交互 shell 的切换。[S1] + +本机隔离目录实验,bash 3.2.57、zsh 5.9 和系统 dash: + +| 实验 | 结果 | +| --- | --- | +| `cd -- '/absolute/path'` 与 `cd '/absolute/path'` | 三种 shell 均成功 | +| 从 A 列出 `src`,执行前切到 B,再 `cd './src'` | 三种 shell 均进入 B/src | +| 同样条件下使用 A/src 绝对路径 | 三种 shell 均进入指定 A/src | +| 设置 `CDPATH` 后执行 `cd 'src'` | bash/dash 进入搜索路径中的 src;本次 zsh 优先进入本地 src,不能泛化为各 shell 完全相同 | + +这些实验只证明上述本机版本。`--` 与引号作用不同:前者结束选项,后者保持参数边界。对于当前 `/` 开头的绝对路径,`--` 不是必需;不应把删掉它当成 Windows 兼容方案。引用策略必须按 shell 测试,不能把 POSIX 单引号拼接直接推广到 fish/CMD。[S1、S4、N1] + +## 4. 支持矩阵与数据来源 + +| 环境 | cwd 首选/回退 | 目录读取 | 切换策略与主要缺口 | +| --- | --- | --- | --- | +| macOS zsh,兼容 bash 3.2 | 已有 lsof;新增 prompt/chpwd 上报 | 本地 FS | 当前 shell 的 cd;保留原有 login/rc/PATH 行为 | +| Linux bash/zsh/dash/ash | 已有 `/proc`;可用时接 shell 报告 | 本地 FS | 独立引用测试;dash/ash 不保证有 bash 的 hook 能力 | +| Linux/macOS fish | prompt/PWD 事件,必要时进程回退 | 本地 FS | fish 引用与事件;不能运行 POSIX 初始化脚本 | +| Windows PowerShell 5.1/7 | **当前 runspace 的位置报告** | FileSystem provider 的本地 FS | `Set-Location -LiteralPath`;盘符、UNC、provider、策略限制 | +| Windows CMD | 会话 PROMPT 中的位置/边界报告 | Windows 本地 FS | `cd /d`;百分号、感叹号、命令扩展、UNC 另定 | +| Windows WSL | 所选 distro 内 shell 上报/受控 helper | 同一 distro 的 Linux FS 适配 | Linux 语法;不能把 `/home` 传给宿主 Windows FS | +| Windows Git Bash/Cygwin | 该环境的 shell 上报 | 已验证的命名空间映射/helper | MSYS/Cygwin 的挂载规则,不是 WSL 的路径转换 | +| 普通 SSH 到 Unix | 已有严格活动 shell 探测;可选远端集成 | 同一连接的 SFTP;先证明路径对应 | 嵌套 shell、sudo、chroot 不能退回登录 home 冒充 cwd | +| SSH 到 Windows | 远端活动 shell 报告;不靠新 exec 的 Get-Location | 远端 SFTP 路径映射/受控能力 | Win32-OpenSSH hint 不等于活动 shell;独立阶段 | +| 单通道跳板、网络设备、mosh/ET、插件终端 | 按 provider/传输能力分别证明 | 按该传输证明 | 不因支持 cwd 上报就自动支持目录枚举或安全切换 | + +Ubuntu/Debian、Fedora/Rocky/Alma、Arch、Alpine 等应作为验收样本,不能把发行版与用户当前 shell 硬绑定。Windows 也不能只根据 PowerShell/CMD 的提示符外观推断可写状态。 + +## 5. 会话级 shell 集成的可行路径 + +### 5.1 参考实现与可复用部分 + +VS Code 将工作目录与命令边界由 shell 脚本报告,启动时通过参数/环境注入;其用户文档也明确普通 SSH、子 shell、特殊启动参数会使自动注入失效。[S2] 固定源码快照 N1 中: + +- bash 使用 init-file 路径,并兼容用户 rc/login 启动;fish 使用 init-command。 +- zsh 使用临时 ZDOTDIR 中的启动文件代理,不只是加载 `.zshrc` 一步。 +- PowerShell 在原 prompt 前后报告位置和边界,只为 FileSystem provider 报告文件路径;受限语言模式会退出集成。 +- Windows Terminal 另给出 PowerShell/CMD 的 prompt 集成例子,使用 OSC 133 与 OSC 9;9;这与现有 OSC 7 接收逻辑不是同一协议。[S3、N1] + +这些代码证明路径可行,不等于 Netcatty 已支持,也不应整套复制。尤其官方页面和最新主分支的 shell 支持范围可能不同,以自己测试过的版本为准。 + +### 5.2 推荐启动方式 + +本地在 `startLocalSession` 的可执行文件、参数和环境解析完成后,按已识别 shell 生成**会话级启动方案**。支持的普通交互参数才注入;用户 `-Command`、`-File`、`--norc`、自定义 `--rcfile`、受限模式或包装脚本不能悄悄改写。集成失败时照常打开终端,声明能力不足,保留当前支持的回退。 + +临时脚本通过 `tempDirBridge.getTempFilePath()` 放在 Netcatty 管理目录,检查权限、包内资源路径与清理生命周期;不能依赖源码目录在打包后存在。外部 shell 不能把 Electron 的 asar 虚拟路径当普通脚本文件使用,需显式部署为真实资源或复制到受管目录后加载。[S15] 首期不改用户 rc、注册表 AutoRun 或全局环境,也不默认重载整个配置文件。 + +shell hook 要保留原 prompt、主题插件、退出状态及 PATH;防止重复安装和递归。bash 区分标量/数组 `PROMPT_COMMAND` 及旧版本;zsh 保留 precmd/chpwd 链;fish 保留已有函数和事件。PowerShell 包装原 prompt 并恢复其结果,不能使用 PowerShell 6 才加入的反引号 e 作为 5.1 唯一 ESC 写法,应采用如 `[char]27` 的兼容构造。[S5–S8] + +### 5.3 上报协议与可信度 + +推荐先保留 OSC 7 的可互操作 cwd 展示,再为 host-owned 集成增加可协商、带明确版本及编码的状态报告;是否复用 OSC 633,需在实现前确定。不要随意占用新的 OSC 编号,也不要为完整命令录制扩张本功能。 + +最低需要报告:当前 cwd/provider、路径类型、shell kind、prompt-ready/running,以及 shell 实例或集成代次。接收器必须处理 BEL/ST、分片、多字节 UTF-8、转义、长度上限与 URI authority。不能把终端原样输出拼成命令。 + +报告范围只覆盖目录与操作所需状态,不默认收集命令全文、环境变量或凭据。新增序列需经过已有输出管线,避免污染日志、回放、输出触发器与侧栏上下文;不能只在可见 xterm 中生效,忽略 worker/hibernate 路径。 + +**OSC 7 和普通边界序列是内容,不是认证。** 任意程序都可能打印它们,cwd 报告不能单独解除密码/MFA、alternate screen 或半行输入的阻止条件。VS Code 的 nonce 用于部分命令报告验证,不代表所有 Cwd 属性都已认证。[S2、N1] 候选方案可以使用会话 nonce 降低误识别,但 shell 内可执行代码仍可能读取它,不能宣传为隔离恶意进程的安全边界。 + +实现时在 worker/host 绑定 session、连接及 shell 代次,验证消息后再发 typed event 到应用状态。保留每会话 revision,使另一个终端的更新不能盖过本终端严格读取;旧连接、退出、hibernate/恢复、外部 `su`、嵌套 shell 均需失效规则。 + +## 6. Windows 原生 shell + +### PowerShell + +PowerShell 每个 runspace 的当前位置不同于 `[Environment]::CurrentDirectory`;另起 `powershell -Command Get-Location` 也读不到原交互 runspace 的状态。[S4] 应在目标 prompt 内获取 `$PWD`/`SessionState.Path.CurrentLocation`,只在 provider 为 FileSystem 时取 ProviderPath。进入 `HKLM:`、Env: 或自定义 provider 时显示“非文件系统位置”,不继续展示上一次目录为当前值。[S4、N1] + +切换示例为 `Microsoft.PowerShell.Management\Set-Location -LiteralPath 'D:\Project [test]\O''Brien'`:单引号内部的单引号按 PowerShell 规则加倍;`-LiteralPath` 防止方括号等被当通配符。按当前 runspace 的 FileSystem home 做 `~` 展示;不要使用启动 Electron 的用户 home 代替。不能利用 Invoke-Expression 处理用户路径,也不以子进程的成功退出替代原 runspace 确认。[S4、S5] + +PowerShell 5.1 与 7 分别验证 PSReadLine、有/无 profile、oh-my-posh/starship、UNC、PSDrive、ConstrainedLanguage/JEA。遵守执行策略;不能自动 `Set-ExecutionPolicy`、强制 Bypass 或绕过组策略。策略阻止集成时声明不可用,并给出可理解原因。[S9、N1] + +### CMD + +`cd /d "D:\Project"` 才会同时切换盘符和目录;单引号不是 CMD 的路径引用语法。[S10] `PROMPT` 的 `$P`、`$E` 可提供位置和序列构造,Windows Terminal 提供了会话 PROMPT 的组合示例。[S3、S11] 这只证明可上报,不自动解决命令前后边界、当前半行输入、编码或错误码保留。 + +`%NAME%` 的环境展开、`/V:ON` 的 `!NAME!`、交互输入与批处理中的 `%` 规则不同。不能照抄嵌套 `cmd /c` 包装器的转义:子 CMD 切目录不影响父 CMD;`setlocal` 包装也可能改变退出后的目录/状态。[S12、N1 的对照边界] + +第一版可先明确拒绝未经验证的 `%`/`!` 等路径,而非声明支持任意目录。不能修改用户 delayed expansion/AutoRun 来让自己的命令能运行。UNC 也不能默认用 `pushd` 兜底:它会创建临时盘符并改变目录栈;必须另行设计可见语义、清理和失败恢复。[S10–S12] + +## 7. WSL、路径模型和远程 + +路径至少区分显示值、执行值、文件系统地址、逻辑/物理路径及 authority。例如同一 `/home/me` 在 distro A、distro B、SSH 或容器里不是同一目标;`C:foo` 是盘符相对路径,不等于 `C:\foo`;UNC 根也不能用 POSIX 字符串截断计算父级。[S4、S10、S13] + +WSL 优先使用所选 distro 的 helper 枚举并返回结构化目录,或经过验证的 Windows UNC 访问;不把 `$PWD` 直接交给 `listLocalDir`。Git Bash/Cygwin 则要验证挂载点、`/c`/`/cygdrive`/`/usr`、链接和编码,不能只替换斜杠。helper 不经 `ls` 文本拆行,支持中英文、空格与严格取消;必要时仍拒绝无法安全执行的控制字符。 + +PowerShell 的 drive/provider、Windows 大小写、Linux 的大小写敏感与链接语义应交给对应适配器,不对所有路径全局 lowercase/trim/decode。WSL 的 Linux FS 与 Windows FS 在大小写和访问性能上有区别。[S13] + +本地集成不会随普通 ssh、tmux、容器或 sudo 自动迁移到目标 shell。远端可选择已有的显式 OSC 7 配置流程,或后续受控地安装当前 shell 的临时集成;必须说明配置是否持久化。不能因菜单打开而私自修改远端 rc。单通道、mosh/ET、Windows OpenSSH、受限 SFTP 需各自证明 cwd、list、change 三种能力,不能借另一个登录“猜目录”。[S2、项目现有实现] + +## 8. 实验范围与参考资料 + +本轮完成源码检查与本机 bash/zsh/dash 命令实验。PowerShell、CMD、fish、WSL 未在本机安装,Windows 和多发行版运行结果**尚未验证**。现有 PR 的本地 PTY/SSH fixture 证明的是当前 Unix 路径,不证明 Windows 已可用。 + +官方资料均查阅于 2026-10-30: + +- S1:[POSIX cd](https://pubs.opengroup.org/onlinepubs/9799919799/utilities/cd.html),当前 shell、CDPATH、逻辑/物理路径。 +- S2:[VS Code shell integration](https://code.visualstudio.com/docs/terminal/shell-integration),注入、支持范围、SSH 限制、OSC 633 与 nonce。 +- S3:[Windows Terminal shell integration](https://learn.microsoft.com/en-us/windows/terminal/tutorials/shell-integration),PowerShell/CMD 的 OSC 133 和位置报告。 +- S4:[PowerShell locations](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_locations?view=powershell-7.5) 与 [Set-Location](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/set-location?view=powershell-7.5),runspace、provider、LiteralPath。 +- S5:[PowerShell quoting rules](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7.5) 与 [special characters](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_special_characters?view=powershell-7.5),引用及 5.1/6+ 语法区别。 +- S6:[Bash prompt](https://www.gnu.org/software/bash/manual/html_node/Controlling-the-Prompt.html) 与 [Bash startup files](https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html)。 +- S7:[zsh functions](https://zsh.sourceforge.io/Doc/Release/Functions.html),precmd/chpwd 及 hook 链。 +- S8:[fish language](https://fishshell.com/docs/current/language.html),PWD、函数作用域与事件。 +- S9:[PowerShell execution policies](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.5)。 +- S10:[CMD cd](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cd),盘符与 `/d`。 +- S11:[CMD prompt](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/prompt),位置、转义及目录栈符号。 +- S12:[CMD](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd) 与 [pushd](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/pushd),展开、AutoRun、UNC/临时盘符。 +- S13:[WSL filesystems](https://learn.microsoft.com/en-us/windows/wsl/filesystems),路径空间、大小写与访问方式。 +- S14:[WezTerm shell integration](https://wezterm.org/shell-integration.html),OSC 7 Windows/POSIX 构造对照。 +- S15:[Electron ASAR archives](https://www.electronjs.org/docs/latest/tutorial/asar-archives),虚拟路径、外部程序与 unpack 限制。 + +N1:VS Code 官方仓库固定快照 `ce233327f26ef7791b7fff0143c24e81a8126bd2`,用于验证实现机制,不表示其支持承诺等同于 Netcatty: + +- [terminalEnvironment.ts](https://github.com/microsoft/vscode/blob/ce233327f26ef7791b7fff0143c24e81a8126bd2/src/vs/platform/terminal/node/terminalEnvironment.ts):按 shell 注入参数、ZDOTDIR 与 unsupported-args 分支。 +- [shellIntegration.ps1](https://github.com/microsoft/vscode/blob/ce233327f26ef7791b7fff0143c24e81a8126bd2/src/vs/workbench/contrib/terminal/common/scripts/shellIntegration.ps1):provider、原 prompt、状态、语言模式与协议字段。 +- [shellIntegration-bash.sh](https://github.com/microsoft/vscode/blob/ce233327f26ef7791b7fff0143c24e81a8126bd2/src/vs/workbench/contrib/terminal/common/scripts/shellIntegration-bash.sh)、[shellIntegration-rc.zsh](https://github.com/microsoft/vscode/blob/ce233327f26ef7791b7fff0143c24e81a8126bd2/src/vs/workbench/contrib/terminal/common/scripts/shellIntegration-rc.zsh)、[shellIntegration.fish](https://github.com/microsoft/vscode/blob/ce233327f26ef7791b7fff0143c24e81a8126bd2/src/vs/workbench/contrib/terminal/common/scripts/shellIntegration.fish):各 shell 初始化及事件处理。 diff --git a/docs/research/terminal-compose-context/directory-picker-follow-up.md b/docs/research/terminal-compose-context/directory-picker-follow-up.md new file mode 100644 index 000000000..7e8db1e9f --- /dev/null +++ b/docs/research/terminal-compose-context/directory-picker-follow-up.md @@ -0,0 +1,97 @@ +# Directory Picker:后续开发计划 + +日期:2026-10-30。目标是在现有目录芯片上补齐 Windows 原生终端与常用 shell 支持,同时保持 macOS/Linux/普通 SSH 的既有行为。技术依据、实验与官方来源见 [跨平台研究](directory-picker-cross-platform.md);当前功能规格见 [directory-picker.md](directory-picker.md)。 + +## 1. 当前交付与后续范围 + +当前 PR 实现目录菜单、绝对路径切换、真实 cwd 确认、手动 cd 联动及默认开启的 Context Chips 设置。Windows 本地、WSL/Git Bash/Cygwin 仍为不可用,不应先撤销门槛再寻找兼容方案。 + +后续按**路径与能力 → Windows PowerShell → CMD → WSL/兼容层 → 扩展远程**推进。macOS/Linux 的会话集成可与 PowerShell 阶段复用协议基础,但不同 shell 独立验收,不要求为增加一个平台一次性重写全部终端。 + +## 2. 统一能力与状态 + +不能只有一个 `supported`:至少分别描述 `readCwd`、`listDirectories`、`changeDirectory`、`confirmChange`。只有目标环境和这些能力一致,菜单才可执行切换。例如收到 OSC cwd 但没有正确的 WSL 枚举能力时,只能展示位置;没有可用的安全执行/确认时不能给出可操作假象。 + +候选能力快照应包含下列语义;这是规划,不是当前新增的公共 RPC 协议: + +| 字段 | 用途 | +| --- | --- | +| session/connection/shell generation | 绑定实际目标,重连与嵌套 shell 变化废弃旧请求 | +| shell kind/version/confidence | 区分 spawn 信息、登录 hint 与当前活动 shell;未知时拒绝危险猜测 | +| filesystem authority/path flavor | native-win32、posix、wsl:distro、msys、cygwin、ssh 等环境身份 | +| provider/cwd/home/source/revision | 表示 FileSystem、非文件系统、未知与过期;保留单会话排序 | +| integration status/capabilities | active、fallback、unsupported、policy-blocked 等可解释状态 | + +UI 显示值可以缩写和截断;执行目标保留对应命名空间的绝对路径。调用前重新校验 cwd revision/身份,结果按真实上报确认,不能只因命令已写入就宣布成功。关闭工具栏停止其额外工作,但不能拆掉其他功能仍在消费的共享集成。 + +## 3. 阶段 A:路径、能力及确认边界 + +**交付**:抽出按 path flavor 的解析、父目录、拼接、比较和显示逻辑,扩展目录控制器所需的 typed capability;保持现有 UI 与 POSIX 默认行为。 + +调整位置:`domain/directoryPicker.ts`、`terminalDirectoryController.ts`、`useTerminalDirectorySession.ts`、`infrastructure/services/terminalDirectory.ts` 及对应 bridge 类型。将变更目录的意图构造注入控制器或放入明确 shell 适配,不让控制器固定引用唯一 POSIX builder。 + +优先复用 `resolveInteractiveTerminalCdIntent` 的 POSIX 路径与控制字节规则。PowerShell/CMD 新策略不得直接改变该函数现有恢复目录/SFTP 调用者的契约。现有 AI helper 仅提取经过验证的纯引用函数,避免复用含子 shell/eval 的执行包装。 + +**验收门槛**:POSIX `/`、Windows `C:\`、UNC `\\server\share\`、相对盘符 `C:foo`、大小写和 symlink 不混淆;文件系统 authority 不同的同名路径永不互用。旧的目录、广播、草稿、会话失效、关闭 chips 和 SFTP 测试保持通过。 + +## 4. 阶段 B:shell 报告基础与 PowerShell 5.1/7 + +**交付**:本地 PowerShell FileSystem 目录展示、子目录/父目录导航、手动切换联动、真实结果确认。目标包括项目支持 Windows 版本上的系统 Windows PowerShell 5.1 和用户安装的 PowerShell 7;具体 Windows build 按当时 Electron/ConPTY 支持矩阵验证,不能用“包能打出来”代替实机支持。 + +实施点: + +1. 在 `electron/bridges/terminalBridge.cjs` 的 spawn 参数解析后加入可测试的会话启动方案;脚本由 `tempDirBridge` 管理。保留 profile、PSReadLine、用户启动参数和原 prompt。未知参数/策略阻止时不注入,不改执行策略。 +2. 位置取自该 runspace 的 FileSystem ProviderPath;`HKLM:` 等报告为非文件系统。切换使用 LiteralPath 和 PowerShell 引用,在原 shell 生效。 +3. worker 接收并归一化 shell 状态,随后通过既有 session 事件/preload 传递给应用层。协议版本、字段转义、最大长度、旧代次与来源必须可验证;是否复用 OSC 633 在此阶段明确。 +4. cwd 报告与就绪证明分开;敏感输入、半行草稿和 TUI 仍会阻止注入。不能把可以打印任意 OSC 的进程当成 host authority。 +5. 使用本地 FS 读取原生 Windows 路径;新进入的盘符/UNC 要重新校验,FileSystem home 才可显示为 `~`。 + +**验收门槛**:Windows 实际 ConPTY 中验证切换盘符、空格、中文、单引号、方括号、`$`、反引号、只读目录、删除目录、policy-blocked、`-NoProfile`、自定义 prompt。registry/Env provider 不冒充本地目录;PowerShell 5.1 不使用仅 6+ 可用的 ESC 语法。启动失败不能损坏用户 profile,关闭后无持久配置变更。 + +同一基础在 macOS/Linux 新会话内按 shell 启用:bash 兼容 3.2 的 cwd hook,zsh 的 precmd/chpwd,fish 的事件。无法集成的 dash/ash 保留现有进程回退。完整命令生命周期在不同旧版本上未必可用,不能为 cwd 功能强制要求全部实现 preexec。 + +## 5. 阶段 C:CMD 原生路径导航 + +**交付**:会话级 cwd 上报、盘符切换、普通路径菜单、清楚的受限路径提示。 + +PROMPT 包装保留用户原值,`$P` 提供位置。`cd /d` 必须在原 CMD 中执行,不经另一个 `cmd /c`。独立实现并验证交互/batch 转义、命令扩展、`%`/`!`、编码与 ERRORLEVEL;不要通过临时改变 delayed expansion/AutoRun 绕过问题。 + +**范围选择**:可先支持经过验证的盘符绝对目录,对 `%`/`!` 和 UNC 明确不可切换。UNC 如果以后采用 pushd/popd,要先定义临时盘符、目录栈、退出及失败清理,不把这个动作伪装成无副作用的 cd。 + +**验收门槛**:命令扩展开/关、delayed expansion 开/关、默认/自定义 PROMPT、空格/中文/`&`/`^`/`%`/`!`、从 C 到 D、访问被拒、共享不可达。UI 不能把拒绝/失败当 `± 0` 类的空成功;不执行多余命令、不改变父 CMD 之外的进程来冒充结果。 + +## 6. 阶段 D:WSL、Git Bash 与 Cygwin + +**交付**:明确目标 distro/兼容层的 cwd 与目录读取适配。Windows 上只是发现了 bash.exe/wsl.exe,不足以启用 Directory Picker。 + +- WSL 在所选 distro 内获取 shell 上报和结构化目录数据,验证 distro 身份及 `wslpath`/UNC 映射策略;同一路径不能跨 distro 复用缓存。WSL1/2 的支持范围按实测决定。 +- Git Bash/Cygwin 各自验证 mount/drive/symlink 映射,不能把 POSIX 路径字符串直接交给 Windows `fs`。 +- helper 协议保留原始名称、文件类型和目录链接;支持有限输出、取消、权限失败。不得使用 `ls` 的展示文本做机器目录清单。 + +**验收门槛**:Linux home、Windows 挂载盘、两个 distro 相同路径、大小写敏感目录、链接、编码、启动参数和 unavailable provider。不支持的映射有具体提示;测试不得通过修改用户 distro 配置来获得成功。 + +## 7. 阶段 E:远程与嵌套 shell + +普通 Unix SSH 保留当前严格探测和 exact-session SFTP 约束。远程集成是目标 shell 的独立能力,不随本机启动脚本自动生效。已有显式 OSC 7 配置写 rc,与后续无持久化注入必须在 UI 和权限上区分。 + +逐项处理 SSH 到 Windows、su/sudo、嵌套 shell、tmux/screen、容器、mosh/ET、SFTP chroot 和单通道跳板。一个 cwd 报告不能证明登录用户的 SFTP 有相同目录视图;无法证明映射或当前活动 shell 身份时,保持不可用,不新建另一个登录。 + +**验收门槛**:连接及 shell 代次变更、主机不同的同名 cwd、权限跨用户、拒绝额外通道、工作目录已删除、重连/hibernate/附加窗口。自动安装远端脚本不纳入当前计划的默认行为;必须经独立范围确认。 + +## 8. 必须保留的回归与完成标准 + +| 类别 | 验收内容 | +| --- | --- | +| 命令与路径 | 每个 shell 的实际输入结果;绝对路径不受 CDPATH/异步 cwd 改变影响;特殊字符不执行额外代码 | +| shell 生命周期 | prompt、原状态码、PATH、历史与主题不被破坏;login、无 profile、特殊启动参数有明确行为 | +| 协议 | 分片/合并、BEL/ST、编码、Windows URI、大小上限、伪造/旧报告、重复集成和 nonce 限制 | +| 正确性 | 手动 cd、函数 cd、延迟 cd、失败 cd、逻辑/物理路径、provider 切换、目录列表与真实 cwd 一致 | +| 安全与目标 | 密码/MFA/sudo、TUI、半行输入、广播开启、切焦点/重连:没有错误目标写入 | +| 平台 | Windows 原生 ConPTY 的 5.1/7/CMD;macOS 系统 bash 3.2 与 zsh;Linux bash/dash/ash/fish/zsh | +| 发行版 | Ubuntu/Debian、Fedora/Rocky 或 Alma、Arch、Alpine 作为后端 shell 样本;不把同一 shell 的语法复制测试替代真实环境 | +| 性能 | 有效集成优先事件更新,回退探测合并/单飞/有超时;空闲不额外轮询,关闭 chips 不产生其额外读写 | +| 打包 | 外部 shell 使用真实脚本资源或受管副本,不依赖 asar 虚拟路径;native helper 如有新增,验证各架构与签名;资源变更通过 `npm run pack:dir` | + +现有 domain、controller、registry、hook、真实 PTY、SSH fixture 与 Windows CI 是起点。后续 Windows 测试必须使用真实 Windows shell/ConPTY 验证 runspace 状态,不能仅靠 Linux mock 或 Windows 编译成功。是否开启某个平台,由这些验收结果决定,不以删除平台 gate 作为完成标准。 + +当前 PR 只追加研究与规划;阶段 A–E 的产品实现、脚本安装及协议扩展由后续独立改动完成。 diff --git a/docs/research/terminal-compose-context/directory-picker.md b/docs/research/terminal-compose-context/directory-picker.md index 4cbdf80a8..d18e1df8a 100644 --- a/docs/research/terminal-compose-context/directory-picker.md +++ b/docs/research/terminal-compose-context/directory-picker.md @@ -6,6 +6,10 @@ 本地模拟见 [directory-picker-demo.html](directory-picker-demo.html),不访问文件系统或真实终端。 +Context Chips 在“设置 → 终端”中默认开启,可关闭整行。该偏好随现有终端设置保存,旧配置默认开启;关闭不会发送或清空草稿,也不会继续订阅芯片的额外 cwd 刷新。 + +Windows 原生 shell、跨平台路径与 shell 集成的后续范围见 [跨平台研究](directory-picker-cross-platform.md) 和 [开发计划](directory-picker-follow-up.md),不改变本 PR 的产品支持范围。 + ## 1. 目标与首期边界 用户在撰写命令前,能看到**当前聚焦终端的真实工作目录**,并通过一个小菜单搜索当前层子目录、返回父目录、选择目录,使接下来执行的命令落在目标位置。 diff --git a/domain/directoryPicker.test.ts b/domain/directoryPicker.test.ts new file mode 100644 index 000000000..63e30d391 --- /dev/null +++ b/domain/directoryPicker.test.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { directoryDisplayName, directoryEntries, directoryLabel, directoryParent, filterDirectories, isDirectoryPath } from './directoryPicker'; + +test('directory paths preserve names, enforce home boundaries, and stop at root', () => { + assert.equal(directoryLabel('/home/me/a ', '/home/me'), '~/a '); + assert.equal(directoryLabel('/home/metal/a', '/home/me'), '/home/metal/a'); + assert.equal(directoryParent('/'), null); + assert.equal(directoryParent('/one/'), '/'); + assert.equal(directoryParent('/one/two '), '/one'); + assert.ok(isDirectoryPath("/a '$()`中文")); + for (const value of ['~/a', 'C:\\a', '/a\n', '/a\x1b', '/a\0']) assert.equal(isDirectoryPath(value), false); + assert.equal(directoryDisplayName('a\n\x1b'), 'a\\x0a\\x1b'); +}); + +test('directory results include only directories and directory symlinks; filtering is local and natural', () => { + const entries = directoryEntries('/base', [ + { name: 'app10', type: 'directory', size: '', lastModified: '' }, + { name: 'app2', type: 'symlink', linkTarget: 'directory', size: '', lastModified: '' }, + { name: '.config', type: 'directory', size: '', lastModified: '' }, + { name: 'broken', type: 'symlink', size: '', lastModified: '' }, + { name: 'file', type: 'file', size: '', lastModified: '' }, + { name: '..', type: 'directory', size: '', lastModified: '' }, + ]); + assert.deepEqual(filterDirectories(entries, 'APP', false).map(entry => entry.path), ['/base/app2', '/base/app10']); + assert.equal(filterDirectories(entries, '', false).length, 2); + assert.equal(filterDirectories(entries, '', true).length, 3); + assert.deepEqual(filterDirectories(entries, 'missing', true), []); +}); diff --git a/domain/directoryPicker.ts b/domain/directoryPicker.ts new file mode 100644 index 000000000..7854da5ca --- /dev/null +++ b/domain/directoryPicker.ts @@ -0,0 +1,44 @@ +import type { RemoteFile } from './models'; +import { resolveInteractiveTerminalCdIntent } from './sessionRestore'; + +export type DirectoryEntry = { name: string; path: string; hidden: boolean }; +export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'changeFailed' | 'unsupportedPath'; + +export class DirectoryPickerError extends Error { + constructor(public readonly code: DirectoryPickerErrorCode) { super(code); } +} + +export function isDirectoryPath(path: string | null | undefined): path is string { + return typeof path === 'string' && path.startsWith('/') && !!resolveInteractiveTerminalCdIntent(path); +} + +export function directoryParent(path: string): string | null { + const trimmed = path.replace(/\/+$/, '') || '/'; + return trimmed === '/' ? null : trimmed.slice(0, trimmed.lastIndexOf('/')) || '/'; +} + +export function directoryLabel(path: string, home?: string | null): string { + const prefix = home?.replace(/\/+$/, ''); + if (prefix && (path === prefix || path.startsWith(prefix + '/'))) return '~' + path.slice(prefix.length); + return path; +} + +export function directoryEntries(path: string, files: readonly RemoteFile[]): DirectoryEntry[] { + return files.filter(file => file.type === 'directory' || (file.type === 'symlink' && file.linkTarget === 'directory')) + .filter(file => file.name !== '.' && file.name !== '..' && !file.name.includes('/') && file.name.length > 0) + .map(file => ({ name: file.name, path: (path === '/' ? '' : path.replace(/\/+$/, '')) + '/' + file.name, + hidden: file.hidden === true || file.name.startsWith('.') })); +} + +const names = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); +export function filterDirectories(entries: readonly DirectoryEntry[], query: string, showHidden: boolean): DirectoryEntry[] { + const needle = query.toLocaleLowerCase(); + return entries.filter(entry => (showHidden || !entry.hidden) && entry.name.toLocaleLowerCase().includes(needle)) + .sort((a, b) => names.compare(a.name, b.name) || a.name.localeCompare(b.name)); +} + +/** Control characters remain visible as data rather than affecting menu layout. */ +export function directoryDisplayName(name: string): string { + return Array.from(name, char => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127 + ? '\\x' + char.charCodeAt(0).toString(16).padStart(2, '0') : char).join(''); +} diff --git a/domain/models/terminal.ts b/domain/models/terminal.ts index 1620b1807..294858196 100644 --- a/domain/models/terminal.ts +++ b/domain/models/terminal.ts @@ -71,6 +71,8 @@ export interface KeywordHighlightRule { export type TerminalTabDoubleClickBehavior = 'duplicate' | 'copy' | 'disabled'; export interface TerminalSettings { + /** Context chips below quick commands in the compose bar. */ + contextChipsEnabled?: boolean; // Rendering scrollback: number; // Number of lines kept in buffer drawBoldInBrightColors: boolean; // Draw bold text in bright colors @@ -438,6 +440,7 @@ export const normalizeTerminalSettings = ( const mergedSettings = { ...DEFAULT_TERMINAL_SETTINGS, ...(settings ?? {}), + contextChipsEnabled: settings?.contextChipsEnabled !== false, middleClickBehavior, middleClickPaste: middleClickBehavior === 'paste', wordSeparators, @@ -531,6 +534,7 @@ export function isLegacyDefaultShiftEnterNewlineText(value: unknown): boolean { } const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = { + contextChipsEnabled: true, scrollback: DEFAULT_TERMINAL_SCROLLBACK, drawBoldInBrightColors: true, terminalEmulationType: 'xterm-256color', diff --git a/domain/settingsSearchCatalog.ts b/domain/settingsSearchCatalog.ts index 805c6152c..00018accb 100644 --- a/domain/settingsSearchCatalog.ts +++ b/domain/settingsSearchCatalog.ts @@ -429,6 +429,13 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [ descriptionKey: "settings.terminal.behavior.shiftEnterForceText.desc", sectionKey: "settings.terminal.section.behavior", }, + { + id: "terminal-context-chips", + tab: "terminal", + labelKey: "settings.terminal.behavior.contextChips", + descriptionKey: "settings.terminal.behavior.contextChips.desc", + sectionKey: "settings.terminal.section.behavior", + }, { id: "terminal-clear-wipes-scrollback", tab: "terminal", diff --git a/electron/bridges/sftpBridge.cjs b/electron/bridges/sftpBridge.cjs index bddcb9b80..970e1662b 100644 --- a/electron/bridges/sftpBridge.cjs +++ b/electron/bridges/sftpBridge.cjs @@ -1985,7 +1985,9 @@ async function openSftpForSession(_event, payload) { throwIfAborted(payload?.abortSignal); let sourceSessionId = sessionId; let source; - if (payload?.expectedEndpoint) { + if (payload?.reuseExactSessionOnly === true) { + source = { sessionId, ...ensureRemoteSftpSupport(sessionId) }; + } else if (payload?.expectedEndpoint) { const expectedEndpoint = buildConnectionReuseEndpoint(payload.expectedEndpoint); source = findRemoteSftpSourceByEndpoint( sessionId, @@ -2006,7 +2008,7 @@ async function openSftpForSession(_event, payload) { session.singleChannelSsh || remoteSoftwareRequiresSingleChannel(session.remoteSshVersion || sshClient?._remoteVer) ) { - if (typeof session._openDedicatedSftp === "function") { + if (payload?.reuseExactSessionOnly !== true && typeof session._openDedicatedSftp === "function") { const opened = await session._openDedicatedSftp(payload); const client = sftpClients?.get(opened.sftpId); if (client) client.__netcattySourceSessionId = sourceSessionId; diff --git a/electron/bridges/sftpBridge.singleChannelDial.test.cjs b/electron/bridges/sftpBridge.singleChannelDial.test.cjs index d37501d97..aeb26c281 100644 --- a/electron/bridges/sftpBridge.singleChannelDial.test.cjs +++ b/electron/bridges/sftpBridge.singleChannelDial.test.cjs @@ -5,6 +5,45 @@ const assert = require("node:assert/strict"); const bridge = require("./sftpBridge.cjs"); const { buildConnectionReuseEndpoint, normalizeEndpoint } = require("./sshConnectionPool.cjs"); +test('exact-session-only browse refuses the dedicated-login path on single-channel hosts', async () => { + let dialed = false; + bridge.init({ sessions: new Map([['terminal', { + singleChannelSsh: true, conn: { sftp() { throw new Error('must not borrow'); } }, + async _openDedicatedSftp() { dialed = true; return { sftpId: 'wrong' }; }, + }]]), sftpClients: new Map(), electronModule: {} }); + await assert.rejects(bridge.openSftpForSession(null, { sessionId: 'terminal', reuseExactSessionOnly: true }), + { code: 'ERR_SFTP_SINGLE_CHANNEL_BASTION' }); + assert.equal(dialed, false); +}); + +test('exact-session-only browse never borrows a different live session', async () => { + let borrowed = false; + bridge.init({ sessions: new Map([['other', { conn: { sftp() { borrowed = true; } } }]]), + sftpClients: new Map(), electronModule: {} }); + await assert.rejects(bridge.openSftpForSession(null, { sessionId: 'missing', reuseExactSessionOnly: true }), /not found/); + assert.equal(borrowed, false); +}); + +test('exact-session-only browse uses authenticated password/proxy identity without reconstructing credentials', async () => { + const options = { hostname: 'host', username: 'me', password: 'test-only-password', + authMethod: 'password', proxy: { type: 'socks5', host: 'proxy', port: 1080 } }; + let opened = 0; let ended = false; + const channel = { readdir() {}, stat() {}, mkdir() {}, unlink() {}, end() { ended = true; } }; + const conn = { sftp(callback) { opened++; callback(null, channel); } }; + const clients = new Map(); + bridge.init({ sessions: new Map([['terminal', { + conn, _reuseEndpoint: normalizeEndpoint(buildConnectionReuseEndpoint(options)), + }]]), sftpClients: clients, electronModule: {} }); + const result = await bridge.openSftpForSession(null, { + sessionId: 'terminal', reuseExactSessionOnly: true, fileProtocol: 'sftp', + expectedEndpoint: { hostname: 'host', username: 'me' }, + }); + assert.equal(result.sourceSessionId, 'terminal'); + assert.equal(opened, 1); + await bridge.closeSftp(null, { sftpId: result.sftpId }); + assert.equal(ended, true); +}); + test("GUI vault reconnect finds the dedicated terminal dial without a source-session hint", async (t) => { t.mock.method(require("node:net").Socket.prototype, "connect", () => { throw new Error("Unexpected fresh vault dial instead of the terminal profile"); diff --git a/electron/bridges/sshBridge/sessionOps.cjs b/electron/bridges/sshBridge/sessionOps.cjs index 84a8a863b..681212cbb 100644 --- a/electron/bridges/sshBridge/sessionOps.cjs +++ b/electron/bridges/sshBridge/sessionOps.cjs @@ -142,6 +142,7 @@ function createSessionOpsApi(ctx) { return { success: true, remoteSshVersion: session.remoteSshVersion || '', + singleChannelSsh: session.singleChannelSsh === true, }; } diff --git a/electron/bridges/sshBridge/sessionOps.cwd.test.cjs b/electron/bridges/sshBridge/sessionOps.cwd.test.cjs index 7c9b10022..9c4e1c90c 100644 --- a/electron/bridges/sshBridge/sessionOps.cwd.test.cjs +++ b/electron/bridges/sshBridge/sessionOps.cwd.test.cjs @@ -12,6 +12,16 @@ function quoteShellArg(value) { return "'" + String(value).replace(/'/g, "'\\''") + "'"; } +test('session metadata exposes runtime single-channel restrictions without opening exec', async () => { + let execCount = 0; + const api = makeApi({ singleChannelSsh: true, remoteSshVersion: 'OpenSSH_9.6', + conn: { exec() { execCount++; } } }); + assert.deepEqual(await api.getSessionRemoteInfo(null, { sessionId: 'session-1' }), { + success: true, singleChannelSsh: true, remoteSshVersion: 'OpenSSH_9.6', + }); + assert.equal(execCount, 0); +}); + function makePwdStream(cwd, loginPid) { const stream = new EventEmitter(); stream.stderr = new EventEmitter(); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index a3a68fd8f..9e6bc5fde 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -945,10 +945,10 @@ function createPreloadApi(ctx) { const result = await ipcRenderer.invoke("netcatty:sftp:openForSession", { ...(options || {}), sessionId, - expectedEndpoint: options, + expectedEndpoint: options?.reuseExactSessionOnly === true ? undefined : options, }); if ( - options?.requireExactSourceSession === true + (options?.requireExactSourceSession === true || options?.reuseExactSessionOnly === true) && result.sourceSessionId !== sessionId ) { if (result.sftpId) { diff --git a/electron/preload/api.stageUploadFile.test.cjs b/electron/preload/api.stageUploadFile.test.cjs index ff9f2b4a0..a7300fc46 100644 --- a/electron/preload/api.stageUploadFile.test.cjs +++ b/electron/preload/api.stageUploadFile.test.cjs @@ -220,6 +220,19 @@ test("openSftpForSession keeps the SSH source session id when options include an assert.equal(invoked[0].payload.expectedEndpoint.sessionId, "sftp-left-browse-session"); }); +test('exact-session-only browse does not fabricate a credential profile', async () => { + const calls = []; + const api = createPreloadApi({ webUtils: {}, ipcRenderer: { + on() {}, removeListener() {}, + async invoke(channel, payload) { calls.push({ channel, payload }); return { sftpId: 'channel', sourceSessionId: 'terminal' }; }, + } }); + assert.equal(await api.openSftpForSession('terminal', { + hostname: 'host', username: 'me', reuseExactSessionOnly: true, fileProtocol: 'sftp', + }), 'channel'); + assert.equal(calls[0].payload.expectedEndpoint, undefined); + assert.equal(calls[0].payload.reuseExactSessionOnly, true); +}); + test("strict openSftpForSession closes and rejects a mismatched source result", async () => { const invoked = []; const api = createPreloadApi({ diff --git a/global.d.ts b/global.d.ts index 7bb17a752..48c9a390c 100644 --- a/global.d.ts +++ b/global.d.ts @@ -182,6 +182,8 @@ declare global { sourceSessionId?: string; /** Require openSftpForSession to use exactly the requested live session. */ requireExactSourceSession?: boolean; + /** Use the named live terminal only; never open a dedicated/fresh login. */ + reuseExactSessionOnly?: boolean; // Skip POSIX process discovery when copying a network-device session. skipShellPidDiscovery?: boolean; /** diff --git a/infrastructure/services/terminalDirectory.local.test.ts b/infrastructure/services/terminalDirectory.local.test.ts new file mode 100644 index 000000000..a914858a1 --- /dev/null +++ b/infrastructure/services/terminalDirectory.local.test.ts @@ -0,0 +1,161 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createRequire } from 'node:module'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createTerminalDirectoryIO } from './terminalDirectory'; +import { createTerminalDirectoryController } from '../../application/state/terminalDirectoryController'; +import { terminalCwdStore } from '../../application/state/terminalCwdStore'; +import { + observeTerminalDirectory, registerTerminalDirectory, refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh, +} from '../../application/state/terminalDirectoryRegistry'; + +const require = createRequire(import.meta.url); + +test('directory picker changes a real POSIX PTY cwd with quoted names and directory symlinks', { + skip: process.platform === 'win32', timeout: 20000, +}, async t => { + const tempDirBridge = require('../../electron/bridges/tempDirBridge.cjs'); + const { readLocalSessionCwd } = require('../../electron/bridges/localSessionCwd.cjs'); + const pty = require('node-pty') as typeof import('node-pty'); + tempDirBridge.ensureTempDir(); + const fixture = fs.mkdtempSync(tempDirBridge.getTempFilePath('directory-picker-')); + const name = "space ' $() `literal` 中文"; + const target = path.join(fixture, name); + fs.mkdirSync(target); + fs.symlinkSync(target, path.join(fixture, 'link')); + let ready = false; + const shell = pty.spawn('/bin/bash', ['--noprofile', '--norc', '-i'], { + cwd: fixture, env: { ...process.env, PS1: '__DIRECTORY_READY__ ', PROMPT_COMMAND: '' }, + cols: 100, rows: 24, + }); + shell.onData(data => { if (data.includes('__DIRECTORY_READY__ ')) ready = true; }); + const waitReady = async () => { + const deadline = Date.now() + 4000; + while (!ready && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20)); + assert.ok(ready, 'shell reached its prompt'); + }; + t.after(() => { shell.kill(); fs.rmSync(fixture, { recursive: true, force: true }); }); + await waitReady(); + let published = ''; + const io = createTerminalDirectoryIO({ + getSessionPwd: async () => readLocalSessionCwd({ pty: shell }), + realpathLocal: async value => fs.promises.realpath(value), + writeToSession: (id, data) => { assert.equal(id, 'real-shell'); ready = false; shell.write(data); }, + } as unknown as NetcattyBridge, 'real-shell', { local: true, hostname: '', username: '' }); + const controller = createTerminalDirectoryController({ + sessionId: 'real-shell', io, isReady: () => ready, isCurrent: () => true, + publish: cwd => { published = cwd; }, + }); + t.after(() => controller.dispose()); + await controller.change(target, new AbortController().signal, () => {}); + assert.equal(await io.cwd(), fs.realpathSync(target)); + assert.equal(published, fs.realpathSync(target)); + await waitReady(); + await controller.change(path.join(fixture, 'link'), new AbortController().signal, () => {}); + assert.equal(await io.cwd(), fs.realpathSync(target)); +}); + +test('a real nested Bash OSC 7 cwd survives outer PTY probes after output settles', { + skip: process.platform !== 'linux', timeout: 20000, +}, async t => { + const tempDirBridge = require('../../electron/bridges/tempDirBridge.cjs'); + const { readLocalSessionCwd } = require('../../electron/bridges/localSessionCwd.cjs'); + const pty = require('node-pty') as typeof import('node-pty'); + tempDirBridge.ensureTempDir(); + const fixture = fs.mkdtempSync(tempDirBridge.getTempFilePath('nested-directory-shell-')); + const id = 'nested-directory-shell'; + const shell = pty.spawn('/bin/bash', ['--noprofile', '--norc', '-i'], { + cwd: fixture, env: { ...process.env, PS1: '__OUTER_READY__ ', PROMPT_COMMAND: '' }, cols: 100, rows: 24, + }); + let output = ''; + let reports = 0; + const published: string[] = []; + const subscription = shell.onData(data => { + output += data; + scheduleObservedTerminalDirectoryRefresh(id); + // Parse actual bytes from the child shell, including split OSC chunks. + const paths = output.split('\x1b]7;file://localhost').slice(1) + .filter(chunk => chunk.includes('\x07')).map(chunk => chunk.split('\x07')[0]); + if (paths.length > reports) { + reports = paths.length; + terminalCwdStore.setCwd(id, paths.at(-1)!, 'osc7'); + } + }); + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => true, + io: { cwd: async () => { + const result = await readLocalSessionCwd({ pty: shell }); + assert.ok(result.success); return result.cwd; + }, list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} }, + publish: cwd => { published.push(cwd); terminalCwdStore.setCwd(id, cwd, 'backend-strict'); }, + }); + const unregister = registerTerminalDirectory(id, controller); + const stopObserving = observeTerminalDirectory(id); + t.after(() => { stopObserving(); unregister(); subscription.dispose(); shell.kill(); fs.rmSync(fixture, { recursive: true, force: true }); }); + const waitFor = async (condition: () => boolean) => { + const deadline = Date.now() + 5000; + while (!condition() && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 25)); + assert.ok(condition(), 'nested shell reached the expected prompt/cwd'); + }; + await waitFor(() => output.includes('__OUTER_READY__ ')); + shell.write('PS1="__CHILD_READY__ " PROMPT_COMMAND=\'printf "\\033]7;file://localhost%s\\007" "$PWD"\' bash --noprofile --norc -i\r'); + await waitFor(() => reports > 0); + shell.write('cd /\r'); + await waitFor(() => terminalCwdStore.getCwd(id) === '/'); + // Demonstrate the original lookup really observes the outer shell, then + // let the real 150 ms debounce expire before checking the picker/tracker. + assert.equal((await readLocalSessionCwd({ pty: shell })).cwd, fs.realpathSync(fixture)); + await new Promise(resolve => setTimeout(resolve, 350)); + assert.equal(terminalCwdStore.getCwd(id), '/'); + refreshObservedTerminalDirectory(id); + assert.equal(await controller.refresh(), '/'); + assert.equal(terminalCwdStore.getSource(id), 'osc7'); + assert.ok(!published.includes(fs.realpathSync(fixture)), 'outer cwd never overwrote the child report'); +}); + +test('manual cd and delayed shell functions update the observed cwd without shell integration', { + skip: process.platform === 'win32', timeout: 20000, +}, async t => { + const tempDirBridge = require('../../electron/bridges/tempDirBridge.cjs'); + const { readLocalSessionCwd } = require('../../electron/bridges/localSessionCwd.cjs'); + const pty = require('node-pty') as typeof import('node-pty'); + tempDirBridge.ensureTempDir(); + const fixture = fs.mkdtempSync(tempDirBridge.getTempFilePath('manual-directory-cd-')); + const first = path.join(fixture, 'first'); const second = path.join(fixture, 'second'); + fs.mkdirSync(first); fs.mkdirSync(second); + const id = 'manual-cd-shell'; + // An intentionally non-standard PS1: no trusted prompt/completion callback + // or OSC directory reporting is available to drive chip updates. + const shell = pty.spawn('/bin/bash', ['--noprofile', '--norc', '-i'], { + cwd: fixture, env: { ...process.env, PS1: 'custom input: ', PROMPT_COMMAND: '' }, cols: 100, rows: 24, + }); + let output = ''; let published = ''; + const subscription = shell.onData(data => { + output += data; + scheduleObservedTerminalDirectoryRefresh(id); + }); + const controller = createTerminalDirectoryController({ + sessionId: id, isCurrent: () => true, isReady: () => false, + io: { cwd: async () => { + const result = await readLocalSessionCwd({ pty: shell }); + assert.ok(result.success); return result.cwd; + }, list: async () => ({ entries: [], home: null }), realpath: async value => value, + write() { assert.fail('manual navigation must not use the picker write action'); } }, + publish: cwd => { published = cwd; }, + }); + const unregister = registerTerminalDirectory(id, controller); + const stopObserving = observeTerminalDirectory(id); + t.after(() => { stopObserving(); unregister(); subscription.dispose(); shell.kill(); fs.rmSync(fixture, { recursive: true, force: true }); }); + const waitFor = async (condition: () => boolean) => { + const deadline = Date.now() + 5000; + while (!condition() && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 25)); + assert.ok(condition(), 'cwd followed actual shell output'); + }; + await waitFor(() => output.includes('custom input: ')); + shell.write(`cd -- '${first}'\r`); + await waitFor(() => published === fs.realpathSync(first)); + // The directory changes well after a fixed post-Enter timer would fire. + shell.write(`go_later() { sleep 0.6; cd -- '${second}'; }; go_later\r`); + await waitFor(() => published === fs.realpathSync(second)); +}); diff --git a/infrastructure/services/terminalDirectory.ssh.test.ts b/infrastructure/services/terminalDirectory.ssh.test.ts new file mode 100644 index 000000000..32787b55f --- /dev/null +++ b/infrastructure/services/terminalDirectory.ssh.test.ts @@ -0,0 +1,113 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createRequire } from 'node:module'; +import { generateKeyPairSync } from 'node:crypto'; +import { spawn } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createTerminalDirectoryIO } from './terminalDirectory'; +import { createTerminalDirectoryController } from '../../application/state/terminalDirectoryController'; +import { + observeTerminalDirectory, registerTerminalDirectory, scheduleObservedTerminalDirectoryRefresh, +} from '../../application/state/terminalDirectoryRegistry'; + +const require = createRequire(import.meta.url); + +test('manual SSH cd refreshes through the real session cwd probe with no OSC or trusted prompt', { + skip: process.platform === 'win32', timeout: 20000, +}, async t => { + const { Client, Server } = require('ssh2') as typeof import('ssh2'); + const pty = require('node-pty') as typeof import('node-pty'); + const tempDirBridge = require('../../electron/bridges/tempDirBridge.cjs'); + const { createSessionOpsApi } = require('../../electron/bridges/sshBridge/sessionOps.cjs'); + tempDirBridge.ensureTempDir(); + const fixture = fs.mkdtempSync(tempDirBridge.getTempFilePath('ssh-directory-cd-')); + const first = path.join(fixture, 'first'); const second = path.join(fixture, 'second'); + fs.mkdirSync(first); fs.mkdirSync(second); + const key = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs1', format: 'pem' }); + const client = new Client(); + const connections = new Set(); + const children = new Set>(); + let shell: import('node-pty').IPty | null = null; + let execs = 0; + const server = new Server({ hostKeys: [key] }, connection => { + connections.add(connection); + connection.on('error', () => {}); + connection.on('close', () => connections.delete(connection)); + connection.on('authentication', auth => { + if (auth.method === 'password' && auth.username === 'fixture' && auth.password === 'fixture-only') auth.accept(); + else auth.reject(); + }); + connection.on('ready', () => connection.on('session', accept => { + const session = accept(); + session.on('pty', acceptPty => acceptPty?.()); + session.on('shell', acceptShell => { + const channel = acceptShell(); + shell = pty.spawn('/bin/bash', ['--noprofile', '--norc', '-i'], { + cwd: fixture, env: { ...process.env, PS1: 'custom remote input: ', PROMPT_COMMAND: '' }, cols: 100, rows: 24, + }); + const running = shell; + running.onData(data => channel.write(data)); + channel.on('data', data => running.write(data.toString())); + channel.on('close', () => { try { running.kill(); } catch { /* already exited */ } }); + }); + session.on('exec', (acceptExec, _reject, info) => { + execs++; + const channel = acceptExec(); + // Execute the production getSessionPwd script on the fixture server; + // its own cwd stays at fixture, distinct from the interactive PTY cwd. + const child = spawn('/bin/sh', ['-c', info.command], { cwd: fixture, env: process.env }); + children.add(child); + child.stdout.on('data', data => channel.write(data)); + child.stderr.on('data', data => channel.stderr.write(data)); + child.on('close', code => { children.delete(child); channel.exit(code ?? 1); channel.end(); }); + }); + })); + }); + let unregister = () => {}; + let stopObserving = () => {}; + t.after(async () => { + stopObserving(); unregister(); client.destroy(); + for (const child of children) child.kill(); + try { shell?.kill(); } catch { /* already exited */ } + for (const connection of connections) connection.end(); + if (server.address()) await new Promise(resolve => server.close(() => resolve())); + fs.rmSync(fixture, { recursive: true, force: true }); + }); + await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }); + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + await new Promise((resolve, reject) => { + client.once('ready', resolve); client.once('error', reject); + client.connect({ host: '127.0.0.1', port: address.port, username: 'fixture', password: 'fixture-only' }); + }); + const channel = await new Promise((resolve, reject) => { + client.shell({ term: 'xterm-256color', cols: 100, rows: 24 }, (error, stream) => error ? reject(error) : resolve(stream)); + }); + const id = 'ssh-cd-fixture'; + let output = ''; let published = ''; + channel.on('data', data => { output += data.toString(); scheduleObservedTerminalDirectoryRefresh(id); }); + const waitFor = async (condition: () => boolean) => { + const deadline = Date.now() + 6000; + while (!condition() && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 25)); + assert.ok(condition(), 'actual SSH shell cwd reached the observer'); + }; + await waitFor(() => !!shell && output.includes('custom remote input: ')); + const sessions = new Map([[id, { protocol: 'ssh', conn: client, stream: channel, + shellPid: String(shell!.pid), remoteSshVersion: 'OpenSSH_9.6' }]]); + const api = createSessionOpsApi({ sessions, setTimeout, clearTimeout, + quoteShellArg: (value: string) => "'" + value.replace(/'/g, "'\\''") + "'", log() {} }); + const io = createTerminalDirectoryIO({ + getSessionRemoteInfo: sessionId => api.getSessionRemoteInfo(null, { sessionId }), + getSessionPwd: (sessionId, options) => api.getSessionPwd(null, { sessionId, ...options }), + } as unknown as NetcattyBridge, id, { local: false, hostname: '127.0.0.1', username: 'fixture', port: address.port }); + const controller = createTerminalDirectoryController({ sessionId: id, io, + isCurrent: () => true, isReady: () => false, publish: cwd => { published = cwd; } }); + unregister = registerTerminalDirectory(id, controller); + stopObserving = observeTerminalDirectory(id); + channel.write(`cd -- '${first}'\r`); + await waitFor(() => published === fs.realpathSync(first)); + channel.write(`sleep 0.6; cd -- '${second}'\r`); + await waitFor(() => published === fs.realpathSync(second)); + assert.ok(execs >= 2, 'production strict cwd queries used SSH exec channels'); +}); diff --git a/infrastructure/services/terminalDirectory.test.ts b/infrastructure/services/terminalDirectory.test.ts new file mode 100644 index 000000000..f07daa7f3 --- /dev/null +++ b/infrastructure/services/terminalDirectory.test.ts @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createTerminalDirectoryIO } from './terminalDirectory'; + +test('remote reads use only the exact terminal connection and always close their channel', async () => { + const calls: unknown[] = []; + const bridge = { + getSessionRemoteInfo: async () => ({ success: true, remoteSshVersion: 'OpenSSH_9.6' }), + openSftpForSession: async (id: string, opts: NetcattySSHOptions) => { calls.push([id, opts]); return 'owned-channel'; }, + listSftp: async () => { throw new Error('denied'); }, + closeSftp: async (id: string) => { calls.push(['close', id]); }, + } as unknown as NetcattyBridge; + const io = createTerminalDirectoryIO(bridge, 'terminal-a', { local: false, hostname: 'remote', username: 'me', port: 2222 }); + await assert.rejects(io.list('/project'), /denied/); + assert.deepEqual(calls, [['terminal-a', { hostname: 'remote', username: 'me', port: 2222, requireExactSourceSession: true, reuseExactSessionOnly: true, fileProtocol: 'sftp' }], ['close', 'owned-channel']]); +}); + +test('cwd probes forbid home/login-shell fallbacks, and writes are addressed to one session', async () => { + const calls: unknown[] = []; + const bridge = { + getSessionPwd: async (id: string, opts: unknown) => { calls.push([id, opts]); return { success: true, cwd: '/actual' }; }, + writeToSession: (...args: unknown[]) => { calls.push(args); }, + } as unknown as NetcattyBridge; + const io = createTerminalDirectoryIO(bridge, 'terminal-a', { local: true, hostname: '', username: '' }); + assert.equal(await io.cwd(), '/actual'); + io.write("cd -- '/actual'\r"); + assert.deepEqual(calls, [ + ['terminal-a', { allowHomeFallback: false, allowLoginShellFallback: false, timeoutMs: 2000 }], + ['terminal-a', "cd -- '/actual'\r", { automated: true }], + ]); +}); + +test('network-device SSH banners refuse probes before opening exec or SFTP', async () => { + let probes = 0; + const io = createTerminalDirectoryIO({ + getSessionRemoteInfo: async () => ({ success: true, remoteSshVersion: '-' }), + getSessionPwd: async () => { probes++; return { success: true, cwd: '/wrong' }; }, + } as unknown as NetcattyBridge, 'router', { local: false, hostname: 'router', username: 'me' }); + await assert.rejects(io.cwd(), { code: 'unavailable' }); + assert.equal(probes, 0); +}); + +test('single-channel sessions never invoke dedicated-login SFTP fallback', async () => { + let opened = false; + const io = createTerminalDirectoryIO({ + getSessionRemoteInfo: async () => ({ success: true, singleChannelSsh: true, remoteSshVersion: 'OpenSSH_9.6' }), + openSftpForSession: async () => { opened = true; return 'unexpected'; }, + } as unknown as NetcattyBridge, 'limited', { local: false, hostname: 'limited', username: 'me' }); + await assert.rejects(io.list('/project'), { code: 'unavailable' }); + assert.equal(opened, false); +}); + +test('a connection invalidated while metadata is loading does not open another channel', async () => { + let finish!: (value: { success: boolean; remoteSshVersion: string }) => void; + let current = true; let opened = false; + const io = createTerminalDirectoryIO({ + getSessionRemoteInfo: () => new Promise(resolve => { finish = resolve; }), + openSftpForSession: async () => { opened = true; return 'unexpected'; }, + } as unknown as NetcattyBridge, 'old', { local: false, hostname: 'remote', username: 'me' }, () => current); + const read = io.list('/project'); current = false; + finish({ success: true, remoteSshVersion: 'OpenSSH_9.6' }); + await assert.rejects(read, { code: 'unavailable' }); + assert.equal(opened, false); +}); + +test('closing a picker during channel open closes the handle without listing', async () => { + let finish!: (id: string) => void; + let listed = false; let closed = false; + const io = createTerminalDirectoryIO({ + getSessionRemoteInfo: async () => ({ success: true, remoteSshVersion: 'OpenSSH_9.6' }), + openSftpForSession: () => new Promise(resolve => { finish = resolve; }), + listSftp: async () => { listed = true; return []; }, + closeSftp: async () => { closed = true; }, + } as unknown as NetcattyBridge, 'remote', { local: false, hostname: 'remote', username: 'me' }); + const cancel = new AbortController(); + const task = io.list('/project', cancel.signal); + await Promise.resolve(); await Promise.resolve(); + cancel.abort(); finish('temporary-channel'); + await assert.rejects(task, { code: 'unavailable' }); + assert.equal(listed, false); assert.equal(closed, true); +}); diff --git a/infrastructure/services/terminalDirectory.ts b/infrastructure/services/terminalDirectory.ts new file mode 100644 index 000000000..87b7d9f98 --- /dev/null +++ b/infrastructure/services/terminalDirectory.ts @@ -0,0 +1,69 @@ +import { DirectoryPickerError, directoryEntries, isDirectoryPath } from '../../domain/directoryPicker'; +import { shouldProbeSessionCwd } from '../../domain/host'; + +export interface TerminalDirectoryIO { + cwd(): Promise; + home?(): Promise; + list(path: string, signal?: AbortSignal): Promise<{ entries: ReturnType; home: string | null }>; + realpath(path: string, signal?: AbortSignal): Promise; + write(data: string): void; +} + +/** Uses the exact authenticated terminal transport; never dials another host. */ +export function createTerminalDirectoryIO(bridge: NetcattyBridge, sessionId: string, + endpoint: { local: boolean; hostname: string; username: string; port?: number; encoding?: import('../../types').SftpFilenameEncoding }, + isCurrent: () => boolean = () => true, +): TerminalDirectoryIO { + const check = (signal?: AbortSignal) => { if (!isCurrent() || signal?.aborted) throw new DirectoryPickerError('unavailable'); }; + async function checkRemote(signal?: AbortSignal) { + check(signal); + const info = await bridge.getSessionRemoteInfo?.(sessionId); + check(signal); + if (!info?.success || info.singleChannelSsh || !shouldProbeSessionCwd({ isNetworkDevice: false, remoteSshVersion: info.remoteSshVersion })) { + throw new DirectoryPickerError('unavailable'); + } + } + async function withSftp(run: (id: string) => Promise, signal?: AbortSignal): Promise { + await checkRemote(signal); + if (!bridge.openSftpForSession) throw new DirectoryPickerError('unavailable'); + const id = await bridge.openSftpForSession(sessionId, { + hostname: endpoint.hostname, username: endpoint.username, port: endpoint.port, + requireExactSourceSession: true, reuseExactSessionOnly: true, fileProtocol: 'sftp', + }); + try { check(signal); return await run(id); } + finally { await bridge.closeSftp(id).catch(() => {}); } + } + return { + async home() { check(); return endpoint.local ? await bridge.getHomeDir?.().catch(() => null) ?? null : null; }, + async cwd() { + check(); + if (!endpoint.local) await checkRemote(); + const result = await bridge.getSessionPwd?.(sessionId, { + allowHomeFallback: false, allowLoginShellFallback: false, timeoutMs: 2000, + }); + if (!result?.success || !isDirectoryPath(result.cwd)) throw new DirectoryPickerError('unknown'); + return result.cwd; + }, + async list(path, signal) { + check(signal); + if (!isDirectoryPath(path)) throw new DirectoryPickerError('unsupportedPath'); + if (endpoint.local) { + const files = await bridge.listLocalDir(path); + check(signal); + const home = await bridge.getHomeDir?.().catch(() => null) ?? null; + return { entries: directoryEntries(path, files), home }; + } + return withSftp(async id => { + const files = await bridge.listSftp(id, path, endpoint.encoding); + // SFTP's login directory may be a chroot root, so do not guess remote HOME. + return { entries: directoryEntries(path, files), home: null }; + }, signal); + }, + async realpath(path, signal) { + check(signal); + return endpoint.local ? await bridge.realpathLocal?.(path) ?? path + : withSftp(async id => await bridge.realpathSftp?.(id, path, endpoint.encoding) ?? path, signal); + }, + write(data) { check(); bridge.writeToSession(sessionId, data, { automated: true }); }, + }; +} diff --git a/types/global/netcatty-bridge-session.d.ts b/types/global/netcatty-bridge-session.d.ts index 3f7ef547f..85ac9b548 100644 --- a/types/global/netcatty-bridge-session.d.ts +++ b/types/global/netcatty-bridge-session.d.ts @@ -261,6 +261,7 @@ declare global { getSessionRemoteInfo?(sessionId: string): Promise<{ success: boolean; remoteSshVersion?: string; + singleChannelSsh?: boolean; error?: string; }>; /**