Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/design/immediate-auto-update-relaunch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Immediate Automatic Update Relaunch

## Problem

Updating a global installation in place while the interactive CLI is running
removes content-hashed chunks that the old process may still import. Deferring
the install until the user exits avoids that corruption, but delays every
automatic update and reopens a session the user intentionally closed.

## Design

Reuse the existing update relaunch handoff:

1. The post-render update check discovers an installable update.
2. The UI exits with the update relaunch code after normal cleanup. If a model
or tool turn, prompt or automatic-notification queue, slash command, or
unsent draft is active, it waits for a safe idle boundary.
3. The supervisor rechecks and installs the update after the child is gone.
4. The stable launcher starts the updated CLI with the original options and
resumes the exact durable session without replaying the initial prompt. For
a session with no recorded messages, the handoff independently records
whether the initial prompt was already consumed: an unconsumed prompt still
runs, while an executed slash or shell command is not replayed.

The production wrapper supplies an explicit capability marker only after it
resolves a stable launcher, plus a private handoff file for the session ID.
Container and macOS sandboxes receive the same handoff. If no stable launcher
is available, or a conversation cannot be resumed because recording is
disabled or failed, keep the current manual guidance. Custom or manually
managed sandbox hosts remain manual. Windows standalone installs download in
the background but apply after exit because the running executable is locked.

## Non-goals

