Skip to content
Merged
104 changes: 104 additions & 0 deletions client/e2e/native-file-quit-relaunch.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'use strict';

// Real Electron relaunch with controlled open-file delivery and cleanup delay.
// This does not simulate macOS Finder itself or start a model/Hub/user profile.
const fs = require('node:fs'), path = require('node:path'), os = require('node:os');
const { spawn } = require('node:child_process');
const assert = require('node:assert/strict');
const electron = require('electron');
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

if (typeof electron === 'string') {
(async () => {
const output = path.resolve(process.argv[2] || '../outputs/native-file-quit-relaunch');
fs.mkdirSync(output, { recursive: true });
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'soduwork-native-file-quit-'));
fs.writeFileSync(path.join(root, 'probe.json'), JSON.stringify({ nativeFileQuit: true }));
const log = fs.openSync(path.join(output, 'probe.log'), 'w');
const env = { ...process.env };
delete env.ELECTRON_RUN_AS_NODE; delete env.NODE_OPTIONS;
const original = spawn(electron, [__filename, '--native-file-probe-root', root,
'--soduwork-open-file', path.join(root, 'earlier.txt')],
{ env, windowsHide: true, stdio: ['ignore', log, log] });
let launchError;
original.once('error', error => { launchError = error; });
async function waitFor(name) {
const filename = path.join(root, name + '.json'), started = Date.now();
while (!fs.existsSync(filename)) {
if (launchError) throw launchError;
if (Date.now() - started > 20000) throw Error('Timed out waiting for ' + name);
await delay(40);
}
return JSON.parse(fs.readFileSync(filename, 'utf8'));
}
try {
await waitFor('stopping');
const a = path.join(root, '材料 & first.txt'), b = path.join(root, 'second.txt');
fs.writeFileSync(path.join(root, 'requests.pending'), JSON.stringify([a, b, a]));
fs.renameSync(path.join(root, 'requests.pending'), path.join(root, 'requests.json'));
const restarted = await waitFor('restarted');
await waitFor('finished');
const events = fs.readFileSync(path.join(root, 'events.jsonl'), 'utf8').trim().split('\n').map(JSON.parse);
assert.notEqual(restarted.pid, original.pid);
assert.deepEqual(restarted.files, [a, b]);
assert.equal(events.filter(row => row.event === 'open-file').length, 3);
assert.equal(events.filter(row => row.event === 'relaunch').length, 1);
assert.ok(!events.some(row => row.event === 'exiting-workspace'));
const report = { ok: true, nativeElectron: true, syntheticCleanup: true,
syntheticNativeFileEvents: true, root, files: restarted.files, events };
fs.writeFileSync(path.join(output, 'report.json'), JSON.stringify(report, null, 2));
console.log(JSON.stringify({ ok: true, files: restarted.files.length, output }));
} finally {
if (original.exitCode === null) original.kill();
fs.closeSync(log);
}
})().catch(error => { console.error(error); process.exitCode = 1; });
} else {
const { app, BrowserWindow } = electron;
const root = process.argv[process.argv.indexOf('--native-file-probe-root') + 1];
if (!root || !fs.existsSync(path.join(root, 'probe.json'))) throw Error('Missing isolated native-file probe root');
app.setPath('userData', path.join(root, 'profile'));
const files = require('../main/file-open.cjs');
const record = event => fs.appendFileSync(path.join(root, 'events.jsonl'), JSON.stringify({ event, pid: process.pid }) + '\n');
const write = (name, data) => fs.writeFileSync(path.join(root, name + '.json'), JSON.stringify(data));
const watchdog = setTimeout(() => app.exit(2), 15000); watchdog.unref();
if (!app.requestSingleInstanceLock(files.instanceData(process.argv, process.cwd(), false))) app.quit();
else if (fs.existsSync(path.join(root, 'stopping.json'))) {
app.whenReady().then(async () => {
const win = new BrowserWindow({ show: false });
await win.loadURL('data:text/html,<title>Native file restart</title>');
write('restarted', { pid: process.pid, files: files.commandFiles(process.argv, process.cwd(), false) });
app.once('quit', () => write('finished', { pid: process.pid })); app.quit();
}).catch(error => { console.error(error); app.exit(2); });
} else {
const state = require('../main/quit-relaunch.cjs').create(app);
files.create({ app, ipcMain: { handle() {} }, getWorkspace: () => null,
revealWorkspace: () => record('exiting-workspace'), identityOf: async () => null, ownerOf: () => '',
deferLaunch: requested => state.deferLaunch(requested) });
const relaunch = app.relaunch.bind(app);
app.relaunch = options => { record('relaunch'); return relaunch(options); };
const poll = setInterval(() => {
const filename = path.join(root, 'requests.json');
if (!fs.existsSync(filename)) return;
clearInterval(poll);
for (const file of JSON.parse(fs.readFileSync(filename, 'utf8'))) {
record('open-file'); app.emit('open-file', { preventDefault() {} }, file);
}
}, 40);
poll.unref();
let cleanupReady = false, timer;
app.on('before-quit', event => {
if (cleanupReady) return;
event.preventDefault();
if (!timer) {
write('stopping', { pid: process.pid });
timer = setTimeout(() => { cleanupReady = true; app.quit(); }, 2500);
}
});
app.whenReady().then(async () => {
const win = new BrowserWindow({ show: false });
await win.loadURL('data:text/html,<title>Native file shutdown</title>');
state.markQuitting(); app.quit();
}).catch(error => { console.error(error); app.exit(2); });
}
}
59 changes: 39 additions & 20 deletions client/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const _distribution = require('./main/distribution.cjs');
* Set it before any userData path consumers.
*/
require('./main/userdata-path.cjs').initializeUserData(app);
require('./main/requirement-diagnostics.cjs').install({app,ipcMain});
if (require('./main/keychain-startup.cjs').dispatch({ app, BrowserWindow, shell, nativeImage })) return;
const _hubEndpoint = require('./main/hub-endpoint.cjs');
_hubEndpoint.initialize(app);
Expand Down Expand Up @@ -111,7 +112,6 @@ process.on('unhandledRejection', (reason) => {
console.error('[SoduWork] unhandled rejection (kept alive):', reason && reason.stack || reason);
});

