mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-21 07:32:54 +00:00
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 <hexart@gmail.com>
This commit is contained in:
1 parent
2e3dc687cb
commit
efe012e0c8
45 files changed
+2064
-9
No files matched your search
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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': 'Журнал сессии',
|
||||
|
||||
@@ -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': '会话日志',
|
||||
|
||||
@@ -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': '工作階段日誌',
|
||||
|
||||
@@ -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());
|
||||
});
|
||||
@@ -10,11 +10,16 @@ export type TerminalCwdSource = "osc7" | "inferred" | "backend-strict" | "backen
|
||||
class TerminalCwdStore {
|
||||
private cwdBySession = new Map<string, string>();
|
||||
private sourceBySession = new Map<string, TerminalCwdSource>();
|
||||
private revisionBySession = new Map<string, number>();
|
||||
private revision = 0;
|
||||
private version = 0;
|
||||
private listeners = new Set<Listener>();
|
||||
|
||||
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) {
|
||||
|
||||
@@ -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<TerminalDirectoryIO> = {}) {
|
||||
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' });
|
||||
});
|
||||
}
|
||||
@@ -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<typeof createTerminalDirectoryController>;
|
||||
|
||||
/** 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<string> | 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<T>(task: Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||
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<string> {
|
||||
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<void>(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(); },
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { TerminalDirectoryController } from './terminalDirectoryController';
|
||||
|
||||
const sessions = new Map<string, TerminalDirectoryController>();
|
||||
const consumers = new Map<string, number>();
|
||||
const scheduledRefreshes = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
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));
|
||||
}
|
||||
@@ -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 };
|
||||
|
||||
@@ -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<typeof useComposeDirectoryPicker>;
|
||||
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<typeof useComposeDirectoryPicker>;
|
||||
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<typeof useComposeDirectoryPicker>;
|
||||
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']);
|
||||
});
|
||||
@@ -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<DirectoryEntry[]>([]);
|
||||
const [home, setHome] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
const listingBase = useRef<string | null>(null);
|
||||
const [error, setError] = useState<DirectoryPickerErrorCode | null>(null);
|
||||
const generation = useRef(0);
|
||||
const lifetime = useRef(new AbortController());
|
||||
const read = useRef<AbortController | null>(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 };
|
||||
}
|
||||
@@ -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<typeof useTerminalDirectorySession>[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<typeof useComposeDirectoryPicker>;
|
||||
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(); });
|
||||
});
|
||||
@@ -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]);
|
||||
}
|
||||
Reference in new issue
Block a user