Reuse terminals for non-service scripts and track lifecycle via OSC 633
Scripts launched from the UI now run in a dedicated terminal per script (titled after the script) and reuse the same terminal across re-runs. Script lifecycle is driven by a new onCommandFinished signal sourced from OSC 633 command-finished events emitted by the zsh shell integration, so foreground script exit updates status without killing the terminal. Script payloads now carry terminalId so the workspace can surface the associated tab from the scripts dropdown.
This commit is contained in:
@@ -57,6 +57,7 @@ function createStubTerminalManager(
|
||||
send: () => {},
|
||||
subscribe: () => () => {},
|
||||
onExit: () => () => {},
|
||||
onCommandFinished: () => () => {},
|
||||
getState: () => ({
|
||||
rows: 1,
|
||||
cols: 1,
|
||||
@@ -69,6 +70,7 @@ function createStubTerminalManager(
|
||||
getSize: () => ({ rows: 1, cols: 1 }),
|
||||
getTitle: () => undefined,
|
||||
getExitInfo: () => null,
|
||||
killAndWait: async () => {},
|
||||
};
|
||||
},
|
||||
registerCwdEnv() {},
|
||||
@@ -76,6 +78,7 @@ function createStubTerminalManager(
|
||||
return undefined;
|
||||
},
|
||||
killTerminal() {},
|
||||
async killTerminalAndWait() {},
|
||||
listDirectories() {
|
||||
return [];
|
||||
},
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
buildWorkspaceScriptPayloads,
|
||||
createScriptStatusEmitter,
|
||||
} from "./script-status-projection.js";
|
||||
import { WorkspaceScriptPayloadSchema } from "../shared/messages.js";
|
||||
import type { ScriptHealthState } from "./script-health-monitor.js";
|
||||
import { WorkspaceScriptRuntimeStore } from "./workspace-script-runtime-store.js";
|
||||
|
||||
@@ -50,6 +51,21 @@ function buildPayloads(input: {
|
||||
}
|
||||
|
||||
describe("script-status-projection", () => {
|
||||
it("defaults omitted workspace script terminal ids to null", () => {
|
||||
expect(
|
||||
WorkspaceScriptPayloadSchema.parse({
|
||||
scriptName: "typecheck",
|
||||
type: "script",
|
||||
hostname: "typecheck",
|
||||
port: null,
|
||||
proxyUrl: null,
|
||||
lifecycle: "stopped",
|
||||
health: null,
|
||||
exitCode: 0,
|
||||
}).terminalId,
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("projects plain scripts and services differently", () => {
|
||||
const workspaceId = "workspace-plain-and-service";
|
||||
const workspace = createWorkspaceRepo({
|
||||
@@ -90,6 +106,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "stopped",
|
||||
health: null,
|
||||
exitCode: 0,
|
||||
terminalId: "term-script",
|
||||
},
|
||||
{
|
||||
scriptName: "web",
|
||||
@@ -100,6 +117,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "stopped",
|
||||
health: null,
|
||||
exitCode: null,
|
||||
terminalId: null,
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
@@ -121,19 +139,19 @@ describe("script-status-projection", () => {
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
|
||||
try {
|
||||
expect(
|
||||
buildPayloads({
|
||||
workspaceId,
|
||||
workspaceDirectory: workspace.repoDir,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
daemonPort: 6767,
|
||||
gitMetadata: {
|
||||
projectSlug: "service-provided",
|
||||
currentBranch: "feature/from-service",
|
||||
},
|
||||
}),
|
||||
).toEqual([
|
||||
const payloads = buildPayloads({
|
||||
workspaceId,
|
||||
workspaceDirectory: workspace.repoDir,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
daemonPort: 6767,
|
||||
gitMetadata: {
|
||||
projectSlug: "service-provided",
|
||||
currentBranch: "feature/from-service",
|
||||
},
|
||||
});
|
||||
|
||||
expect(payloads).toEqual([
|
||||
{
|
||||
scriptName: "web",
|
||||
type: "service",
|
||||
@@ -143,6 +161,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "stopped",
|
||||
health: null,
|
||||
exitCode: null,
|
||||
terminalId: null,
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
@@ -198,6 +217,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "running",
|
||||
health: "healthy",
|
||||
exitCode: null,
|
||||
terminalId: "term-web",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
@@ -252,6 +272,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "running",
|
||||
health: null,
|
||||
exitCode: null,
|
||||
terminalId: "term-web",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
@@ -299,6 +320,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "running",
|
||||
health: null,
|
||||
exitCode: null,
|
||||
terminalId: "term-docs",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
@@ -339,6 +361,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "running",
|
||||
health: null,
|
||||
exitCode: null,
|
||||
terminalId: "term-typecheck",
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
@@ -409,6 +432,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "running",
|
||||
health: "healthy",
|
||||
exitCode: null,
|
||||
terminalId: "term-api",
|
||||
},
|
||||
{
|
||||
scriptName: "typecheck",
|
||||
@@ -419,6 +443,7 @@ describe("script-status-projection", () => {
|
||||
lifecycle: "stopped",
|
||||
health: null,
|
||||
exitCode: null,
|
||||
terminalId: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -103,6 +103,7 @@ export function buildWorkspaceScriptPayloads(
|
||||
lifecycle: runtimeEntry?.lifecycle ?? "stopped",
|
||||
health: type === "service" ? toWireHealth(options.resolveHealth?.(hostname) ?? null) : null,
|
||||
exitCode: runtimeEntry?.exitCode ?? null,
|
||||
terminalId: runtimeEntry?.terminalId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -134,6 +135,7 @@ export function buildWorkspaceScriptPayloads(
|
||||
? toWireHealth(options.resolveHealth?.(hostname) ?? null)
|
||||
: null,
|
||||
exitCode: runtimeEntry.exitCode,
|
||||
terminalId: runtimeEntry.terminalId,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -427,6 +427,11 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
};
|
||||
},
|
||||
onExit: () => () => {},
|
||||
onCommandFinished: () => () => {},
|
||||
onTitleChange: () => () => {},
|
||||
getSize: () => ({ rows: 0, cols: 0 }),
|
||||
getTitle: () => undefined,
|
||||
getExitInfo: () => null,
|
||||
getState: () => ({
|
||||
rows: 0,
|
||||
cols: 0,
|
||||
@@ -435,6 +440,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
cursor: { row: 0, col: 0 },
|
||||
}),
|
||||
kill: () => {},
|
||||
killAndWait: async () => {},
|
||||
};
|
||||
},
|
||||
registerCwdEnv() {},
|
||||
@@ -442,6 +448,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
return undefined;
|
||||
},
|
||||
killTerminal() {},
|
||||
async killTerminalAndWait() {},
|
||||
listDirectories() {
|
||||
return [];
|
||||
},
|
||||
@@ -508,6 +515,11 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
send: () => {},
|
||||
subscribe: () => () => {},
|
||||
onExit: () => () => {},
|
||||
onCommandFinished: () => () => {},
|
||||
onTitleChange: () => () => {},
|
||||
getSize: () => ({ rows: 1, cols: 1 }),
|
||||
getTitle: () => undefined,
|
||||
getExitInfo: () => null,
|
||||
getState: () => ({
|
||||
rows: 1,
|
||||
cols: 1,
|
||||
@@ -516,6 +528,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
cursor: { row: 0, col: 0 },
|
||||
}),
|
||||
kill: () => {},
|
||||
killAndWait: async () => {},
|
||||
};
|
||||
},
|
||||
registerCwdEnv(options) {
|
||||
@@ -525,6 +538,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
return undefined;
|
||||
},
|
||||
killTerminal() {},
|
||||
async killTerminalAndWait() {},
|
||||
listDirectories() {
|
||||
return [];
|
||||
},
|
||||
@@ -563,11 +577,15 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
interface CreateTerminalCall {
|
||||
cwd: string;
|
||||
name?: string;
|
||||
title?: string;
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface StubTerminalRecord {
|
||||
id: string;
|
||||
triggerExit: (exitCode: number) => void;
|
||||
triggerCommandFinished: (exitCode: number) => void;
|
||||
sentInputs: string[];
|
||||
}
|
||||
|
||||
function createStubTerminalManager(
|
||||
@@ -575,6 +593,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
terminalRecords: StubTerminalRecord[] = [],
|
||||
): TerminalManager {
|
||||
let terminalCounter = 0;
|
||||
const sessionsById = new Map<string, TerminalSession>();
|
||||
|
||||
return {
|
||||
async getTerminals() {
|
||||
@@ -583,9 +602,16 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
async createTerminal(options: CreateTerminalCall): Promise<TerminalSession> {
|
||||
createTerminalCalls.push(options);
|
||||
terminalCounter += 1;
|
||||
const terminalId = `term-service-${terminalCounter}`;
|
||||
const terminalId = `term-${terminalCounter}`;
|
||||
let exitHandler: ((info: { exitCode: number | null }) => void) | null = null;
|
||||
let commandFinishedHandler: ((info: { exitCode: number | null }) => void) | null = null;
|
||||
const sentInputs: string[] = [];
|
||||
terminalRecords.push({
|
||||
id: terminalId,
|
||||
sentInputs,
|
||||
triggerCommandFinished: (exitCode) => {
|
||||
commandFinishedHandler?.({ exitCode });
|
||||
},
|
||||
triggerExit: (exitCode) => {
|
||||
if (exitHandler) {
|
||||
exitHandler({ exitCode });
|
||||
@@ -593,11 +619,15 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
const session: TerminalSession = {
|
||||
id: terminalId,
|
||||
name: options.name ?? "Terminal",
|
||||
cwd: options.cwd,
|
||||
send: () => {},
|
||||
send: (message) => {
|
||||
if (message.type === "input") {
|
||||
sentInputs.push(message.data);
|
||||
}
|
||||
},
|
||||
subscribe: () => () => {},
|
||||
onExit: (handler) => {
|
||||
exitHandler = handler;
|
||||
@@ -607,6 +637,14 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
}
|
||||
};
|
||||
},
|
||||
onCommandFinished: (handler) => {
|
||||
commandFinishedHandler = handler;
|
||||
return () => {
|
||||
if (commandFinishedHandler === handler) {
|
||||
commandFinishedHandler = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
getState: () => ({
|
||||
rows: 1,
|
||||
cols: 1,
|
||||
@@ -621,10 +659,12 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
getExitInfo: () => null,
|
||||
killAndWait: async () => {},
|
||||
};
|
||||
sessionsById.set(terminalId, session);
|
||||
return session;
|
||||
},
|
||||
registerCwdEnv() {},
|
||||
getTerminal() {
|
||||
return undefined;
|
||||
getTerminal(id) {
|
||||
return sessionsById.get(id);
|
||||
},
|
||||
killTerminal() {},
|
||||
async killTerminalAndWait() {},
|
||||
@@ -653,26 +693,29 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
return env;
|
||||
}
|
||||
|
||||
it("spawns plain scripts without env injection or routes", async () => {
|
||||
writeFileSync(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
scripts: {
|
||||
web: {
|
||||
command: "npm run dev",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
function commitPaseoScripts(
|
||||
scripts: Record<string, { command: string; type?: "script" | "service" }>,
|
||||
message = "add script config",
|
||||
): void {
|
||||
writeFileSync(join(repoDir, "paseo.json"), JSON.stringify({ scripts }));
|
||||
execSync("git add paseo.json", { cwd: repoDir, stdio: "pipe" });
|
||||
execSync("git -c commit.gpgsign=false commit -m 'add script config'", {
|
||||
execSync(`git -c commit.gpgsign=false commit -m ${JSON.stringify(message)}`, {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
}
|
||||
|
||||
it("spawns plain scripts in persistent shell terminals without env injection or routes", async () => {
|
||||
commitPaseoScripts({
|
||||
web: {
|
||||
command: "npm run dev",
|
||||
},
|
||||
});
|
||||
|
||||
const routeStore = new ScriptRouteStore();
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const createTerminalCalls: CreateTerminalCall[] = [];
|
||||
const terminalRecords: StubTerminalRecord[] = [];
|
||||
|
||||
const results = await spawnWorktreeScripts({
|
||||
repoRoot: repoDir,
|
||||
@@ -681,7 +724,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager: createStubTerminalManager(createTerminalCalls),
|
||||
terminalManager: createStubTerminalManager(createTerminalCalls, terminalRecords),
|
||||
});
|
||||
|
||||
expect(results).toHaveLength(1);
|
||||
@@ -689,40 +732,277 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
expect(createTerminalCalls).toHaveLength(1);
|
||||
expect(createTerminalCalls[0]?.cwd).toBe(repoDir);
|
||||
expect(createTerminalCalls[0]?.name).toBe("web");
|
||||
expect(createTerminalCalls[0]?.title).toBe("web");
|
||||
expect(createTerminalCalls[0]?.env).toBeUndefined();
|
||||
expect(terminalRecords[0]?.sentInputs).toEqual(["npm run dev\r"]);
|
||||
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "web" })).toMatchObject({
|
||||
type: "script",
|
||||
lifecycle: "running",
|
||||
exitCode: null,
|
||||
terminalId: "term-service-1",
|
||||
terminalId: "term-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("spawns services with route registration and injected peer service env vars", async () => {
|
||||
writeFileSync(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
scripts: {
|
||||
api: {
|
||||
type: "service",
|
||||
command: "npm run api",
|
||||
},
|
||||
"app-server": {
|
||||
type: "service",
|
||||
command: "npm run app",
|
||||
},
|
||||
it("records plain script exit codes from shell command completion without terminal exit", async () => {
|
||||
commitPaseoScripts(
|
||||
{
|
||||
typecheck: {
|
||||
command: 'node -e "process.exit(7)"',
|
||||
},
|
||||
}),
|
||||
},
|
||||
"add one-off script config",
|
||||
);
|
||||
execSync("git add paseo.json", { cwd: repoDir, stdio: "pipe" });
|
||||
execSync("git -c commit.gpgsign=false commit -m 'add service script config'", {
|
||||
cwd: repoDir,
|
||||
stdio: "pipe",
|
||||
});
|
||||
|
||||
const routeStore = new ScriptRouteStore();
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const createTerminalCalls: CreateTerminalCall[] = [];
|
||||
const terminalRecords: StubTerminalRecord[] = [];
|
||||
const terminalManager = createStubTerminalManager(createTerminalCalls, terminalRecords);
|
||||
|
||||
const result = await spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
workspaceId: repoDir,
|
||||
projectSlug: "repo",
|
||||
branchName: "feature-script-exit",
|
||||
scriptName: "typecheck",
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
expect(createTerminalCalls).toHaveLength(1);
|
||||
terminalRecords[0]?.triggerCommandFinished(7);
|
||||
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "typecheck" })).toMatchObject({
|
||||
type: "script",
|
||||
lifecycle: "stopped",
|
||||
terminalId: result.terminalId,
|
||||
exitCode: 7,
|
||||
});
|
||||
expect(terminalRecords[0]?.sentInputs).toEqual(['node -e "process.exit(7)"\r']);
|
||||
});
|
||||
|
||||
it("reuses a live terminal when rerunning after plain script completion", async () => {
|
||||
commitPaseoScripts(
|
||||
{
|
||||
typecheck: {
|
||||
command: "npm run typecheck",
|
||||
},
|
||||
},
|
||||
"add one-off script config",
|
||||
);
|
||||
|
||||
const routeStore = new ScriptRouteStore();
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const createTerminalCalls: CreateTerminalCall[] = [];
|
||||
const terminalRecords: StubTerminalRecord[] = [];
|
||||
const terminalManager = createStubTerminalManager(createTerminalCalls, terminalRecords);
|
||||
|
||||
const firstResult = await spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
workspaceId: repoDir,
|
||||
projectSlug: "repo",
|
||||
branchName: "feature-script-rerun",
|
||||
scriptName: "typecheck",
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
terminalRecords[0]?.triggerCommandFinished(7);
|
||||
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "typecheck" })).toMatchObject({
|
||||
type: "script",
|
||||
lifecycle: "stopped",
|
||||
terminalId: firstResult.terminalId,
|
||||
exitCode: 7,
|
||||
});
|
||||
|
||||
const secondResult = await spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
workspaceId: repoDir,
|
||||
projectSlug: "repo",
|
||||
branchName: "feature-script-rerun",
|
||||
scriptName: "typecheck",
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
expect(secondResult.terminalId).toBe(firstResult.terminalId);
|
||||
expect(createTerminalCalls).toHaveLength(1);
|
||||
expect(terminalRecords[0]?.sentInputs).toEqual(["npm run typecheck\r", "npm run typecheck\r"]);
|
||||
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "typecheck" })).toMatchObject({
|
||||
type: "script",
|
||||
lifecycle: "running",
|
||||
terminalId: firstResult.terminalId,
|
||||
exitCode: null,
|
||||
});
|
||||
terminalRecords[0]?.triggerCommandFinished(0);
|
||||
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "typecheck" })).toMatchObject({
|
||||
type: "script",
|
||||
lifecycle: "stopped",
|
||||
terminalId: firstResult.terminalId,
|
||||
exitCode: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks command completion when reusing a live terminal from a stopped plain script entry", async () => {
|
||||
commitPaseoScripts(
|
||||
{
|
||||
typecheck: {
|
||||
command: "npm run typecheck",
|
||||
},
|
||||
},
|
||||
"add one-off script config",
|
||||
);
|
||||
|
||||
const routeStore = new ScriptRouteStore();
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const createTerminalCalls: CreateTerminalCall[] = [];
|
||||
const terminalRecords: StubTerminalRecord[] = [];
|
||||
const terminalManager = createStubTerminalManager(createTerminalCalls, terminalRecords);
|
||||
const existingTerminal = await terminalManager.createTerminal({
|
||||
cwd: repoDir,
|
||||
name: "typecheck",
|
||||
title: "typecheck",
|
||||
});
|
||||
runtimeStore.set({
|
||||
workspaceId: repoDir,
|
||||
scriptName: "typecheck",
|
||||
type: "script",
|
||||
lifecycle: "stopped",
|
||||
terminalId: existingTerminal.id,
|
||||
exitCode: 1,
|
||||
});
|
||||
|
||||
const result = await spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
workspaceId: repoDir,
|
||||
projectSlug: "repo",
|
||||
branchName: "feature-script-existing-terminal",
|
||||
scriptName: "typecheck",
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
expect(result.terminalId).toBe(existingTerminal.id);
|
||||
expect(createTerminalCalls).toHaveLength(1);
|
||||
expect(terminalRecords[0]?.sentInputs).toEqual(["npm run typecheck\r"]);
|
||||
|
||||
terminalRecords[0]?.triggerCommandFinished(0);
|
||||
|
||||
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "typecheck" })).toMatchObject({
|
||||
type: "script",
|
||||
lifecycle: "stopped",
|
||||
terminalId: existingTerminal.id,
|
||||
exitCode: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses terminal exit as a fallback before shell command completion", async () => {
|
||||
commitPaseoScripts(
|
||||
{
|
||||
typecheck: {
|
||||
command: "npm run typecheck",
|
||||
},
|
||||
},
|
||||
"add one-off script config",
|
||||
);
|
||||
|
||||
const routeStore = new ScriptRouteStore();
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const createTerminalCalls: CreateTerminalCall[] = [];
|
||||
const terminalRecords: StubTerminalRecord[] = [];
|
||||
const terminalManager = createStubTerminalManager(createTerminalCalls, terminalRecords);
|
||||
|
||||
const result = await spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
workspaceId: repoDir,
|
||||
projectSlug: "repo",
|
||||
branchName: "feature-script-terminal-exit",
|
||||
scriptName: "typecheck",
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
terminalRecords[0]?.triggerExit(9);
|
||||
|
||||
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "typecheck" })).toMatchObject({
|
||||
type: "script",
|
||||
lifecycle: "stopped",
|
||||
terminalId: result.terminalId,
|
||||
exitCode: 9,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects duplicate plain script starts while running", async () => {
|
||||
commitPaseoScripts(
|
||||
{
|
||||
typecheck: {
|
||||
command: 'node -e "setTimeout(() => {}, 30000)"',
|
||||
},
|
||||
},
|
||||
"add long-running one-off script",
|
||||
);
|
||||
|
||||
const routeStore = new ScriptRouteStore();
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const createTerminalCalls: CreateTerminalCall[] = [];
|
||||
const terminalManager = createStubTerminalManager(createTerminalCalls);
|
||||
|
||||
await spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
workspaceId: repoDir,
|
||||
projectSlug: "repo",
|
||||
branchName: "feature-script-duplicate",
|
||||
scriptName: "typecheck",
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
await expect(
|
||||
spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
workspaceId: repoDir,
|
||||
projectSlug: "repo",
|
||||
branchName: "feature-script-duplicate",
|
||||
scriptName: "typecheck",
|
||||
daemonPort: null,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager,
|
||||
}),
|
||||
).rejects.toThrow("Script 'typecheck' is already running");
|
||||
expect(createTerminalCalls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("spawns services with route registration and injected peer service env vars", async () => {
|
||||
commitPaseoScripts(
|
||||
{
|
||||
api: {
|
||||
type: "service",
|
||||
command: "npm run api",
|
||||
},
|
||||
"app-server": {
|
||||
type: "service",
|
||||
command: "npm run app",
|
||||
},
|
||||
},
|
||||
"add service script config",
|
||||
);
|
||||
|
||||
const routeStore = new ScriptRouteStore();
|
||||
const runtimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const createTerminalCalls: CreateTerminalCall[] = [];
|
||||
const terminalRecords: StubTerminalRecord[] = [];
|
||||
|
||||
const result = await spawnWorkspaceScript({
|
||||
repoRoot: repoDir,
|
||||
@@ -733,7 +1013,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
daemonPort: 6767,
|
||||
routeStore,
|
||||
runtimeStore,
|
||||
terminalManager: createStubTerminalManager(createTerminalCalls),
|
||||
terminalManager: createStubTerminalManager(createTerminalCalls, terminalRecords),
|
||||
});
|
||||
|
||||
expect(result.scriptName).toBe("api");
|
||||
@@ -749,6 +1029,7 @@ describe("runAsyncWorktreeBootstrap", () => {
|
||||
expect(createTerminalCalls).toHaveLength(1);
|
||||
expect(createTerminalCalls[0]?.cwd).toBe(repoDir);
|
||||
expect(createTerminalCalls[0]?.name).toBe("api");
|
||||
expect(terminalRecords[0]?.sentInputs).toEqual(["npm run api\r"]);
|
||||
expect(createTerminalCalls[0]?.env).not.toHaveProperty("PORT");
|
||||
expect(createTerminalCalls[0]?.env?.PASEO_PORT).toEqual(expect.any(String));
|
||||
expect(createTerminalCalls[0]?.env?.HOST).toBe("127.0.0.1");
|
||||
|
||||
@@ -686,11 +686,6 @@ export interface WorktreeScriptResult {
|
||||
terminalId: string;
|
||||
}
|
||||
|
||||
interface WorkspaceServiceDeclaration {
|
||||
scriptName: string;
|
||||
port?: number;
|
||||
}
|
||||
|
||||
interface SpawnWorkspaceScriptOptions {
|
||||
repoRoot: string;
|
||||
workspaceId: string;
|
||||
@@ -730,26 +725,28 @@ export async function spawnWorkspaceScript(
|
||||
}
|
||||
|
||||
const serviceScript = isServiceScript(config);
|
||||
const scriptType = serviceScript ? "service" : "script";
|
||||
let hostname: string | null = null;
|
||||
let port: number | null = null;
|
||||
let terminal: TerminalSession | null = null;
|
||||
let runtimeRegistered = false;
|
||||
let routeRegistered = false;
|
||||
let disposeLifecycleListeners: (() => void) | null = null;
|
||||
|
||||
try {
|
||||
if (runtimeStore.isRunning({ workspaceId, scriptName })) {
|
||||
throw new Error(`Script '${scriptName}' is already running`);
|
||||
}
|
||||
|
||||
const existingRuntimeEntry = runtimeStore.get({ workspaceId, scriptName });
|
||||
let env: Record<string, string> | undefined;
|
||||
if (serviceScript) {
|
||||
const serviceHostname = buildScriptHostname({
|
||||
hostname = buildScriptHostname({
|
||||
projectSlug,
|
||||
branchName,
|
||||
scriptName,
|
||||
});
|
||||
hostname = serviceHostname;
|
||||
const serviceDeclarations: WorkspaceServiceDeclaration[] = [];
|
||||
|
||||
const serviceDeclarations: Array<{ scriptName: string; port?: number }> = [];
|
||||
for (const [configuredScriptName, scriptConfig] of scriptConfigs) {
|
||||
if (isServiceScript(scriptConfig)) {
|
||||
serviceDeclarations.push({
|
||||
@@ -767,8 +764,7 @@ export async function spawnWorkspaceScript(
|
||||
services: serviceDeclarations,
|
||||
allocatePort: findFreePort,
|
||||
});
|
||||
const existingRuntimeEntry = runtimeStore.get({ workspaceId, scriptName });
|
||||
const servicePort =
|
||||
port =
|
||||
existingRuntimeEntry?.lifecycle === "stopped"
|
||||
? await refreshWorkspaceServicePort({
|
||||
workspaceId,
|
||||
@@ -777,13 +773,11 @@ export async function spawnWorkspaceScript(
|
||||
})
|
||||
: requirePlannedWorkspaceServicePort(plannedPorts, scriptName);
|
||||
|
||||
port = servicePort;
|
||||
|
||||
const peers: WorkspaceServicePeer[] = [];
|
||||
for (const [peerScriptName, peerPort] of plannedPorts) {
|
||||
peers.push({
|
||||
scriptName: peerScriptName,
|
||||
port: peerScriptName === scriptName ? servicePort : peerPort,
|
||||
port: peerScriptName === scriptName ? port : peerPort,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -797,8 +791,8 @@ export async function spawnWorkspaceScript(
|
||||
});
|
||||
|
||||
routeStore.registerRoute({
|
||||
hostname: serviceHostname,
|
||||
port: servicePort,
|
||||
hostname,
|
||||
port,
|
||||
workspaceId,
|
||||
projectSlug,
|
||||
scriptName,
|
||||
@@ -806,47 +800,82 @@ export async function spawnWorkspaceScript(
|
||||
routeRegistered = true;
|
||||
}
|
||||
|
||||
const createdTerminal = await terminalManager.createTerminal({
|
||||
cwd: repoRoot,
|
||||
name: scriptName,
|
||||
env,
|
||||
});
|
||||
terminal = createdTerminal;
|
||||
let reusableTerminal: TerminalSession | null = null;
|
||||
if (!serviceScript && existingRuntimeEntry?.terminalId) {
|
||||
reusableTerminal = terminalManager.getTerminal(existingRuntimeEntry.terminalId) ?? null;
|
||||
}
|
||||
const terminal =
|
||||
reusableTerminal ??
|
||||
(await terminalManager.createTerminal({
|
||||
cwd: repoRoot,
|
||||
name: scriptName,
|
||||
title: scriptName,
|
||||
env,
|
||||
}));
|
||||
|
||||
runtimeStore.set({
|
||||
workspaceId,
|
||||
scriptName,
|
||||
type: serviceScript ? "service" : "script",
|
||||
type: scriptType,
|
||||
lifecycle: "running",
|
||||
terminalId: createdTerminal.id,
|
||||
terminalId: terminal.id,
|
||||
exitCode: null,
|
||||
});
|
||||
runtimeRegistered = true;
|
||||
|
||||
terminal.onExit((info) => {
|
||||
if (hostname) {
|
||||
const stopRuntimeIfCurrent = (input: { exitCode: number | null; removeRoute: boolean }) => {
|
||||
const current = runtimeStore.get({ workspaceId, scriptName });
|
||||
if (current?.terminalId !== terminal.id || current.lifecycle !== "running") {
|
||||
return;
|
||||
}
|
||||
|
||||
disposeLifecycleListeners?.();
|
||||
disposeLifecycleListeners = null;
|
||||
|
||||
if (input.removeRoute && hostname) {
|
||||
routeStore.removeRouteForWorkspaceScript({ workspaceId, scriptName });
|
||||
}
|
||||
runtimeStore.set({
|
||||
workspaceId,
|
||||
scriptName,
|
||||
type: serviceScript ? "service" : "script",
|
||||
type: scriptType,
|
||||
lifecycle: "stopped",
|
||||
terminalId: createdTerminal.id,
|
||||
exitCode: info.exitCode,
|
||||
terminalId: terminal.id,
|
||||
exitCode: input.exitCode,
|
||||
});
|
||||
onLifecycleChanged?.();
|
||||
logger?.info(
|
||||
{
|
||||
scriptName,
|
||||
hostname,
|
||||
exitCode: info.exitCode,
|
||||
terminalId: createdTerminal.id,
|
||||
exitCode: input.exitCode,
|
||||
terminalId: terminal.id,
|
||||
},
|
||||
"Stopped worktree script",
|
||||
);
|
||||
};
|
||||
|
||||
const unsubscribeExit = terminal.onExit((info) => {
|
||||
stopRuntimeIfCurrent({
|
||||
exitCode: info.exitCode,
|
||||
removeRoute: true,
|
||||
});
|
||||
});
|
||||
|
||||
await waitForTerminalBootstrapReadiness(terminal);
|
||||
let unsubscribeCommandFinished: (() => void) | null = null;
|
||||
if (!serviceScript) {
|
||||
unsubscribeCommandFinished = terminal.onCommandFinished((info) => {
|
||||
stopRuntimeIfCurrent({ exitCode: info.exitCode, removeRoute: false });
|
||||
});
|
||||
}
|
||||
disposeLifecycleListeners = () => {
|
||||
unsubscribeExit();
|
||||
unsubscribeCommandFinished?.();
|
||||
};
|
||||
|
||||
if (!reusableTerminal) {
|
||||
await waitForTerminalBootstrapReadiness(terminal);
|
||||
}
|
||||
terminal.send({ type: "input", data: `${config.command}\r` });
|
||||
|
||||
logger?.info(
|
||||
@@ -855,7 +884,7 @@ export async function spawnWorkspaceScript(
|
||||
hostname,
|
||||
port,
|
||||
terminalId: terminal.id,
|
||||
type: serviceScript ? "service" : "script",
|
||||
type: scriptType,
|
||||
},
|
||||
serviceScript
|
||||
? `Registered script proxy: ${hostname} -> 127.0.0.1:${port}`
|
||||
@@ -870,6 +899,7 @@ export async function spawnWorkspaceScript(
|
||||
terminalId: terminal.id,
|
||||
};
|
||||
} catch (error) {
|
||||
disposeLifecycleListeners?.();
|
||||
if (routeRegistered && hostname) {
|
||||
routeStore.removeRoute(hostname);
|
||||
}
|
||||
|
||||
@@ -143,6 +143,7 @@ function createTerminalManagerStub(options?: {
|
||||
}),
|
||||
subscribe: () => () => {},
|
||||
onExit: () => () => {},
|
||||
onCommandFinished: () => () => {},
|
||||
onTitleChange: () => () => {},
|
||||
send: (message: { type: string; data: string }) => {
|
||||
if (message.type === "input") {
|
||||
|
||||
@@ -1991,6 +1991,7 @@ export const WorkspaceScriptPayloadSchema = z.object({
|
||||
lifecycle: WorkspaceScriptLifecycleSchema,
|
||||
health: WorkspaceScriptHealthSchema.nullable(),
|
||||
exitCode: z.number().nullable().optional().default(null),
|
||||
terminalId: z.string().nullable().optional().default(null),
|
||||
});
|
||||
|
||||
const WorkspaceGitRuntimePayloadSchema = z
|
||||
|
||||
@@ -5,11 +5,26 @@ typeset -g _PASEO_ZSH_INTEGRATION_LOADED=1
|
||||
|
||||
autoload -Uz add-zsh-hook
|
||||
|
||||
typeset -g _PASEO_ZSH_COMMAND_ACTIVE=0
|
||||
|
||||
function _paseo_osc633() {
|
||||
printf '\e]633;%s\a' "$1"
|
||||
}
|
||||
|
||||
function _paseo_precmd() {
|
||||
local command_status=$?
|
||||
if [[ "$_PASEO_ZSH_COMMAND_ACTIVE" == "1" ]]; then
|
||||
_paseo_osc633 "D;${command_status}"
|
||||
_PASEO_ZSH_COMMAND_ACTIVE=0
|
||||
fi
|
||||
printf '\e]2;%s\a' "${PWD/#$HOME/~}"
|
||||
_paseo_osc633 "A"
|
||||
}
|
||||
|
||||
function _paseo_preexec() {
|
||||
_PASEO_ZSH_COMMAND_ACTIVE=1
|
||||
_paseo_osc633 "B"
|
||||
_paseo_osc633 "C"
|
||||
printf '\e]2;%s\a' "$1"
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface TerminalManager {
|
||||
id?: string;
|
||||
cwd: string;
|
||||
name?: string;
|
||||
title?: string;
|
||||
env?: Record<string, string>;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
@@ -160,6 +161,7 @@ export function createTerminalManager(): TerminalManager {
|
||||
id?: string;
|
||||
cwd: string;
|
||||
name?: string;
|
||||
title?: string;
|
||||
env?: Record<string, string>;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
@@ -178,6 +180,7 @@ export function createTerminalManager(): TerminalManager {
|
||||
...(options.id ? { id: options.id } : {}),
|
||||
cwd: options.cwd,
|
||||
name: options.name ?? defaultName,
|
||||
...(options.title ? { title: options.title } : {}),
|
||||
...(options.command ? { command: options.command } : {}),
|
||||
...(options.args ? { args: options.args } : {}),
|
||||
...(mergedEnv ? { env: mergedEnv } : {}),
|
||||
|
||||
@@ -443,6 +443,87 @@ describe("Terminal", () => {
|
||||
unsubscribeTitle();
|
||||
});
|
||||
|
||||
it("keeps preset titles instead of applying OSC title updates", async () => {
|
||||
const session = trackSession(
|
||||
await createTerminal({
|
||||
cwd: "/tmp",
|
||||
shell: "/bin/sh",
|
||||
env: { PS1: "$ " },
|
||||
title: "typecheck",
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForLines(session, ["$"]);
|
||||
session.send({ type: "input", data: "printf '\\033]0;Build Log\\007'\r" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
|
||||
expect(session.getTitle()).toBe("typecheck");
|
||||
expect(session.getState().title).toBe("typecheck");
|
||||
});
|
||||
|
||||
it("emits command completion from VS Code OSC 633 without visible output", async () => {
|
||||
const packageRoot = mkdtempSync(join(tmpdir(), "terminal-command-finished-"));
|
||||
temporaryDirs.push(packageRoot);
|
||||
const scriptPath = join(packageRoot, "emit-command-finished.sh");
|
||||
writeFileSync(scriptPath, "#!/bin/sh\nprintf '\\033]633;D;7\\007'\n");
|
||||
chmodSync(scriptPath, 0o755);
|
||||
|
||||
const session = trackSession(
|
||||
await createTerminal({
|
||||
cwd: packageRoot,
|
||||
shell: "/bin/sh",
|
||||
env: { PS1: "$ " },
|
||||
}),
|
||||
);
|
||||
const commandCompletions: Array<number | null> = [];
|
||||
const unsubscribeCommandFinished = session.onCommandFinished((info) => {
|
||||
commandCompletions.push(info.exitCode);
|
||||
});
|
||||
|
||||
await waitForLines(session, ["$"]);
|
||||
session.send({ type: "input", data: "./emit-command-finished.sh\r" });
|
||||
|
||||
await waitForState(session, () => commandCompletions.length === 1);
|
||||
|
||||
expect(commandCompletions).toEqual([7]);
|
||||
expect(getLines(session.getState()).join("\n")).not.toContain("633;D;7");
|
||||
|
||||
unsubscribeCommandFinished();
|
||||
});
|
||||
|
||||
it("ignores malformed VS Code OSC 633 command completion payloads", async () => {
|
||||
const packageRoot = mkdtempSync(join(tmpdir(), "terminal-command-finished-malformed-"));
|
||||
temporaryDirs.push(packageRoot);
|
||||
const scriptPath = join(packageRoot, "emit-malformed-command-finished.sh");
|
||||
writeFileSync(
|
||||
scriptPath,
|
||||
"#!/bin/sh\nprintf '\\033]633;D;garbage\\007\\033]633;D;8;extra\\007\\033]633;D;3\\007'\n",
|
||||
);
|
||||
chmodSync(scriptPath, 0o755);
|
||||
|
||||
const session = trackSession(
|
||||
await createTerminal({
|
||||
cwd: packageRoot,
|
||||
shell: "/bin/sh",
|
||||
env: { PS1: "$ " },
|
||||
}),
|
||||
);
|
||||
const commandCompletions: Array<number | null> = [];
|
||||
const unsubscribeCommandFinished = session.onCommandFinished((info) => {
|
||||
commandCompletions.push(info.exitCode);
|
||||
});
|
||||
|
||||
await waitForLines(session, ["$"]);
|
||||
session.send({ type: "input", data: "./emit-malformed-command-finished.sh\r" });
|
||||
|
||||
await waitForState(session, () => commandCompletions.length === 1);
|
||||
|
||||
expect(commandCompletions).toEqual([3]);
|
||||
expect(getLines(session.getState()).join("\n")).not.toContain("633;D;garbage");
|
||||
|
||||
unsubscribeCommandFinished();
|
||||
});
|
||||
|
||||
it("debounces rapid title changes and emits only the final title", async () => {
|
||||
const session = trackSession(
|
||||
await createTerminal({
|
||||
@@ -506,6 +587,42 @@ describe("Terminal", () => {
|
||||
await waitForTitle(session, (title) => title === "sleep 1");
|
||||
await waitForTitle(session, (title) => title === "~/dev/faro", 4000);
|
||||
});
|
||||
|
||||
it.skipIf(!hasZsh)("emits zsh shell integration command completion", async () => {
|
||||
const homeDir = mkdtempSync(join(tmpdir(), "terminal-zsh-command-finished-home-"));
|
||||
temporaryDirs.push(homeDir);
|
||||
const realZdotdir = join(homeDir, ".config", "zsh");
|
||||
const workingDir = join(homeDir, "dev", "faro");
|
||||
mkdirSync(realZdotdir, { recursive: true });
|
||||
mkdirSync(workingDir, { recursive: true });
|
||||
writeFileSync(join(realZdotdir, ".zshenv"), "");
|
||||
writeFileSync(join(realZdotdir, ".zshrc"), "PS1='$ '\n");
|
||||
|
||||
const session = trackSession(
|
||||
await createTerminal({
|
||||
cwd: workingDir,
|
||||
shell: "/bin/zsh",
|
||||
env: {
|
||||
HOME: homeDir,
|
||||
ZDOTDIR: realZdotdir,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const commandCompletions: Array<number | null> = [];
|
||||
const unsubscribeCommandFinished = session.onCommandFinished((info) => {
|
||||
commandCompletions.push(info.exitCode);
|
||||
});
|
||||
|
||||
await waitForLines(session, ["$"]);
|
||||
session.send({ type: "input", data: "false\r" });
|
||||
|
||||
await waitForState(session, () => commandCompletions.includes(1));
|
||||
|
||||
expect(commandCompletions).toEqual([1]);
|
||||
expect(getLines(session.getState()).join("\n")).not.toContain("633;D;1");
|
||||
|
||||
unsubscribeCommandFinished();
|
||||
});
|
||||
});
|
||||
|
||||
describe("colors", () => {
|
||||
|
||||
@@ -21,6 +21,10 @@ export interface TerminalExitInfo {
|
||||
lastOutputLines: string[];
|
||||
}
|
||||
|
||||
export interface TerminalCommandFinishedInfo {
|
||||
exitCode: number | null;
|
||||
}
|
||||
|
||||
export type ClientMessage =
|
||||
| { type: "input"; data: string }
|
||||
| { type: "resize"; rows: number; cols: number }
|
||||
@@ -38,6 +42,7 @@ export interface TerminalSession {
|
||||
send(msg: ClientMessage): void;
|
||||
subscribe(listener: (msg: ServerMessage) => void): () => void;
|
||||
onExit(listener: (info: TerminalExitInfo) => void): () => void;
|
||||
onCommandFinished(listener: (info: TerminalCommandFinishedInfo) => void): () => void;
|
||||
onTitleChange(listener: (title?: string) => void): () => void;
|
||||
getSize(): { rows: number; cols: number };
|
||||
getState(): TerminalState;
|
||||
@@ -47,6 +52,23 @@ export interface TerminalSession {
|
||||
killAndWait(options?: { gracefulTimeoutMs?: number; forceTimeoutMs?: number }): Promise<void>;
|
||||
}
|
||||
|
||||
function parseCommandFinishedOsc(data: string): TerminalCommandFinishedInfo | null {
|
||||
// OSC 633 is terminal control traffic, but a foreground command can still
|
||||
// print arbitrary control bytes. Keep this boundary to the exact VS Code
|
||||
// command-finished shape emitted by our shell integration.
|
||||
const parts = data.split(";");
|
||||
if (parts[0] !== "D") {
|
||||
return null;
|
||||
}
|
||||
if (parts.length === 1) {
|
||||
return { exitCode: null };
|
||||
}
|
||||
if (parts.length !== 2 || !/^-?\d+$/.test(parts[1])) {
|
||||
return null;
|
||||
}
|
||||
return { exitCode: Number(parts[1]) };
|
||||
}
|
||||
|
||||
export interface CreateTerminalOptions {
|
||||
id?: string;
|
||||
cwd: string;
|
||||
@@ -55,6 +77,7 @@ export interface CreateTerminalOptions {
|
||||
rows?: number;
|
||||
cols?: number;
|
||||
name?: string;
|
||||
title?: string;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
}
|
||||
@@ -516,6 +539,7 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
|
||||
rows = 24,
|
||||
cols = 80,
|
||||
name = "Terminal",
|
||||
title: presetTitle,
|
||||
command,
|
||||
args = [],
|
||||
} = options;
|
||||
@@ -524,6 +548,7 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
|
||||
const id = options.id ?? randomUUID();
|
||||
const listeners = new Set<(msg: ServerMessage) => void>();
|
||||
const exitListeners = new Set<(info: TerminalExitInfo) => void>();
|
||||
const commandFinishedListeners = new Set<(info: TerminalCommandFinishedInfo) => void>();
|
||||
const titleChangeListeners = new Set<(title?: string) => void>();
|
||||
let killed = false;
|
||||
let disposed = false;
|
||||
@@ -578,10 +603,12 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
|
||||
}
|
||||
}
|
||||
|
||||
const initialTitle = command
|
||||
? (humanizeProcessTitle([command, ...args].join(" ")) ??
|
||||
normalizeProcessTitle([command, ...args].join(" ")))
|
||||
: undefined;
|
||||
const lockedTitle = presetTitle?.trim() || undefined;
|
||||
const processTitle = command ? [command, ...args].join(" ") : null;
|
||||
let initialTitle = lockedTitle;
|
||||
if (!initialTitle && processTitle) {
|
||||
initialTitle = humanizeProcessTitle(processTitle) ?? normalizeProcessTitle(processTitle);
|
||||
}
|
||||
emitTitleChange(initialTitle);
|
||||
|
||||
// Respond to DA1 queries (CSI c or CSI 0 c) — apps like nvim query terminal capabilities
|
||||
@@ -593,18 +620,37 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
|
||||
return false;
|
||||
});
|
||||
|
||||
const disposeTitleChangeSubscription = terminal.onTitleChange((nextTitle) => {
|
||||
if (disposed || killed) {
|
||||
return;
|
||||
let disposeTitleChangeSubscription: { dispose(): void } | null = null;
|
||||
if (!lockedTitle) {
|
||||
disposeTitleChangeSubscription = terminal.onTitleChange((nextTitle) => {
|
||||
if (disposed || killed) {
|
||||
return;
|
||||
}
|
||||
pendingTitle = nextTitle.trim().length > 0 ? nextTitle : undefined;
|
||||
if (titleDebounceTimer) {
|
||||
clearTimeout(titleDebounceTimer);
|
||||
}
|
||||
titleDebounceTimer = setTimeout(() => {
|
||||
titleDebounceTimer = null;
|
||||
emitTitleChange(pendingTitle);
|
||||
}, TERMINAL_TITLE_DEBOUNCE_MS);
|
||||
});
|
||||
}
|
||||
|
||||
const disposeCommandLifecycleSubscription = terminal.parser.registerOscHandler(633, (data) => {
|
||||
const commandFinished = parseCommandFinishedOsc(data);
|
||||
if (!commandFinished) {
|
||||
return true;
|
||||
}
|
||||
pendingTitle = nextTitle.trim().length > 0 ? nextTitle : undefined;
|
||||
if (titleDebounceTimer) {
|
||||
clearTimeout(titleDebounceTimer);
|
||||
|
||||
for (const listener of Array.from(commandFinishedListeners)) {
|
||||
try {
|
||||
listener(commandFinished);
|
||||
} catch {
|
||||
// no-op
|
||||
}
|
||||
}
|
||||
titleDebounceTimer = setTimeout(() => {
|
||||
titleDebounceTimer = null;
|
||||
emitTitleChange(pendingTitle);
|
||||
}, TERMINAL_TITLE_DEBOUNCE_MS);
|
||||
return true;
|
||||
});
|
||||
|
||||
function buildExitInfo(input?: {
|
||||
@@ -647,10 +693,12 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
|
||||
clearTimeout(titleDebounceTimer);
|
||||
titleDebounceTimer = null;
|
||||
}
|
||||
disposeTitleChangeSubscription.dispose();
|
||||
disposeTitleChangeSubscription?.dispose();
|
||||
disposeCommandLifecycleSubscription.dispose();
|
||||
terminal.dispose();
|
||||
listeners.clear();
|
||||
exitListeners.clear();
|
||||
commandFinishedListeners.clear();
|
||||
titleChangeListeners.clear();
|
||||
}
|
||||
|
||||
@@ -759,6 +807,13 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
|
||||
};
|
||||
}
|
||||
|
||||
function onCommandFinished(listener: (info: TerminalCommandFinishedInfo) => void): () => void {
|
||||
commandFinishedListeners.add(listener);
|
||||
return () => {
|
||||
commandFinishedListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
function onTitleChange(listener: (title?: string) => void): () => void {
|
||||
titleChangeListeners.add(listener);
|
||||
if (title !== undefined) {
|
||||
@@ -854,6 +909,7 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
|
||||
send,
|
||||
subscribe,
|
||||
onExit,
|
||||
onCommandFinished,
|
||||
onTitleChange,
|
||||
getSize,
|
||||
getState,
|
||||
|
||||
Reference in New Issue
Block a user