Compare commits

...
15 changed files with 716 additions and 28 deletions

No files matched your search

+2
View File
@@ -994,6 +994,8 @@ export const enVaultMessages: Messages = {
'localShell.field.shellResolved': 'Runs {command}',
'localShell.field.startDir': 'Start directory',
'localShell.field.startDirPlaceholder': 'Inherit global start directory (home if unset)',
'localShell.field.startupCommandPlaceholder': 'Command to run after shell starts (e.g. npm run dev)',
'localShell.field.startupCommandDesc': 'Runs automatically after the local shell starts in the configured directory.',
'localShell.saveAndConnect': 'Save & Connect',
'hostDetails.plugin.title': 'Plugin connection',
+2
View File
@@ -996,6 +996,8 @@ export const esVaultMessages: Messages = {
'localShell.field.shellResolved': 'Ejecuta {command}',
'localShell.field.startDir': 'Directorio de inicio',
'localShell.field.startDirPlaceholder': 'Heredar directorio inicial global (personal si no se configura)',
'localShell.field.startupCommandPlaceholder': 'Comando para ejecutar al iniciar la shell (p. ej., npm run dev)',
'localShell.field.startupCommandDesc': 'Se ejecuta automáticamente cuando la shell local inicia en el directorio configurado.',
'localShell.saveAndConnect': 'Guardar y conectar',
'hostDetails.plugin.title': 'Conexión de plugin',
+2
View File
@@ -1032,6 +1032,8 @@ export const ruVaultMessages: Messages = {
'localShell.field.shellResolved': 'Запускает {command}',
'localShell.field.startDir': 'Начальный каталог',
'localShell.field.startDirPlaceholder': 'Использовать общий начальный каталог (иначе домашний)',
'localShell.field.startupCommandPlaceholder': 'Команда после запуска оболочки (например, npm run dev)',
'localShell.field.startupCommandDesc': 'Выполняется автоматически после запуска локальной оболочки в указанном каталоге.',
'localShell.saveAndConnect': 'Сохранить и открыть',
'hostDetails.plugin.title': 'Подключение плагина',
+2
View File
@@ -408,6 +408,8 @@ export const zhCNVaultMessages: Messages = {
'localShell.field.shellResolved': '启动 {command}',
'localShell.field.startDir': '启动目录',
'localShell.field.startDirPlaceholder': '继承全局起始目录(未设置时为主目录)',
'localShell.field.startupCommandPlaceholder': 'Shell 启动后执行的命令(例如:npm run dev)',
'localShell.field.startupCommandDesc': '本地 Shell 在启动目录打开后自动执行该命令。',
'localShell.saveAndConnect': '保存并打开',
'hostDetails.plugin.title': '插件连接',
+2
View File
@@ -408,6 +408,8 @@ export const zhTWVaultMessages: Messages = {
'localShell.field.shellResolved': '啟動 {command}',
'localShell.field.startDir': '啟動目錄',
'localShell.field.startDirPlaceholder': '繼承全域起始目錄(未設定時為主目錄)',
'localShell.field.startupCommandPlaceholder': 'Shell 啟動後執行的指令(例如:npm run dev)',
'localShell.field.startupCommandDesc': '本地 Shell 在啟動目錄開啟後自動執行該指令。',
'localShell.saveAndConnect': '儲存並開啟',
'hostDetails.plugin.title': '外掛程式連線',
+17 -3
View File
@@ -25,11 +25,13 @@ const existingLocalHost = {
localShell: "powershell",
localShellName: "Windows PowerShell",
localShellIcon: "powershell",
localStartDir: "/workspace/project-a",
startupCommand: "npm run dev",
} as unknown as Host;
const noop = () => {};
test("renderToStaticMarkup: create mode shows title, default-shell option and Save & Connect", () => {
test("renderToStaticMarkup: create mode shows title, default-shell option, startup command field and Save & Connect", () => {
const markup = renderToStaticMarkup(
<LocalShellHostDetailsPanel
defaultGroup="Projects/A"
@@ -45,9 +47,15 @@ test("renderToStaticMarkup: create mode shows title, default-shell option and Sa
assert.match(markup, /localShell\.field\.shellDefault/);
assert.match(markup, /localShell\.saveAndConnect/);
assert.match(markup, /localShell\.saveAndConnect|common\.save/);
assert.match(markup, /hostDetails\.startupCommand/);
assert.match(markup, /localShell\.field\.startupCommandPlaceholder/);
assert.match(markup, /localShell\.field\.startupCommandDesc/);
const startDirIdx = markup.indexOf("local-shell-start-dir");
const startupCmdIdx = markup.indexOf("local-shell-startup-command");
assert.ok(startDirIdx >= 0 && startupCmdIdx > startDirIdx, "startup command field must render below start directory");
});
test("renderToStaticMarkup: edit mode hides Save & Connect and shows existing shell", () => {
test("renderToStaticMarkup: edit mode hides Save & Connect and shows existing shell and startup command", () => {
const markup = renderToStaticMarkup(
<LocalShellHostDetailsPanel
initialData={existingLocalHost}
@@ -60,9 +68,15 @@ test("renderToStaticMarkup: edit mode hides Save & Connect and shows existing sh
assert.match(markup, /localShell\.panel\.title\.edit/);
assert.doesNotMatch(markup, /localShell\.saveAndConnect/);
// Existing label is carried into the form
// Existing label, start directory, and startup command are carried into the form
assert.match(markup, /Project A CMD/);
assert.match(markup, /local-shell-start-dir/);
assert.match(markup, /local-shell-startup-command/);
assert.match(markup, /npm run dev/);
});
test("buildHost forwards startupCommand to createLocalShellHost", () => {
assert.match(panelSource, /startDir,\s*\n\s*startupCommand,/);
});
test("buildHost preserves the saved OS on edits and detects it only for new entries", () => {
+21
View File
@@ -16,6 +16,7 @@ import { Button } from './ui/button';
import { Combobox, ComboboxOption } from './ui/combobox';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Textarea } from './ui/textarea';
import {
AsidePanel,
AsidePanelContent,
@@ -60,6 +61,7 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
const [label, setLabel] = useState(initialData?.label ?? '');
const [shell, setShell] = useState(initialData?.localShell ?? '');
const [startDir, setStartDir] = useState(initialData?.localStartDir ?? '');
const [startupCommand, setStartupCommand] = useState(initialData?.startupCommand ?? '');
// On creation, initialize from defaultGroup so the field reflects what a
// plain save would persist; clearing it then intentionally saves at the
// vault root. Edits keep the host's own group (possibly empty).
@@ -125,6 +127,7 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
shellName: shellMeta?.name,
shellIcon: shellMeta?.icon,
startDir,
startupCommand,
// Save the controlled value directly: '' means the user explicitly
// cleared the group, which persists at the vault root.
group: group,
@@ -226,6 +229,24 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
)}
</div>
</div>
{/* Startup command */}
<div className="space-y-2">
<Label htmlFor="local-shell-startup-command">
{t('hostDetails.startupCommand')}
</Label>
<Textarea
id="local-shell-startup-command"
value={startupCommand}
onChange={(e) => setStartupCommand(e.target.value)}
placeholder={t('localShell.field.startupCommandPlaceholder')}
className="min-h-[80px] font-mono text-sm"
rows={3}
/>
<p className="text-xs text-muted-foreground">
{t('localShell.field.startupCommandDesc')}
</p>
</div>
</AsidePanelContent>
<AsidePanelFooter>
@@ -109,3 +109,40 @@ test("local shell save: duplicated host with a new id saves as a new entry", ()
assert.equal(saved[0].notes, "tweaked");
assert.equal(connected, undefined);
});
test("local shell save: persists, edits, and clears startupCommand cleanly", () => {
const opened = createLocalShellHost({
id: "local-cmd-1",
label: "Dev Shell",
startDir: "/workspace/app",
startupCommand: "npm run dev",
});
let saved: Host[] = [opened];
const hostsRef: { current: Host[] } = { current: [opened] };
const runSave = (editingHost: Host, draft: Host) => {
const save = new Function(
"hosts", "editingLocalShellHost", "onUpdateHosts", "onConnect",
"setIsLocalShellHostPanelOpen", "setEditingLocalShellHost",
"upsertHostById", "saveWorkSurfaceHostDraft",
`${compiled} return save;`,
)(
hostsRef.current, editingHost,
(data: Host[] | ((prev: Host[]) => Host[])) => {
const next = typeof data === "function" ? data(hostsRef.current) : data;
if (next) hostsRef.current = next;
saved = next ?? hostsRef.current;
},
() => {}, () => {}, () => {}, upsertHostById, saveWorkSurfaceHostDraft,
);
save(draft, false);
};
const edited = { ...opened, ...createLocalShellHost({ id: opened.id, label: opened.label, startDir: opened.localStartDir, startupCommand: "pnpm test" }), createdAt: opened.createdAt };
runSave(opened, edited);
assert.equal(saved[0].startupCommand, "pnpm test");
const cleared = { ...edited, ...createLocalShellHost({ id: opened.id, label: opened.label, startDir: opened.localStartDir, startupCommand: " " }), createdAt: opened.createdAt };
runSave(edited, cleared);
assert.equal(saved[0].startupCommand, undefined);
});
@@ -0,0 +1,436 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import * as pty from "node-pty";
import type { Host, TerminalSession } from "../../../domain/models";
import { createLocalShellHost } from "../../../domain/localShellHost";
import { resolveTerminalSessionHost } from "../../../domain/terminalHostResolution";
import { shouldSuppressHostStartupCommandOnReconnect } from "../restoredSessionGate";
import { createTerminalSessionStarters } from "./createTerminalSessionStarters";
import { createMockTerminalBackend, createStarterContext, createTermStub } from "./testSupport/starterHarness";
const noop = () => {};
test("local session skips empty and whitespace-only host startup commands", async () => {
for (const startupCommand of ["", " ", "\n\t \r\n"]) {
const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = [];
const terminalBackend = createMockTerminalBackend({
writeToSession: (id: string, data: string, options?: { automated?: boolean }) => {
sessionWrites.push({ id, data, automated: options?.automated });
},
});
const ctx = createStarterContext({
host: {
id: "local-host",
label: "Local",
hostname: "localhost",
username: "",
protocol: "local",
startupCommand,
},
terminalSettings: { startupCommandDelayMs: 0 },
terminalBackend,
startupCommand: undefined,
promptLineBreakStateRef: undefined,
});
await createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never);
await new Promise((resolve) => setTimeout(resolve, 10));
assert.deepEqual(sessionWrites, [], `expected no writes for ${JSON.stringify(startupCommand)}`);
}
});
test("local session cancels pending host startup command if shell exits before delay elapses", async () => {
const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = [];
let triggerExit: ((evt: { exitCode?: number }) => void) | undefined;
const terminalBackend = createMockTerminalBackend({
onSessionExit: (_id: string, cb: (evt: { exitCode?: number }) => void) => {
triggerExit = cb;
return noop;
},
writeToSession: (id: string, data: string, options?: { automated?: boolean }) => {
sessionWrites.push({ id, data, automated: options?.automated });
},
});
const ctx = createStarterContext({
host: {
id: "local-host",
label: "Local",
hostname: "localhost",
username: "",
protocol: "local",
startupCommand: "echo should-not-run",
},
terminalSettings: { startupCommandDelayMs: 30 },
terminalBackend,
startupCommand: undefined,
promptLineBreakStateRef: undefined,
});
await createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never);
triggerExit?.({ exitCode: 1 });
await new Promise((resolve) => setTimeout(resolve, 60));
assert.deepEqual(sessionWrites, []);
});
test("local session cancels pending host startup command when boot signal aborts before delay elapses", async () => {
const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = [];
const terminalBackend = createMockTerminalBackend({
writeToSession: (id: string, data: string, options?: { automated?: boolean }) => {
sessionWrites.push({ id, data, automated: options?.automated });
},
});
const controller = new AbortController();
const ctx = createStarterContext({
host: {
id: "local-host",
label: "Local",
hostname: "localhost",
username: "",
protocol: "local",
startupCommand: "echo aborted",
},
terminalSettings: { startupCommandDelayMs: 30 },
terminalBackend,
startupCommand: undefined,
promptLineBreakStateRef: undefined,
});
await createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never, {
signal: controller.signal,
});
controller.abort();
await new Promise((resolve) => setTimeout(resolve, 60));
assert.deepEqual(sessionWrites, []);
});
test("local session normalizes CRLF multi-line startup commands for paste and lineDelay modes", async () => {
for (const mode of ["paste", "lineDelay"] as const) {
const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = [];
const terminalBackend = createMockTerminalBackend({
writeToSession: (id: string, data: string, options?: { automated?: boolean }) => {
sessionWrites.push({ id, data, automated: options?.automated });
},
});
const ctx = createStarterContext({
host: {
id: "local-win",
label: "PowerShell",
hostname: "localhost",
username: "",
protocol: "local",
localShell: "powershell.exe",
startupCommand: "cd C:\\work\r\nnpm run dev",
startupCommandRunMode: mode,
},
terminalSettings: { startupCommandDelayMs: 0 },
terminalBackend,
startupCommand: undefined,
promptLineBreakStateRef: undefined,
});
await createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never);
await new Promise((resolve) => setTimeout(resolve, 15));
if (mode === "paste") {
assert.deepEqual(sessionWrites, [{
id: "local-session",
data: "cd C:\\work\nnpm run dev\r",
automated: true,
}]);
} else {
assert.deepEqual(sessionWrites, [
{ id: "local-session", data: "cd C:\\work\r", automated: true },
{ id: "local-session", data: "npm run dev\r", automated: true },
]);
}
}
});
test("restored local attach runs hydrated live host startup command only when launch target matches", async () => {
const bootHost = {
id: "local-restored",
label: "Project Shell",
hostname: "localhost",
username: "local",
protocol: "local" as const,
localShell: "/bin/zsh",
localStartDir: "/tmp/project",
};
// Matching hydrated vault host runs its startup command.
{
const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = [];
const hostRef: { current: Partial<Host> } = { current: bootHost };
let releaseStart: (() => void) | undefined;
const startGate = new Promise<void>((resolve) => { releaseStart = resolve; });
const terminalBackend = createMockTerminalBackend({
startLocalSession: async () => {
await startGate;
return "local-session";
},
writeToSession: (id: string, data: string, options?: { automated?: boolean }) => {
sessionWrites.push({ id, data, automated: options?.automated });
},
});
const ctx = createStarterContext({
host: bootHost,
hostRef,
terminalSettings: { startupCommandDelayMs: 0 },
terminalBackend,
startupCommand: undefined,
suppressHostStartupCommandRef: {
current: shouldSuppressHostStartupCommandOnReconnect("restored"),
},
promptLineBreakStateRef: undefined,
});
const started = createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never);
hostRef.current = { ...bootHost, startupCommand: "echo restored-local" };
releaseStart?.();
await started;
await new Promise((resolve) => setTimeout(resolve, 10));
assert.deepEqual(sessionWrites, [
{ id: "local-session", data: "echo restored-local\r", automated: true },
]);
}
// Mismatched shell/startDir/protocol keeps snapshot and skips the unrelated command.
const mismatchCases: Array<[string, Partial<Host>]> = [
["localShell", { localShell: "/bin/bash" }],
["localStartDir", { localStartDir: "/tmp/other" }],
["localShellArgs", { localShellArgs: ["-l"] }],
["protocol", { protocol: "ssh" }],
];
for (const [label, patch] of mismatchCases) {
const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = [];
const hostRef: { current: Partial<Host> } = { current: bootHost };
let releaseStart: (() => void) | undefined;
const startGate = new Promise<void>((resolve) => { releaseStart = resolve; });
const terminalBackend = createMockTerminalBackend({
startLocalSession: async () => {
await startGate;
return "local-session";
},
writeToSession: (id: string, data: string, options?: { automated?: boolean }) => {
sessionWrites.push({ id, data, automated: options?.automated });
},
});
const ctx = createStarterContext({
host: bootHost,
hostRef,
terminalSettings: { startupCommandDelayMs: 0 },
terminalBackend,
startupCommand: undefined,
suppressHostStartupCommandRef: {
current: shouldSuppressHostStartupCommandOnReconnect("restored"),
},
promptLineBreakStateRef: undefined,
});
const started = createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never);
hostRef.current = { ...bootHost, ...patch, startupCommand: "echo wrong-target" };
releaseStart?.();
await started;
await new Promise((resolve) => setTimeout(resolve, 10));
assert.deepEqual(sessionWrites, [], label);
}
});
test("restored local attach through resolveTerminalSessionHost rejects hydrated startup command when saved host changed shell or dir", async () => {
const restoredSession: TerminalSession = {
id: "sess-restored-local",
hostId: "local-restored-prod",
hostLabel: "Project Shell",
hostname: "localhost",
username: "local",
status: "connecting",
protocol: "local",
localShell: "/bin/zsh",
localShellArgs: [],
localStartDir: "/tmp/original-project",
};
const baseSavedHost: Host = createLocalShellHost({
id: "local-restored-prod",
label: "Project Shell",
os: "macos",
shell: "/bin/zsh",
startDir: "/tmp/original-project",
startupCommand: "echo hydrated-ok",
});
const runHydratedRestore = async (hydratedHost: Host) => {
const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = [];
// Before vault hydration, resolveTerminalSessionHost builds the fallback host from the session.
const preHydrationHost = resolveTerminalSessionHost({
session: restoredSession,
hosts: [],
groupConfigs: [],
proxyProfiles: [],
localOs: "macos",
});
const hostRef: { current: Host } = { current: preHydrationHost };
let releaseStart: (() => void) | undefined;
const startGate = new Promise<void>((resolve) => { releaseStart = resolve; });
const terminalBackend = createMockTerminalBackend({
startLocalSession: async () => {
await startGate;
return "local-session";
},
writeToSession: (id: string, data: string, options?: { automated?: boolean }) => {
sessionWrites.push({ id, data, automated: options?.automated });
},
});
const ctx = createStarterContext({
host: preHydrationHost,
hostRef,
terminalSettings: { startupCommandDelayMs: 0 },
terminalBackend,
startupCommand: undefined,
suppressHostStartupCommandRef: {
current: shouldSuppressHostStartupCommandOnReconnect("restored"),
},
promptLineBreakStateRef: undefined,
});
const started = createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never);
// Vault hydration resolves the saved host through production resolveTerminalSessionHost (with overlaySessionLocalShell).
hostRef.current = resolveTerminalSessionHost({
session: restoredSession,
hosts: [hydratedHost],
groupConfigs: [],
proxyProfiles: [],
localOs: "macos",
});
releaseStart?.();
await started;
await new Promise((resolve) => setTimeout(resolve, 10));
return sessionWrites;
};
assert.deepEqual(await runHydratedRestore(baseSavedHost), [
{ id: "local-session", data: "echo hydrated-ok\r", automated: true },
]);
const editedTargets: Array<[string, Host]> = [
["edited shell", { ...baseSavedHost, localShell: "/bin/bash", startupCommand: "echo wrong-shell" }],
["edited startDir", { ...baseSavedHost, localStartDir: "/tmp/edited-project", startupCommand: "echo wrong-dir" }],
["edited shellArgs", { ...baseSavedHost, localShellArgs: ["-l"], startupCommand: "echo wrong-args" }],
["edited protocol", { ...baseSavedHost, protocol: "ssh", hostname: "prod.example.test", username: "ops", startupCommand: "echo wrong-proto" }],
];
for (const [label, editedHost] of editedTargets) {
assert.deepEqual(
await runHydratedRestore(editedHost),
[],
`${label}: startup command from an edited host must not run in the old session`,
);
}
});
test("real local PTY smoke: executes single-line and multi-line startup commands in configured startup directory", {
timeout: 15000,
skip: process.platform === "win32" ? "POSIX /bin/sh smoke test" : false,
}, async () => {
const tempDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-local-startup-")));
const runRealLocalPtyScenario = async (startupCommand: string | undefined, expectedMarker?: string) => {
const host = createLocalShellHost({
label: "Smoke Local",
shell: "/bin/sh",
startDir: tempDir,
startupCommand,
});
let proc: pty.IPty | null = null;
let output = "";
const dataListeners = new Set<(chunk: string) => void>();
const exitListeners = new Set<(evt: { exitCode?: number }) => void>();
const writes: string[] = [];
const terminalBackend = createMockTerminalBackend({
startLocalSession: async (options: { shell?: string; shellArgs?: string[]; cwd?: string; cols?: number; rows?: number }) => {
proc = pty.spawn(options.shell || "/bin/sh", options.shellArgs ?? [], {
name: "xterm-256color",
cols: options.cols || 80,
rows: options.rows || 24,
cwd: options.cwd,
env: {
...process.env,
PS1: "__NC_PROMPT__$ ",
TERM: "xterm-256color",
},
});
proc.onData((chunk) => {
output += chunk;
for (const listener of dataListeners) listener(chunk);
});
proc.onExit((evt) => {
for (const listener of exitListeners) listener(evt);
});
return "real-local-pty";
},
onSessionData: (_id: string, cb: (chunk: string) => void) => {
dataListeners.add(cb);
return () => dataListeners.delete(cb);
},
onSessionExit: (_id: string, cb: (evt: { exitCode?: number }) => void) => {
exitListeners.add(cb);
return () => exitListeners.delete(cb);
},
writeToSession: (_id: string, data: string) => {
writes.push(data);
proc?.write(data);
},
});
const ctx = createStarterContext({
host,
terminalSettings: { startupCommandDelayMs: 120 },
terminalBackend,
startupCommand: undefined,
promptLineBreakStateRef: undefined,
});
try {
await createTerminalSessionStarters(ctx as never).startLocal(createTermStub() as never);
if (expectedMarker) {
const deadline = Date.now() + 8000;
while (!output.includes(expectedMarker) && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 40));
}
assert.ok(
output.includes(expectedMarker),
`Expected PTY output to contain ${JSON.stringify(expectedMarker)}, got:\n${output}`,
);
} else {
await new Promise((resolve) => setTimeout(resolve, 300));
assert.deepEqual(writes, []);
}
} finally {
try { proc?.kill(); } catch { /* ignore */ }
}
};
try {
await runRealLocalPtyScenario(
'printf "__SINGLE_OK__:%s__\\n" "$(pwd -P)"',
`__SINGLE_OK__:${tempDir}__`,
);
await runRealLocalPtyScenario(
'TAG=netcatty4273\nprintf "__MULTI_OK__:%s:%s__\\n" "$TAG" "$(pwd -P)"',
`__MULTI_OK__:netcatty4273:${tempDir}__`,
);
await runRealLocalPtyScenario(" \n ");
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
@@ -1947,7 +1947,24 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
{ replayBacklog: true },
);
let localSessionExited = false;
let cancelPendingStartupCommand: (() => void) | undefined;
const isLocalConnectionCurrent = () =>
!localSessionExited
&& options?.signal?.aborted !== true
&& (ctx.bootEpochRef?.current ?? 0) === bootEpoch;
const handleAbortStartupCommand = () => {
cancelPendingStartupCommand?.();
cancelPendingStartupCommand = undefined;
};
const clearAbortStartupListener = () => {
options?.signal?.removeEventListener("abort", handleAbortStartupCommand);
};
ctx.disposeExitRef.current = ctx.terminalBackend.onSessionExit(id, async (evt) => {
localSessionExited = true;
handleAbortStartupCommand();
clearAbortStartupListener();
ctx.updateStatus("disconnected");
const exitMessage = `\r\n[session closed${evt?.exitCode !== undefined ? ` (code ${evt.exitCode})` : ""}]`;
writeTerminalLine(ctx, term, exitMessage);
@@ -1984,7 +2001,23 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
ctx.onSessionAttached?.(id);
consumeRestoreCwdIntent(term, id);
scheduleStartupCommand(ctx, term, id);
cancelPendingStartupCommand = scheduleStartupCommand(
ctx,
term,
id,
() => {
cancelPendingStartupCommand = undefined;
clearAbortStartupListener();
},
isLocalConnectionCurrent,
);
if (cancelPendingStartupCommand && options?.signal) {
if (options.signal.aborted) {
handleAbortStartupCommand();
} else {
options.signal.addEventListener("abort", handleAbortStartupCommand, { once: true });
}
}
} catch (err) {
if (ignoreStaleAttemptUi()) return;
const message = err instanceof Error ? err.message : String(err);
@@ -4,25 +4,23 @@ import { markPromptLineBreakCommandPending } from "./promptLineBreak";
import type { TerminalSessionStartersContext } from "./createTerminalSessionStarters.types";
/**
* Host startup is scheduled only after the shell attaches. Restored SSH panes
* boot from the session fallback first; vault hydration (including group
* defaults) replaces `hostRef` while that dial is still in flight. `startSSH`
* keeps dialing the boot snapshot (`ctx.host`). The startup command may come
* from the live host only when that object is still this dial: same id,
* hostname, username, and dial port (`port || 22`), and the same protocol
* when the live host sets one. A missing protocol is a legacy SSH host.
* A saved host edited onto another endpoint since the workspace was saved
* keeps the snapshot, so its command is not typed into the old session.
* Host startup is scheduled only after the shell attaches. Restored SSH and
* local panes boot from the session fallback first; vault hydration replaces
* `hostRef` while that start is still in flight. The startup command may come
* from the live host only when that object still describes this launch:
* - SSH: same id, hostname, username, dial port (`port || 22`), and protocol.
* - Local: same id, protocol `"local"`, shell, shell args, and start directory.
* A saved host edited onto another endpoint or shell since the workspace was
* saved keeps the snapshot, so its command is not typed into the old session.
*
* Serial preflight uses this same resolver to decide whether to wait for
* auto-login, then schedules again after the port opens. Non-SSH transports
* stay on the snapshot, so a command that appears on `hostRef` during the
* open is not typed into a saved username/password exchange.
* A ref that only carries a write-path toggle (no id) is not a host snapshot.
* A different host id is a later pane, not this dial, so keep the snapshot.
* Serial and Telnet preflight stay on the snapshot so a command that appears
* on `hostRef` during open is not typed into a saved username/password
* exchange. A ref that only carries a write-path toggle (no id) is not a host
* snapshot. A different host id is a later pane, not this launch, so keep the
* snapshot.
*/
const prefersLiveStartupHost = (protocol: string | undefined): boolean =>
protocol === "ssh" || protocol === undefined;
protocol === "ssh" || protocol === "local" || protocol === undefined;
const sshDialPort = (port: number | undefined): number => port || 22;
@@ -38,6 +36,30 @@ const sameSshDialTarget = (
return true;
};
const sameLocalShellArgs = (
left: string[] | undefined,
right: string[] | undefined,
): boolean => {
const normalizedLeft = left?.length ? left : undefined;
const normalizedRight = right?.length ? right : undefined;
if (!normalizedLeft && !normalizedRight) return true;
if (!normalizedLeft || !normalizedRight || normalizedLeft.length !== normalizedRight.length) {
return false;
}
return normalizedLeft.every((arg, index) => arg === normalizedRight[index]);
};
const sameLocalLaunchTarget = (
dial: TerminalSessionStartersContext["host"],
live: TerminalSessionStartersContext["host"],
): boolean => {
if (live.protocol !== "local") return false;
if ((live.localShell ?? "") !== (dial.localShell ?? "")) return false;
if (!sameLocalShellArgs(dial.localShellArgs, live.localShellArgs)) return false;
if ((live.localStartDir || "~") !== (dial.localStartDir || "~")) return false;
return true;
};
const resolveStartupHost = (
ctx: TerminalSessionStartersContext,
): TerminalSessionStartersContext["host"] => {
@@ -46,7 +68,9 @@ const resolveStartupHost = (
prefersLiveStartupHost(ctx.host.protocol)
&& live
&& live.id === ctx.host.id
&& sameSshDialTarget(ctx.host, live)
&& (ctx.host.protocol === "local"
? sameLocalLaunchTarget(ctx.host, live)
: sameSshDialTarget(ctx.host, live))
) {
return live;
}
+13
View File
@@ -15,6 +15,7 @@ test('createLocalShellHost builds a grouped local-protocol host', () => {
shellIcon: 'powershell',
group: 'Projects/A',
startDir: ' /home/user/work ',
startupCommand: 'npm run dev',
tags: ['local', 'build'],
});
@@ -27,10 +28,22 @@ test('createLocalShellHost builds a grouped local-protocol host', () => {
assert.equal(host.localShellName, 'Windows PowerShell');
assert.equal(host.localShellIcon, 'powershell');
assert.equal(host.localStartDir, '/home/user/work');
assert.equal(host.startupCommand, 'npm run dev');
assert.deepEqual(host.tags, ['local', 'build']);
assert.ok(host.id.startsWith('local-'));
});
test('createLocalShellHost preserves startupCommand verbatim when non-empty and clears blank input', () => {
const withLeadingSpace = createLocalShellHost({ startupCommand: ' echo secret' });
assert.equal(withLeadingSpace.startupCommand, ' echo secret');
const multiLine = createLocalShellHost({ startupCommand: 'source .venv/bin/activate\npytest' });
assert.equal(multiLine.startupCommand, 'source .venv/bin/activate\npytest');
assert.equal(createLocalShellHost({ startupCommand: '' }).startupCommand, undefined);
assert.equal(createLocalShellHost({ startupCommand: ' \n\t ' }).startupCommand, undefined);
});
test('createLocalShellHost falls back to defaults for empty input', () => {
const host = createLocalShellHost({});
assert.equal(host.label, 'Local Shell');
+2
View File
@@ -22,6 +22,7 @@ export interface LocalShellHostInput {
shellName?: string;
shellIcon?: string;
startDir?: string;
startupCommand?: string;
group?: string;
tags?: string[];
notes?: string;
@@ -45,6 +46,7 @@ export const createLocalShellHost = (input: LocalShellHostInput): Host => ({
localShellName: input.shellName?.trim() || undefined,
localShellIcon: input.shellIcon?.trim() || undefined,
localStartDir: input.startDir?.trim() || undefined,
startupCommand: input.startupCommand?.trim() ? input.startupCommand : undefined,
});
/** What an existing vault host shows as its local-shell display name. */
+57
View File
@@ -255,6 +255,63 @@ test("resolveTerminalSessionHost preserves the session local-shell snapshot over
assert.equal(resolved.localStartDir, "C:/project");
});
test("resolveTerminalSessionHost keeps startupCommand only when the saved local host matches the session launch target", () => {
const savedLocalHost: Host = {
id: "target",
label: "Project Shell",
hostname: "localhost",
username: "",
protocol: "local",
tags: ["local"],
os: "macos",
localShell: "/bin/zsh",
localShellArgs: ["-l"],
localStartDir: "/workspace/app",
startupCommand: "npm run dev",
startupCommandRunMode: "lineDelay",
};
const sessionSnapshot: TerminalSession = {
...baseSession,
hostname: "localhost",
username: "local",
port: undefined,
protocol: "local",
localShell: "/bin/zsh",
localShellArgs: ["-l"],
localStartDir: "/workspace/app",
};
const matching = resolveTerminalSessionHost({
session: sessionSnapshot,
hosts: [savedLocalHost],
groupConfigs: [],
proxyProfiles,
localOs: "macos",
});
assert.equal(matching.startupCommand, "npm run dev");
assert.equal(matching.startupCommandRunMode, "lineDelay");
const mismatches: Array<[string, Partial<Host>]> = [
["localShell", { localShell: "/bin/bash" }],
["localShellArgs", { localShellArgs: ["--norc"] }],
["localStartDir", { localStartDir: "/workspace/other" }],
["protocol", { protocol: "ssh", hostname: "prod.example.com", username: "ops" }],
];
for (const [label, patch] of mismatches) {
const resolved = resolveTerminalSessionHost({
session: sessionSnapshot,
hosts: [{ ...savedLocalHost, ...patch }],
groupConfigs: [],
proxyProfiles,
localOs: "macos",
});
assert.equal(resolved.localShell, "/bin/zsh", label);
assert.equal(resolved.localStartDir, "/workspace/app", label);
assert.equal(resolved.startupCommand, undefined, `${label} should drop edited host startupCommand`);
assert.equal(resolved.startupCommandRunMode, undefined, `${label} should drop edited host startupCommandRunMode`);
}
});
test("resolveTerminalSessionHost falls back to the saved local shell when the session has no snapshot", () => {
const host: Host = {
id: "target",
+48 -7
View File
@@ -96,20 +96,61 @@ function buildFallbackHostFromSession(
};
}
const sameLocalShellArgs = (
left: string[] | undefined,
right: string[] | undefined,
): boolean => {
const normalizedLeft = left?.length ? left : undefined;
const normalizedRight = right?.length ? right : undefined;
if (!normalizedLeft && !normalizedRight) return true;
if (!normalizedLeft || !normalizedRight || normalizedLeft.length !== normalizedRight.length) {
return false;
}
return normalizedLeft.every((arg, index) => arg === normalizedRight[index]);
};
const matchesSavedLocalLaunchTarget = (
savedHost: Host,
overlaid: Pick<Host, "localShell" | "localShellArgs" | "localStartDir">,
): boolean => (
savedHost.protocol === "local"
&& (overlaid.localShell ?? "") === (savedHost.localShell ?? "")
&& sameLocalShellArgs(overlaid.localShellArgs, savedHost.localShellArgs)
&& (overlaid.localStartDir || "~") === (savedHost.localStartDir || "~")
);
// A local session carries a shell snapshot (shell path, args, name, icon,
// start dir) captured at launch time; the saved host may have been edited
// since. Popup/clone flows must relaunch the session's shell, not the host's
// current one, so overlay the snapshot onto the resolved host.
const overlaySessionLocalShell = (session: TerminalSession, host: Host): Host => {
// current one, so overlay the snapshot onto the resolved host. When the saved
// host now targets a different protocol, shell, args, or start directory, drop
// its startup command so a command authored for the edited target cannot run
// inside the old session.
const overlaySessionLocalShell = (
session: TerminalSession,
host: Host,
savedHost: Host,
): Host => {
if (session.protocol !== "local") return host;
const localShell = session.localShell ?? host.localShell;
const localShellArgs = session.localShellArgs ?? host.localShellArgs;
const localStartDir = session.localStartDir ?? host.localStartDir;
const keepsSavedStartupCommand = matchesSavedLocalLaunchTarget(savedHost, {
localShell,
localShellArgs,
localStartDir,
});
return {
...host,
username: session.username,
localShell: session.localShell ?? host.localShell,
localShellArgs: session.localShellArgs ?? host.localShellArgs,
localShell,
localShellArgs,
localShellName: session.localShellName ?? host.localShellName,
localShellIcon: session.localShellIcon ?? host.localShellIcon,
localStartDir: session.localStartDir ?? host.localStartDir,
localStartDir,
...(keepsSavedStartupCommand
? {}
: { startupCommand: undefined, startupCommandRunMode: undefined }),
};
};
@@ -156,7 +197,7 @@ export function resolveTerminalSessionHost({
backspaceBehavior === existingHost.backspaceBehavior
) {
return suppressDeviceTypeForShellTransport(
overlaySessionLocalShell(session, existingHost),
overlaySessionLocalShell(session, existingHost, existingHost),
);
}
@@ -168,7 +209,7 @@ export function resolveTerminalSessionHost({
etEnabled,
pluginConnection,
backspaceBehavior,
}));
}, existingHost));
}
export function resolveTerminalChainHosts({