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:
陈大猫andJoseph Hau authored and GitHub committed 2026-11-05 23:44:37 +08:00
1 parent 2e3dc687cb
commit efe012e0c8
45 files changed
+2064 -9

No files matched your search

+15
View File
@@ -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<TerminalProps> = ({
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<TerminalProps> = ({
const cwdAwareOnCommandSubmitted = useCallback((
...args: Parameters<NonNullable<typeof onCommandSubmitted>>
) => {
scheduleObservedTerminalDirectoryRefresh(sessionId);
if (!shouldPreserveTerminalCwdAcrossCommand(hostRestrictsExtraSshChannels(host))) {
invalidateTerminalCwdAfterCommand(
terminalCwdTracker,
@@ -2603,6 +2608,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}, [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<TerminalProps> = ({
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<TerminalProps> = ({
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<TerminalProps> = ({
onTerminalDataCapture: handleTerminalDataCaptureOnce,
onTerminalOutput: (chunk: string, meta?: TerminalSessionDataMeta) => {
observeTerminalInputPrompt(chunk, meta);
scheduleObservedTerminalDirectoryRefresh(sessionId);
appendOutputTriggerOutputRef.current(chunk, meta);
if (onTerminalOutput) {
onTerminalOutput(sessionId, chunk);
@@ -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/);
@@ -48,6 +48,14 @@ export const TerminalBehaviorSettings: React.FC<TerminalBehaviorSettingsProps> =
<>
<SectionHeader title={t("settings.terminal.section.behavior")} />
<div className="space-y-0 divide-y divide-border rounded-lg border bg-card px-4">
<SettingRow
anchorId="terminal-context-chips"
label={t("settings.terminal.behavior.contextChips")}
description={t("settings.terminal.behavior.contextChips.desc")}
>
<Toggle checked={terminalSettings.contextChipsEnabled !== false} onChange={(v) => updateTerminalSetting("contextChipsEnabled", v)} />
</SettingRow>
<SettingRow
anchorId="terminal-auto-close-on-exit"
label={t("settings.terminal.behavior.autoCloseOnExit")}
@@ -0,0 +1,129 @@
import { ArrowUp, ChevronDown, Folder, LoaderCircle, RefreshCw } from 'lucide-react';
import { useEffect, useId, useRef, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useComposeDirectoryPicker } from '../../application/state/useComposeDirectoryPicker';
import { directoryDisplayName, directoryLabel } from '../../domain/directoryPicker';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import type { ComposeBarTheme } from './TerminalComposeBar';
export function ComposeDirectoryPicker({ sessionId, theme, onReturnFocus }: {
sessionId: string; theme: ComposeBarTheme; onReturnFocus: () => void;
}) {
const { t } = useI18n();
const model = useComposeDirectoryPicker(sessionId);
const [active, setActive] = useState(0);
const [scrollTop, setScrollTop] = useState(0);
const search = useRef<HTMLInputElement>(null);
const viewport = useRef<HTMLDivElement>(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) => (
<div
key={path} id={`${id}-${index}`} role="option" aria-selected={active === index}
title={directoryDisplayName(path)}
className="h-8 flex items-center gap-2 px-3 text-xs cursor-pointer min-w-0"
style={{ backgroundColor: active === index ? theme.chipHoverBg : undefined,
color: active === index ? theme.resolvedFg : theme.mutedFg }}
onPointerMove={() => setActive(index)}
onMouseDown={event => event.preventDefault()}
onClick={() => { if (!model.pending) void model.change(path); }}
>
{parent ? <ArrowUp size={13} className="shrink-0" /> : <Folder size={13} className="shrink-0" />}
<span className="truncate">{directoryDisplayName(name)}</span>
</div>
);
return (
<div className="shrink-0 flex items-center gap-2 px-3 h-7 min-w-0" role="group" aria-label="Context Chips">
<Popover open={model.open} onOpenChange={value => { if (value) outside.current = false; model.setOpen(value); }}>
<PopoverTrigger asChild>
<button type="button" disabled={model.pending}
aria-label={t('terminal.directory.open', { path: model.cwd ? directoryLabel(model.cwd, model.home) : t('terminal.directory.unknown') })}
title={model.cwd ? directoryDisplayName(model.cwd) : t('terminal.directory.unknown')}
className="h-6 min-w-0 max-w-full flex items-center gap-1.5 rounded border px-2 text-[11px] font-mono focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-60"
style={{ backgroundColor: theme.chipBg, borderColor: theme.borderColor, color: theme.resolvedFg }}
>
{model.pending ? <LoaderCircle size={12} className="shrink-0 animate-spin" /> : <Folder size={12} className="shrink-0" />}
<span className="truncate">{model.cwd ? directoryDisplayName(directoryLabel(model.cwd, model.home)) : t('terminal.directory.unknown')}</span>
<ChevronDown size={10} className="shrink-0 opacity-60" />
</button>
</PopoverTrigger>
<PopoverContent side="top" align="start" sideOffset={6}
className="p-0 overflow-hidden w-[360px] max-w-[calc(100vw-16px)]"
style={{ backgroundColor: theme.resolvedBg, borderColor: theme.borderColor, color: theme.resolvedFg }}
onOpenAutoFocus={event => { 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);
}
}}
>
<div className="px-3 py-2 border-b" style={{ borderColor: theme.borderColor }}>
<input ref={search} value={model.query} onChange={event => 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; }}
/>
</div>
<div role="listbox" aria-label={t('terminal.directory.directories')} id={`${id}-list`} aria-busy={model.loading}>
{model.parent && row(t('terminal.directory.parent'), model.parent, 0, true)}
<div ref={viewport} className="max-h-56 overflow-y-auto overscroll-contain" onScroll={event => setScrollTop(event.currentTarget.scrollTop)}>
<div style={virtual ? { height: model.entries.length * 32, position: 'relative' } : undefined}>
<div style={virtual ? { position: 'absolute', top: start * 32, left: 0, right: 0 } : undefined}>
{visible.map((entry, index) => row(entry.name, entry.path, start + index + Number(hasParent)))}
</div>
</div>
{model.loading && <p className="px-3 py-4 text-xs" role="status">{t('terminal.directory.loading')}</p>}
{!model.loading && !errorText && model.cwd && !model.entries.length && (
<p className="px-3 py-4 text-xs" style={{ color: theme.mutedFg }}>{t(model.query ? 'terminal.directory.noMatches' : 'terminal.directory.empty')}</p>
)}
</div>
</div>
{(errorText || !model.available || !model.cwd) && <p className="px-3 py-2 text-xs" role="status">
{errorText ?? t(model.available ? 'terminal.directory.unknown' : 'terminal.directory.unavailable')}
</p>}
<div className="flex items-center justify-between border-t px-3 py-2 text-[11px]" style={{ borderColor: theme.borderColor, color: theme.mutedFg }}>
<label className="flex items-center gap-2"><input type="checkbox" checked={model.showHidden} onChange={event => model.setShowHidden(event.target.checked)} />{t('terminal.directory.hidden')}</label>
<button type="button" disabled={model.loading || model.pending || !model.available}
className="inline-flex items-center gap-1 rounded px-1 disabled:opacity-50"
onClick={() => { if (model.cwd) void model.reload(); else void model.refresh(); }}>
<RefreshCw size={11} />{t('terminal.directory.refresh')}
</button>
</div>
</PopoverContent>
</Popover>
{!model.open && errorText && <span role="status" title={errorText} className="truncate text-[10px]" style={{ color: theme.mutedFg }}>{errorText}</span>}
</div>
);
}
@@ -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('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
const originals = new Map<string, PropertyDescriptor | undefined>();
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) => <TooltipProvider><TerminalComposeBar sessionId="toggle-test"
contextChipsEnabled={enabled} onSend={() => true} onClose={() => {}} /></TooltipProvider>;
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('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
+7 -1
View File
@@ -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<boolean | void>;
sessionId: string;
@@ -291,6 +293,7 @@ export interface TerminalComposeBarProps {
export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
onSend,
contextChipsEnabled = true,
sessionId,
onClose,
onSnippetClick,
@@ -611,6 +614,9 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
/>
</div>
{contextChipsEnabled && <ComposeDirectoryPicker key={sessionId} sessionId={sessionId} theme={theme}
onReturnFocus={() => textareaRef.current?.focus({ preventScroll: true })} />}
<div className="flex-1 min-h-0 px-3 pt-1.5 pb-2 flex flex-col">
<div className="flex flex-1 min-h-0 items-start gap-1.5">
{(onToggleComposeSendTarget || sendToAll) && (
+1
View File
@@ -1432,6 +1432,7 @@ function TerminalViewInner({ ctx, isPaneMagnified = false }: { ctx: TerminalView
{/* Compose Bar (solo sessions only; workspace uses TerminalLayer's global bar) */}
{isComposeBarOpen && !inWorkspace && (
<TerminalComposeBar
contextChipsEnabled={terminalSettings?.contextChipsEnabled !== false}
key={sessionId}
sessionId={sessionId}
onSend={async (text) => {
@@ -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)
@@ -350,6 +350,7 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
{activeWorkspace && focusedSessionId && isComposeBarOpen && (
<TerminalComposeBar
sessionId={focusedSessionId}
contextChipsEnabled={terminalSettings?.contextChipsEnabled !== false}
onSend={handleComposeSend}
onSnippetClick={(snippet) => void handleSnippetFromPanel(snippet)}
snippets={snippets}