This does not hot-swap modules in a running process or introduce versioned
installation directories.
132 changes: 129 additions & 3 deletions packages/cli/src/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,11 +394,11 @@ describe('bootstrap import boundaries', () => {
);
writeFileSync(
path.join(oldDir, 'cli.js'),
`import { chmodSync, rmSync, writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(binPath)}, ${JSON.stringify(`#!/bin/sh\nexec "${process.execPath}" "${path.join(newDir, 'entry.mjs')}" "$@"\n`)});\nchmodSync(${JSON.stringify(binPath)}, 0o755);\nrmSync(${JSON.stringify(oldDir)}, { recursive: true, force: true });\nprocess.exit(44);\n`,
`import { chmodSync, rmSync, writeFileSync } from 'node:fs';\nwriteFileSync(process.env.QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH, JSON.stringify({ sessionId: '123e4567-e89b-12d3-a456-426614174000' }));\nwriteFileSync(${JSON.stringify(binPath)}, ${JSON.stringify(`#!/bin/sh\nexec "${process.execPath}" "${path.join(newDir, 'entry.mjs')}" "$@"\n`)});\nchmodSync(${JSON.stringify(binPath)}, 0o755);\nrmSync(${JSON.stringify(oldDir)}, { recursive: true, force: true });\nprocess.exit(44);\n`,
);
writeFileSync(
path.join(newDir, 'cli.js'),
"process.stdout.write(`${JSON.stringify({ args: process.argv.slice(2), skip: process.env.QWEN_CODE_SKIP_UPDATE_CHECK_ONCE, hasLauncherPid: /^\\d+$/.test(process.env.QWEN_CODE_LAUNCHER_PID ?? ''), launcherPath: process.env.QWEN_CODE_LAUNCHER_PATH })}\\n`);\n",
"process.stdout.write(`${JSON.stringify({ args: process.argv.slice(2), skip: process.env.QWEN_CODE_SKIP_UPDATE_CHECK_ONCE, skipPrompt: process.env.QWEN_CODE_SKIP_INITIAL_PROMPT_ONCE, hasLauncherPid: /^\\d+$/.test(process.env.QWEN_CODE_LAUNCHER_PID ?? ''), launcherPath: process.env.QWEN_CODE_LAUNCHER_PATH })}\\n`);\n",
);
writeFileSync(
binPath,
Expand All @@ -420,8 +420,14 @@ describe('bootstrap import boundaries', () => {
});

expect(JSON.parse(output)).toEqual({
args: ['--prompt', 'a&b'],
args: [
'--prompt',
'a&b',
'--resume',
'123e4567-e89b-12d3-a456-426614174000',
],
skip: 'true',
skipPrompt: 'true',
hasLauncherPid: true,
});
} finally {
Expand All @@ -430,6 +436,126 @@ describe('bootstrap import boundaries', () => {
}
});

it('relaunches a fresh session without forcing resume or skipping its prompt', () => {
const tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-cli-fresh-update-'));
const oldDir = path.join(tempDir, 'old');
const newDir = path.join(tempDir, 'new');
const binPath = path.join(tempDir, 'qwen');
try {
mkdirSync(oldDir);
mkdirSync(newDir);
copyFileSync(
'../../scripts/cli-entry.js',
path.join(oldDir, 'entry.mjs'),
);
copyFileSync(
'../../scripts/cli-entry.js',
path.join(newDir, 'entry.mjs'),
);
writeFileSync(
path.join(oldDir, 'cli.js'),
`import { chmodSync, writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(binPath)}, ${JSON.stringify(`#!/bin/sh\nexec "${process.execPath}" "${path.join(newDir, 'entry.mjs')}" "$@"\n`)});\nchmodSync(${JSON.stringify(binPath)}, 0o755);\nprocess.exit(44);\n`,
);
writeFileSync(
path.join(newDir, 'cli.js'),
'process.stdout.write(JSON.stringify({ args: process.argv.slice(2), skipPrompt: process.env.QWEN_CODE_SKIP_INITIAL_PROMPT_ONCE }));\n',
);
writeFileSync(
binPath,
`#!/bin/sh\nexec "${process.execPath}" "${path.join(oldDir, 'entry.mjs')}" "$@"\n`,
);
chmodSync(binPath, 0o755);

const output = execFileSync(binPath, ['--prompt-interactive', 'hello'], {
encoding: 'utf8',
env: {
...process.env,
PATH: `${tempDir}${path.delimiter}${process.env['PATH'] ?? ''}`,
},
});

expect(JSON.parse(output)).toEqual({
args: ['--prompt-interactive', 'hello'],
});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});

it('does not replay a consumed initial command in a fresh session', () => {
const tempDir = mkdtempSync(
path.join(tmpdir(), 'qwen-cli-command-update-'),
);
const oldDir = path.join(tempDir, 'old');
const newDir = path.join(tempDir, 'new');
const binPath = path.join(tempDir, 'qwen');
try {
mkdirSync(oldDir);
mkdirSync(newDir);
copyFileSync(
'../../scripts/cli-entry.js',
path.join(oldDir, 'entry.mjs'),
);
copyFileSync(
'../../scripts/cli-entry.js',
path.join(newDir, 'entry.mjs'),
);
writeFileSync(
path.join(oldDir, 'cli.js'),
`import { chmodSync, writeFileSync } from 'node:fs';\nwriteFileSync(process.env.QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH, JSON.stringify({ skipInitialPrompt: true }));\nwriteFileSync(${JSON.stringify(binPath)}, ${JSON.stringify(`#!/bin/sh\nexec "${process.execPath}" "${path.join(newDir, 'entry.mjs')}" "$@"\n`)});\nchmodSync(${JSON.stringify(binPath)}, 0o755);\nprocess.exit(44);\n`,
);
writeFileSync(
path.join(newDir, 'cli.js'),
'process.stdout.write(JSON.stringify({ args: process.argv.slice(2), skipPrompt: process.env.QWEN_CODE_SKIP_INITIAL_PROMPT_ONCE }));\n',
);
writeFileSync(
binPath,
`#!/bin/sh\nexec "${process.execPath}" "${path.join(oldDir, 'entry.mjs')}" "$@"\n`,
);
chmodSync(binPath, 0o755);

const output = execFileSync(
binPath,
['--prompt-interactive', '/update'],
{
encoding: 'utf8',
env: {
...process.env,
PATH: `${tempDir}${path.delimiter}${process.env['PATH'] ?? ''}`,
},
},
);

expect(JSON.parse(output)).toEqual({
args: ['--prompt-interactive', '/update'],
skipPrompt: 'true',
});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});

it('does not advertise update relaunch without a stable launcher', () => {
const tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-cli-no-launcher-'));
const entryPath = path.join(tempDir, 'entry.mjs');
try {
copyFileSync('../../scripts/cli-entry.js', entryPath);
writeFileSync(
path.join(tempDir, 'cli.js'),
'process.stdout.write(JSON.stringify({ supported: process.env.QWEN_CODE_UPDATE_RELAUNCH_SUPPORTED, statePath: process.env.QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH }));\n',
);

const output = execFileSync(process.execPath, [entryPath], {
encoding: 'utf8',
env: { ...process.env, PATH: '' },
});

expect(JSON.parse(output)).toEqual({});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});

it('does not pass the standalone launcher hint to child processes', () => {
const tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-cli-launcher-env-'));
const entryPath = path.join(tempDir, 'entry.mjs');
Expand Down
78 changes: 77 additions & 1 deletion packages/cli/src/gemini.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
type MockInstance,
} from 'vitest';
import { readFileSync } from 'node:fs';
import os from 'node:os';
import {
createNonInteractivePromptId,
main,
Expand Down Expand Up @@ -885,9 +886,22 @@ describe('gemini.tsx main function', () => {
argv: string[],
sessionId = '123e4567-e89b-12d3-a456-426614174000',
command: 'docker' | 'podman' | 'sandbox-exec' = 'sandbox-exec',
hasUpdateSupervisor = true,
): Promise<string[]> => {
const originalArgv = process.argv;
const originalUpdateSupported =
process.env['QWEN_CODE_UPDATE_RELAUNCH_SUPPORTED'];
const originalUpdateStatePath =
process.env['QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH'];
process.argv = argv;
if (hasUpdateSupervisor) {
process.env['QWEN_CODE_UPDATE_RELAUNCH_SUPPORTED'] = 'true';
process.env['QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH'] =
'/tmp/qwen-update-state.json';
} else {
delete process.env['QWEN_CODE_UPDATE_RELAUNCH_SUPPORTED'];
delete process.env['QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH'];
}
const processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation((code) => {
Expand Down Expand Up @@ -939,6 +953,18 @@ describe('gemini.tsx main function', () => {
}
} finally {
process.argv = originalArgv;
if (originalUpdateSupported === undefined) {
delete process.env['QWEN_CODE_UPDATE_RELAUNCH_SUPPORTED'];
} else {
process.env['QWEN_CODE_UPDATE_RELAUNCH_SUPPORTED'] =
originalUpdateSupported;
}
if (originalUpdateStatePath === undefined) {
delete process.env['QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH'];
} else {
process.env['QWEN_CODE_UPDATE_RELAUNCH_STATE_PATH'] =
originalUpdateStatePath;
}
processExitSpy.mockRestore();
}

Expand Down Expand Up @@ -969,7 +995,10 @@ describe('gemini.tsx main function', () => {

await expect(options?.onUpdateRelaunch?.()).resolves.toBe(44);

expect(mockUpdateBeforeRelaunch).toHaveBeenCalledTimes(1);
expect(mockUpdateBeforeRelaunch).toHaveBeenCalledWith(
expect.anything(),
expect.any(String),
);
});

it('passes host update capability into a container sandbox', async () => {
Expand All @@ -996,6 +1025,53 @@ describe('gemini.tsx main function', () => {
}
});

it('does not advertise host update relaunch without a stable launcher', async () => {
const originalCapability = process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH'];

try {
await runSandboxRelaunch(
['node', 'script.js', '--debug', '-p', 'hello'],
'',
'docker',
false,
);

expect(process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH']).toBe('false');
} finally {
if (originalCapability === undefined) {
delete process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH'];
} else {
process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH'] = originalCapability;
}
}
});

it('keeps Windows standalone host updates deferred', async () => {
const originalCapability = process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH'];
const platformSpy = vi.spyOn(os, 'platform').mockReturnValue('win32');
mockGetInstallationInfo.mockReturnValue({
isStandalone: true,
standaloneDir: 'C:\\qwen-code',
});

try {
await runSandboxRelaunch(
['node', 'script.js', '--debug', '-p', 'hello'],
'',
'docker',
);

expect(process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH']).toBe('false');
} finally {
platformSpy.mockRestore();
if (originalCapability === undefined) {
delete process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH'];
} else {
process.env['QWEN_CODE_HOST_UPDATE_RELAUNCH'] = originalCapability;
}
}
});

it('does not pass an empty session ID into the sandbox child process', async () => {
const sandboxArgs = await runSandboxRelaunch(
['node', 'script.js', '--debug', '-p', 'hello'],
Expand Down
21 changes: 18 additions & 3 deletions packages/cli/src/gemini.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ import { initializeLlmOutputLanguage } from './utils/languageUtils.js';
import {
CUSTOM_SANDBOX_IMAGE_ENV_VAR,
HOST_UPDATE_RELAUNCH_ENV_VAR,
SKIP_INITIAL_PROMPT_ENV_VAR,
UPDATE_COMPLETE_EXIT_CODE,
canRelaunchForUpdate,
} from './utils/processUtils.js';
import { getInstallationInfo } from './utils/installationInfo.js';

Expand Down Expand Up @@ -295,6 +297,17 @@ export async function main() {

markAcpStartup('argsParseStart');
let argv = await parseArguments();
if (process.env[SKIP_INITIAL_PROMPT_ENV_VAR] === 'true') {
if (process.env['QWEN_CODE_NO_RELAUNCH'] || process.env['SANDBOX']) {
delete process.env[SKIP_INITIAL_PROMPT_ENV_VAR];
}
Comment on lines +300 to +303

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] The main() function's consumption of SKIP_INITIAL_PROMPT_ENV_VAR (clearing prompt, promptInteractive, query) has no test. Entry-point propagation is tested in cli.test.ts and sandbox passthrough in sandbox.test.ts, but the actual prompt-clearing behaviour in main() is unexercised. — Concrete cost: if a future refactor drops query: undefined (or the entire block), a relaunched session would re-execute the original --query or --prompt argument despite the supervisor signalling it was already consumed. No test would catch this regression.

— qwen3.8-max-preview via Qwen Code /review

argv = {
...argv,
prompt: undefined,
promptInteractive: undefined,
query: undefined,
};
}
markAcpStartup('argsParseEnd');
profileCheckpoint('after_parse_arguments');

Expand Down Expand Up @@ -430,9 +443,11 @@ export async function main() {
const hostInstallationInfo = getInstallationInfo(updateProjectRoot, true);
process.env[HOST_UPDATE_RELAUNCH_ENV_VAR] = String(
Boolean(
hostInstallationInfo.updateCommand ||
(hostInstallationInfo.isStandalone &&
hostInstallationInfo.standaloneDir),
canRelaunchForUpdate() &&
(hostInstallationInfo.updateCommand ||
(hostInstallationInfo.isStandalone &&
hostInstallationInfo.standaloneDir &&
os.platform() !== 'win32')),
),
);
}
Expand Down
4 changes: 0 additions & 4 deletions packages/cli/src/i18n/locales/ca.js
Original file line number Diff line number Diff line change
Expand Up @@ -2145,10 +2145,6 @@ export default {
'Aquesta sessió utilitza la imatge de sandbox personalitzada {{image}}. Actualitzeu la imatge i reinicieu Qwen Code.',
'Update Qwen Code on the host, then restart the sandbox.':
"Actualitzeu Qwen Code a l'amfitrió i reinicieu l'entorn aïllat.",
'The update will be installed after you exit this session.':
"L'actualització s'instal·larà després de sortir d'aquesta sessió.",
'Run /update to install the update on the host.':
"Executeu /update per instal·lar l'actualització a l'amfitrió.",
'Run /update to install the update.':
"Executeu /update per instal·lar l'actualització.",

Expand Down
4 changes: 0 additions & 4 deletions packages/cli/src/i18n/locales/de.js
Original file line number Diff line number Diff line change
Expand Up @@ -2189,10 +2189,6 @@ export default {
'Diese Sitzung verwendet das benutzerdefinierte Sandbox-Image {{image}}. Aktualisieren Sie das Image und starten Sie Qwen Code neu.',
'Update Qwen Code on the host, then restart the sandbox.':
'Aktualisieren Sie Qwen Code auf dem Host und starten Sie anschließend die Sandbox neu.',
'The update will be installed after you exit this session.':
'Das Update wird nach dem Beenden dieser Sitzung installiert.',
'Run /update to install the update on the host.':
'Führen Sie /update aus, um das Update auf dem Host zu installieren.',
'Run /update to install the update.':
'Führen Sie /update aus, um das Update zu installieren.',

Expand Down
4 changes: 0 additions & 4 deletions packages/cli/src/i18n/locales/en.js
Original file line number Diff line number Diff line change
Expand Up @@ -2646,10 +2646,6 @@ export default {
'This session uses the custom sandbox image {{image}}. Update that image and restart Qwen Code.',
'Update Qwen Code on the host, then restart the sandbox.':
'Update Qwen Code on the host, then restart the sandbox.',
'The update will be installed after you exit this session.':
'The update will be installed after you exit this session.',
'Run /update to install the update on the host.':
'Run /update to install the update on the host.',
'Run /update to install the update.': 'Run /update to install the update.',
'⚠️ History gap: earlier conversation was lost before this point (storage interruption) and could not be recovered.':
'⚠️ History gap: earlier conversation was lost before this point (storage interruption) and could not be recovered.',
Expand Down
4 changes: 0 additions & 4 deletions packages/cli/src/i18n/locales/fr.js
Original file line number Diff line number Diff line change
Expand Up @@ -2192,10 +2192,6 @@ export default {
'Cette session utilise l’image de bac à sable personnalisée {{image}}. Mettez à jour l’image et redémarrez Qwen Code.',
'Update Qwen Code on the host, then restart the sandbox.':
'Mettez à jour Qwen Code sur l’hôte, puis redémarrez le bac à sable.',
'The update will be installed after you exit this session.':
'La mise à jour sera installée après la fermeture de cette session.',
'Run /update to install the update on the host.':
'Exécutez /update pour installer la mise à jour sur l’hôte.',
'Run /update to install the update.':
'Exécutez /update pour installer la mise à jour.',

Expand Down
Loading
Loading