_deviceAuth.install({ app, ipcMain, safeStorage });
require('./main/client-domain-cache.cjs').install({ app, ipcMain, webContents, deviceAuth: _deviceAuth,
modelsChanged: () => _catalogChanges.changed() });
require('./main/read-aloud.cjs').install({ app, ipcMain, BrowserWindow, getRendererRoot: rendererRoot });
Expand All @@ -128,7 +128,6 @@ const _applicationMenu = require('./main/app-menu-info.cjs').install({ app, ipcM
const _workspaceTitlebar = require('./main/workspace-titlebar.cjs').create({ app, ipcMain, BrowserWindow, Menu,
getRendererRoot: rendererRoot, fallbackCommand: _applicationMenu.nativeCommand,
getWorkspace: () => { openDeskWindow({ panel: 'workspace' }, null); return _workWindows.get('workspace'); } });
_runnerRuntime.install({ app, ipcMain, identityOf: _deviceAuth.identity });
require('./main/agent-runtime/custom-runtimes.cjs').install({ app, ipcMain, session: _piSessions,
runner: _runnerRuntime, BrowserWindow, dialog, changed: _catalogChanges.changed });
async function _sessionIdentity(appRef, hub = '', clientId = '') {
Expand Down Expand Up @@ -180,7 +179,14 @@ _workPreview.install({ ipcMain, BrowserWindow, WebContentsView, screen, shell, a
require('./main/app-settings-ipc.cjs').install({ app, ipcMain, safeStorage,
identityOf: _deviceAuth.authenticatedIdentity,
ownerOf: () => { const id = _deviceAuth.identity(app), owner = _deviceAuth.localOwner(app); return id && owner ? id.hub + ':' + owner : ''; } });
require('./main/local-model-ipc.cjs').install({ app, ipcMain, safeStorage });
require('./main/local-model-ipc.cjs').install({ app, ipcMain, safeStorage, changed: _catalogChanges.changed });
require('./main/local-agent-model-ipc.cjs').install({ app, ipcMain, safeStorage, changed: _catalogChanges.changed,
probeAgent: options => require('./main/local-agent-probe.cjs').run({ ...options, runner: _runnerRuntime }),
scopeOf: () => {
const id = _deviceAuth.identity(app), owner = _deviceAuth.localOwner(app);
return id && owner ? { hub: id.hub, clientId: id.clientId, owner } : null;
} });
require('./main/local-automation-model-ipc.cjs').install({ app, ipcMain, safeStorage, identityOf: _sessionIdentity });
_attachmentFiles.install({ app, ipcMain, BrowserWindow, dialog, net, shell, identityOf: _deviceAuth.identity,
authenticatedIdentityOf: _deviceAuth.authenticatedIdentity });
require('./main/acceptance-summary-export.cjs').install({ app, ipcMain, BrowserWindow, dialog,
Expand Down Expand Up @@ -289,6 +295,8 @@ const _fileOpen = _fileOpenModule.create({
},
identityOf: () => _sessionIdentity(app),
ownerOf: require('./main/platform-connections/runtime.cjs').connectionScope,
// macOS can send files before ready, before the quit state below is initialized.
deferLaunch: files => app.isReady() && _quitRelaunch.deferLaunch(files),
});


Expand Down Expand Up @@ -585,10 +593,19 @@ function _trayMenu() {
];
}

const _quitRelaunch = require('./main/quit-relaunch.cjs').create(app);

function _quitSoduWork(reason) {
_quitRelaunch.markQuitting();
if (tray) { tray.destroy(); tray = null; }
_lifecycleDiagnostics.setExitReason(reason);
app.quit();
if (reason === 'tray') {
// Background cleanup can defer quit. Let windows run their normal close handlers now.
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) win.close();
}
}
}

function createTray() {
Expand Down Expand Up @@ -624,28 +641,29 @@ if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', (_event, argv, workingDirectory, additionalData) => {
if (_linuxStartup.focusRecovery(app)) return;
if (_fileOpen.enqueue(_fileOpenModule.instanceFiles(
argv, workingDirectory, app.isPackaged, additionalData))) return;
// Reveal the existing instance even when minimized or hidden.
if (!_desktopOverlay.window || _desktopOverlay.window.isDestroyed()) { _desktopOverlay.createWindow(); return; }
if (_desktopOverlay.emergency && typeof _desktopOverlay.recoverFromEmergency === 'function') { _desktopOverlay.recoverFromEmergency(); return; }
if (_desktopOverlay.window.isMinimized()) _desktopOverlay.window.restore();
if (!_desktopOverlay.window.isVisible()) _desktopOverlay.window.show();
_desktopOverlay.window.focus();
if (!_quitRelaunch.quitting && _linuxStartup.focusRecovery(app)) return;
const files = _fileOpenModule.instanceFiles(argv, workingDirectory, app.isPackaged, additionalData);
// A window opened now would close with this exiting process.
if (_quitRelaunch.deferLaunch(files)) return;
if (_fileOpen.enqueue(files)) return;
/*
* On macOS, repeated application launches also restore the workspace; preserve the
* existing Windows activation path.
* Reopening the application always targets its workspace. The desktop overlay
* can have every entry hidden or be recovering independently; neither state
* should prevent restoring the workspace or change saved visibility preferences.
*/
if (process.platform === 'darwin') {
try { openDeskWindow({ panel: 'workspace' }, null); }
catch (e) { console.error('[second-instance] 打开主工作区失败', e); }
}
try { openDeskWindow({ panel: 'workspace' }, null); }
catch (e) { console.error('[second-instance] Failed to open workspace', e); }
});

_fileOpen.fromCommand(process.argv, process.cwd());
app.whenReady().then(() => {
if (_linuxStartup.showRecovery({ app, BrowserWindow, safeStorage })) return;
if (!_linuxStartup.showRecovery({ app, BrowserWindow, safeStorage, onUnlock: startDesktop })) startDesktop();
});

function startDesktop(credentials) {
_deviceAuth.install({ app, ipcMain, safeStorage, credentials, onAuthUnavailable: _runnerRuntime.pauseForHubChange });
_runnerRuntime.install({ app, ipcMain, identityOf: _deviceAuth.identity, sessionOf: _deviceAuth.session,
canConnect: _deviceAuth.canConnect });
/*
* Adopt the Runner-managed office engine so client probes and child processes use the same
* installation. Missing engines must not block startup.
Expand Down Expand Up @@ -708,6 +726,7 @@ if (!gotTheLock) {
app.on('activate', () => {
/* Apply this activation behavior only on macOS. */
if (process.platform === 'darwin') {
if (_quitRelaunch.deferLaunch()) return;
if (BrowserWindow.getAllWindows().length === 0) _desktopOverlay.createWindow();


Expand All @@ -728,7 +747,7 @@ if (!gotTheLock) {
_desktopOverlay.createWindow();
}
});
});
}
}

