A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): replace TUI process after update (#1631)
Seth Karten083c68dc022e
diff --git a/packages/coding-agent/.changes/update-tui-in-place-relaunch.md b/packages/coding-agent/.changes/update-tui-in-place-relaunch.mdnew file mode 100644index 0000000000..fe99a3050d--- /dev/null+++ b/packages/coding-agent/.changes/update-tui-in-place-relaunch.md@@ -0,0 +1 @@+- Fixed `/update` keeping the old TUI process alive until the relaunched TUI quit by replacing the process in place on POSIX platforms running Node 26.1 and newer; Windows and IBM i keep the previous child relaunch.diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex b23ed23735..53cc14670c 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -48,6 +48,7 @@ import {launchDaemonUpdateRestartCoordinator,resolveDaemonUpdateRestartSocketPath,} from "../../cli/daemon-update-restart.js";+import { type CliSubprocessLaunchSpec, createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";import {APP_NAME,APP_TITLE,@@ -770,6 +771,53 @@ export function buildUpdateRelaunchArgs(args: readonly string[], sessionFile: streturn relaunchArgs;}+type UpdateRelaunchExecve = (file: string, args: string[], environment: Record<string, string>) => never;++interface UpdateRelaunchExecOptions {+ platform: string;+ nodeVersion: string;+ cwd: string;+ previousCwd: string;+ environment: NodeJS.ProcessEnv;+ chdir: (directory: string) => void;+ execve?: UpdateRelaunchExecve;+}++function execveFailureThrows(nodeVersion: string): boolean {+ // Before Node 26.1, a failed execve syscall aborts the process instead of throwing for the fallback below.+ const match = /^(\d+)\.(\d+)\./.exec(nodeVersion);+ if (!match) {+ return false;+ }+ const major = Number(match[1]);+ const minor = Number(match[2]);+ return major > 26 || (major === 26 && minor >= 1);+}++export function tryExecUpdateRelaunch(launch: CliSubprocessLaunchSpec, options: UpdateRelaunchExecOptions): boolean {+ // Process replacement preserves the shell job and foreground terminal without retaining the old TUI.+ if (+ !options.execve ||+ options.platform === "win32" ||+ options.platform === "os400" ||+ !execveFailureThrows(options.nodeVersion)+ ) {+ return false;+ }+ const environment = Object.fromEntries(+ Object.entries(options.environment).filter((entry): entry is [string, string] => typeof entry[1] === "string"),+ );+ options.chdir(options.cwd);+ try {+ options.execve(launch.command, [launch.command, ...launch.args], environment);+ } catch (error) {+ // A thrown execve must not leave the fallback's process on a changed cwd.+ options.chdir(options.previousCwd);+ throw error;+ }+ return true;+}+export function buildUpdateChildArgs(args: readonly string[], daemonSocketPath: string): string[] {return args.includes("--daemon-socket") ? [...args] : [...args, "--daemon-socket", daemonSocketPath];}@@ -8809,7 +8857,28 @@ export class InteractiveMode {);}}- const relaunchResult = spawnSync(process.execPath, [...process.execArgv, entrypoint, ...relaunchArgs], {+ const relaunch = createCliSubprocessLaunchSpec(relaunchArgs);+ const updateProcess = process as NodeJS.Process & { execve?: UpdateRelaunchExecve };+ try {+ if (+ tryExecUpdateRelaunch(relaunch, {+ platform: process.platform,+ nodeVersion: process.versions.node,+ cwd: updateCwd,+ previousCwd: process.cwd(),+ environment: process.env,+ chdir: (directory) => process.chdir(directory),+ execve: updateProcess.execve,+ })+ ) {+ return;+ }+ } catch (error: unknown) {+ console.error(+ `Could not replace the current ${APP_NAME} process (${error instanceof Error ? error.message : String(error)}). Falling back to a child relaunch.`,+ );+ }+ const relaunchResult = spawnSync(relaunch.command, relaunch.args, {stdio: "inherit",cwd: updateCwd,env: process.env,diff --git a/packages/coding-agent/test/interactive-update-relaunch.test.ts b/packages/coding-agent/test/interactive-update-relaunch.test.tsindex 1228efa3cd..b13e6b216d 100644--- a/packages/coding-agent/test/interactive-update-relaunch.test.ts+++ b/packages/coding-agent/test/interactive-update-relaunch.test.ts@@ -1,9 +1,29 @@-import { describe, expect, it } from "vitest";+import type * as ChildProcessModule from "child_process";+import { describe, expect, it, vi } from "vitest";+import type * as DaemonUpdateRestartModule from "../src/cli/daemon-update-restart.js";++const updateMocks = vi.hoisted(() => ({+ spawnSync: vi.fn(),+ launchCoordinator: vi.fn(),+}));++vi.mock("child_process", async (importOriginal) => ({+ ...(await importOriginal<typeof ChildProcessModule>()),+ spawnSync: updateMocks.spawnSync,+}));++vi.mock("../src/cli/daemon-update-restart.js", async (importOriginal) => ({+ ...(await importOriginal<typeof DaemonUpdateRestartModule>()),+ launchDaemonUpdateRestartCoordinator: updateMocks.launchCoordinator,+}));+import { buildDaemonUpdateRestartReport } from "../src/cli/daemon-update-restart.js";import {buildUpdateChildArgs,buildUpdateRelaunchArgs,+ InteractiveMode,resolveInteractiveUpdateDaemonSocketPath,+ tryExecUpdateRelaunch,updateArgsIncludeSelf,} from "../src/modes/interactive/interactive-mode.js";@@ -34,6 +54,209 @@ describe("buildUpdateRelaunchArgs", () => {});});+describe("tryExecUpdateRelaunch", () => {+ it("replaces the current process while preserving argv zero and the environment", () => {+ const environment = { PRIME_AGENT_CODING_AGENT_DIR: "/tmp/agent", OMITTED: undefined };+ const chdir = vi.fn();+ const execve = vi.fn(() => undefined as never);++ expect(+ tryExecUpdateRelaunch(+ { command: "/usr/bin/node", args: ["--trace-warnings", "/opt/prime-agent/cli.js", "--resume", "session"] },+ {+ platform: "darwin",+ nodeVersion: "26.1.0",+ cwd: "/tmp/project",+ previousCwd: "/tmp/before",+ environment,+ chdir,+ execve,+ },+ ),+ ).toBe(true);+ expect(chdir).toHaveBeenCalledWith("/tmp/project");+ expect(execve).toHaveBeenCalledWith(+ "/usr/bin/node",+ ["/usr/bin/node", "--trace-warnings", "/opt/prime-agent/cli.js", "--resume", "session"],+ { PRIME_AGENT_CODING_AGENT_DIR: "/tmp/agent" },+ );++ // A thrown execve restores the previous cwd before the fallback runs.+ execve.mockImplementationOnce(() => {+ throw new Error("execve failed");+ });+ expect(() =>+ tryExecUpdateRelaunch(+ { command: "/usr/bin/node", args: ["cli.js"] },+ {+ platform: "darwin",+ nodeVersion: "26.1.0",+ cwd: "/tmp/project",+ previousCwd: "/tmp/before",+ environment,+ chdir,+ execve,+ },+ ),+ ).toThrow("execve failed");+ expect(chdir).toHaveBeenLastCalledWith("/tmp/before");+ });++ it.each(["win32", "os400"])("keeps the compatible child relaunch on %s", (platform) => {+ const chdir = vi.fn();+ const execve = vi.fn(() => undefined as never);++ expect(+ tryExecUpdateRelaunch(+ { command: "node", args: ["cli.js"] },+ {+ platform,+ nodeVersion: "26.1.0",+ cwd: "/tmp/project",+ previousCwd: "/tmp/before",+ environment: {},+ chdir,+ execve,+ },+ ),+ ).toBe(false);+ expect(chdir).not.toHaveBeenCalled();+ expect(execve).not.toHaveBeenCalled();+ });++ it.each(["22.22.0", "24.13.0", "25.8.1", "26.0.0"])(+ "keeps the compatible child relaunch when execve failures abort Node %s",+ (nodeVersion) => {+ const chdir = vi.fn();+ const execve = vi.fn(() => undefined as never);++ expect(+ tryExecUpdateRelaunch(+ { command: "/usr/bin/node", args: ["cli.js"] },+ {+ platform: "linux",+ nodeVersion,+ cwd: "/tmp/project",+ previousCwd: "/tmp/before",+ environment: {},+ chdir,+ execve,+ },+ ),+ ).toBe(false);+ expect(chdir).not.toHaveBeenCalled();+ expect(execve).not.toHaveBeenCalled();+ },+ );++ it("keeps the compatible child relaunch when execve is unavailable", () => {+ expect(+ tryExecUpdateRelaunch(+ { command: "/usr/bin/node", args: ["cli.js"] },+ {+ platform: "linux",+ nodeVersion: "26.1.0",+ cwd: "/tmp/project",+ previousCwd: "/tmp/before",+ environment: {},+ chdir: vi.fn(),+ },+ ),+ ).toBe(false);+ });+});++describe("interactive self-update relaunch", () => {+ it.skipIf(process.platform === "win32")(+ "tears down and replaces the TUI process without waiting for a child TUI to quit",+ async () => {+ const events: string[] = [];+ updateMocks.spawnSync.mockReset();+ updateMocks.spawnSync.mockImplementation(() => {+ events.push("update");+ return { status: 0, signal: null } as never;+ });+ updateMocks.launchCoordinator.mockReset();+ updateMocks.launchCoordinator.mockImplementation(async () => {+ events.push("coordinator");+ return {+ version: 1,+ requestId: "test-request",+ socketPath: "/tmp/update.sock",+ phase: "complete",+ coordinator: { pid: process.pid },+ counts: { total: 0, restored: 0, resumed: 0, failed: 0 },+ failures: [],+ startedAt: "2026-08-21T00:00:00.000Z",+ updatedAt: "2026-08-21T00:00:01.000Z",+ };+ });++ const updateProcess = process as NodeJS.Process & {+ execve?: (file: string, args: string[], environment: NodeJS.ProcessEnv) => never;+ };+ const originalExecve = updateProcess.execve;+ const originalNodeVersion = Object.getOwnPropertyDescriptor(process.versions, "node");+ const execve = vi.fn((_file: string, _args: string[], _environment: NodeJS.ProcessEnv) => {+ events.push("execve");+ return undefined as never;+ });+ updateProcess.execve = execve;+ Object.defineProperty(process.versions, "node", { ...originalNodeVersion, value: "26.1.0" });++ const receiver = {+ connectionState: {+ activeSessionId: "active-session",+ sessionFile: "/tmp/session.jsonl",+ },+ fullscreenEnabled: false,+ options: {+ daemonSocketPath: "/tmp/update.sock",+ onShutdown: async () => events.push("shutdown"),+ },+ getCurrentCwd: () => process.cwd(),+ stopWorkingLoader: () => events.push("loader-stop"),+ stop: () => events.push("mode-stop"),+ ui: {+ terminal: { drainInput: async () => events.push("drain-input") },+ stop: () => events.push("ui-stop"),+ },+ agentConnection: {+ dispose: async () => events.push("connection-dispose"),+ },+ };+ const handleUpdateCommand = (+ InteractiveMode.prototype as unknown as {+ handleUpdateCommand(this: typeof receiver, args: string): Promise<void>;+ }+ ).handleUpdateCommand;++ try {+ await handleUpdateCommand.call(receiver, "");+ } finally {+ updateProcess.execve = originalExecve;+ if (originalNodeVersion) {+ Object.defineProperty(process.versions, "node", originalNodeVersion);+ }+ }++ expect(events).toEqual([+ "loader-stop",+ "drain-input",+ "ui-stop",+ "update",+ "mode-stop",+ "connection-dispose",+ "shutdown",+ "coordinator",+ "execve",+ ]);+ expect(updateMocks.spawnSync).toHaveBeenCalledTimes(1);+ expect(execve.mock.calls[0]?.[1]).toEqual(expect.arrayContaining(["--resume", "/tmp/session.jsonl"]));+ },+ );+});+describe("buildUpdateChildArgs", () => {it("passes the active custom socket to the deferred self-update child", () => {expect(buildUpdateChildArgs(["--self", "--force"], "/tmp/custom-daemon.sock")).toEqual([