app.on('window-all-closed', () => {
Expand Down
30 changes: 27 additions & 3 deletions client/main/file-open.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,16 @@ const { pipeline } = require('node:stream/promises');
const { Transform } = require('node:stream');
const { createReadStream, createWriteStream } = require('node:fs');
const MAX_BYTES = 256 * 1024 * 1024;
const RELAUNCH_FILES = '--soduwork-relaunch-files';
const PREVIEW = /\.(?:html?|pdf|md|markdown|txt|csv|json|ya?ml|xml|js|jsx|ts|tsx|css|scss|py|java|go|rs|sql|sh|ps1|png|jpe?g|gif|webp|svg|mp4|m4v|webm|mov|ogv)$/i;

function commandFiles(argv, cwd, packaged = true) {
const args = Array.isArray(argv) ? argv : [];
const handoff = args.indexOf(RELAUNCH_FILES);
if (handoff >= 0) {
try { return normalizeFiles(JSON.parse(args[handoff + 1])); }
catch { return []; }
}
const explicit = args.indexOf('--soduwork-open-file');
const candidates = explicit >= 0 ? args.slice(explicit + 1, explicit + 2)
: args.slice(packaged ? 1 : 2).filter(value => path.isAbsolute(String(value)));
Expand All @@ -32,12 +38,28 @@ function instanceData(argv, cwd, packaged = true) {
return { soduworkOpenFiles: { version: 1, files: commandFiles(argv, cwd, packaged) } };
}

function normalizeFiles(files) {
if (!Array.isArray(files)) return [];
return [...new Set(files.slice(0, 20).filter(file =>
typeof file === 'string' && path.isAbsolute(file) && !/[\x00-\x1f]/.test(file)))];
}

// Preserve this process's startup/profile switches, but replace any previous
// handoff. Even an empty list must override files from the original launch.
function relaunchArgs(argv, files) {
const args = [];
for (let i = 1; i < argv.length; i++) {
if (argv[i] === RELAUNCH_FILES) { i++; continue; }
args.push(argv[i]);
}
return [...args, RELAUNCH_FILES, JSON.stringify(normalizeFiles(files))];
}

function instanceFiles(argv, cwd, packaged = true, additionalData) {
if (additionalData && Object.prototype.hasOwnProperty.call(additionalData, 'soduworkOpenFiles')) {
const request = additionalData.soduworkOpenFiles;
if (request?.version !== 1 || !Array.isArray(request.files)) return [];
return [...new Set(request.files.slice(0, 20).filter(file =>
typeof file === 'string' && path.isAbsolute(file) && !/[\x00-\x1f]/.test(file)))];
return normalizeFiles(request.files);
}
// Keep the legacy path conservative: never guess which trailing argument is
// the user's file rather than an Electron entry point or a profile directory.
Expand Down Expand Up @@ -67,6 +89,8 @@ function create(deps) {
if (win && !win.isDestroyed()) win.webContents.send('file-open-pending');
};
function enqueue(files) {
// The existing quit policy owns handoff; this broker must not reveal an exiting workspace.
if (deps.deferLaunch?.(files)) return 0;
for (const value of files || []) {
const file = String(value || '');
if (!file || !path.isAbsolute(file) || /[\x00-\x1f]/.test(file)) continue;
Expand Down Expand Up @@ -151,4 +175,4 @@ function create(deps) {
return { enqueue, signal, fromCommand: (argv, cwd) => enqueue(commandFiles(argv, cwd, app.isPackaged)) };
}

module.exports = { create, commandFiles, instanceData, instanceFiles, PREVIEW, MAX_BYTES };
module.exports = { create, commandFiles, instanceData, instanceFiles, relaunchArgs, normalizeFiles, PREVIEW, MAX_BYTES };
Loading
Loading