Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
88 changes: 88 additions & 0 deletions packages/adapter-workbuddy/test/install-rollback.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {workbuddyWindowsPaths,workbuddyWindowsWiring} from '../../../scripts/workbuddy-windows-wiring.mjs';
import {workbuddyLinuxPaths,workbuddyLinuxWiring} from '../../../scripts/workbuddy-linux-wiring.mjs';
import {commitWorkbuddyInstall} from '../../../scripts/workbuddy-install-transaction.mjs';
import {renderWindowsStartupVbs} from '../../../scripts/portable-runtime.mjs';

function fixture(t){const root=fs.mkdtempSync(path.join(os.tmpdir(),'bc-install-tx-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));return root;}
test('late startup publication failure restores files and registry', t => {
const root = fixture(t), env = { APPDATA: root };
const paths = workbuddyWindowsPaths(env, root);
let registryValue = null;
const wiring = workbuddyWindowsWiring({
env, home: root, launcher: path.join(root, 'launcher.ps1'), journal: path.join(root, 'journal'),
registry: { read: () => registryValue, write: value => { registryValue = value; } },
replace(file, _before, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, value);
throw new Error('temporary cleanup failed');
},
});
assert.throws(() => wiring.install('9335'), /cleanup failed/);
assert.equal(fs.existsSync(paths.startup), false);
assert.equal(registryValue, null);
});

test('identical launcher contents still restore original POSIX permissions', { skip: process.platform === 'win32' }, async t => {
const root = fixture(t);
const runtime = { pointerPath: path.join(root, 'pointer'), launcher: path.join(root, 'launcher.sh') };
fs.writeFileSync(runtime.launcher, 'unchanged', { mode: 0o751 });
fs.chmodSync(runtime.launcher, 0o751);
await assert.rejects(commitWorkbuddyInstall({
runtime, expectedLauncher: 'unchanged', portFile: path.join(root, 'port'), portText: '9335',
install: () => ({ rollback() {} }), discard() {},
activate() { fs.chmodSync(runtime.launcher, 0o755); throw new Error('activation failed'); },
}), /activation failed/);
assert.equal(fs.statSync(runtime.launcher).mode & 0o777, 0o751);
});

test('preflight failures discard the candidate before any wiring', async t => {
const root = fixture(t);
let discarded = 0;
const options = {
runtime: { pointerPath: root, launcher: path.join(root, 'launcher') },
install: () => assert.fail('unexpected install'),
discard: () => { discarded++; },
};
await assert.rejects(commitWorkbuddyInstall(options), /regular file/);
await assert.rejects(commitWorkbuddyInstall({ ...options, expectedLauncher() { throw Error('render failed'); } }), /render failed/);
assert.equal(discarded, 2);
});
test('foreign startup and redirected APPDATA are checked before registry writes; later edits preserved',t=>{
const root=fixture(t),env={APPDATA:path.join(root,'redirected')},paths=workbuddyWindowsPaths(env,root);let value={value:'9000',kind:'String'};
assert.ok(paths.startup.startsWith(env.APPDATA));fs.mkdirSync(path.dirname(paths.startup),{recursive:true});fs.writeFileSync(paths.startup,'foreign');
const registry={read:()=>value,write:v=>{value=v}},journal=path.join(root,'journal');
const options={env,home:root,launcher:path.join(root,'launcher.ps1'),journal,registry};
assert.throws(()=>workbuddyWindowsWiring(options).install('9335'),/not owned/);assert.equal(value.value,'9000');
fs.unlinkSync(paths.startup);fs.writeFileSync(paths.legacy,'foreign legacy');
workbuddyWindowsWiring(options).install('9335');assert.equal(value.value,'9335');
assert.equal(fs.readFileSync(paths.legacy,'utf8'),'foreign legacy');
fs.writeFileSync(paths.startup,'user edited');assert.throws(()=>workbuddyWindowsWiring(options).remove(),/not owned/);assert.equal(value.value,'9335');
});
test('Windows startup write failure restores previous registry/journal state; successful wiring can undo',t=>{
const root=fixture(t),env={APPDATA:root};let value=null;
const registry={read:()=>value,write:v=>{value=v}},journal=path.join(root,'journal'),opts={env,home:root,launcher:path.join(root,'launcher.ps1'),journal,registry};
assert.throws(()=>workbuddyWindowsWiring({...opts,replace(){throw new Error('fixture disk full')}}).install('9335'),/disk full/);
assert.equal(value,null);assert.equal(fs.existsSync(journal),false);
const tx=workbuddyWindowsWiring(opts).install('9335');tx.rollback();assert.equal(value,null);
assert.equal(fs.existsSync(workbuddyWindowsPaths(env,root).startup),false);
});
test('Linux environment failure removes newly created autostart; rollback preserves externally changed target',t=>{
const root=fixture(t),env={XDG_CONFIG_HOME:path.join(root,'config')},paths=workbuddyLinuxPaths(env,root);fs.mkdirSync(env.XDG_CONFIG_HOME,{recursive:true});fs.writeFileSync(path.dirname(paths.environment),'block');
const opts={env,home:root,launcher:'/tmp/fixture/launcher.sh'};
assert.throws(()=>workbuddyLinuxWiring(opts).install('9335'));assert.equal(fs.existsSync(paths.desktop),false);
fs.unlinkSync(path.dirname(paths.environment));const tx=workbuddyLinuxWiring(opts).install('9335');
fs.writeFileSync(paths.environment,'external edit');assert.throws(()=>tx.rollback(),/recovery incomplete/);assert.equal(fs.readFileSync(paths.environment,'utf8'),'external edit');
});
test('runtime activation failure restores wiring, port, pointer and launcher before discarding candidate',async t=>{
const root=fixture(t),runtime={pointerPath:path.join(root,'current.json'),launcher:path.join(root,'launcher.ps1'),version:'v-new'};
const portFile=path.join(root,'port.json');fs.writeFileSync(runtime.pointerPath,'{"version":"v-old"}');fs.writeFileSync(runtime.launcher,'old launcher');fs.writeFileSync(portFile,'old port');let wired=false,discarded=false;
if(process.platform !== 'win32') fs.chmodSync(runtime.launcher, 0o751);
await assert.rejects(commitWorkbuddyInstall({runtime,expectedLauncher:'new launcher',portFile,portText:'new port',install:()=>{wired=true;return{rollback(){wired=false}}},activate:()=>{fs.writeFileSync(runtime.launcher,'new launcher');fs.writeFileSync(runtime.pointerPath,'{"version":"v-new"}');throw new Error('fixture activation')},discard:()=>{discarded=true}}),/fixture activation/);
if(process.platform !== 'win32') assert.equal(fs.statSync(runtime.launcher).mode & 0o777, 0o751);
assert.equal(wired,false);assert.equal(discarded,true);assert.equal(fs.readFileSync(runtime.pointerPath,'utf8'),'{"version":"v-old"}');assert.equal(fs.readFileSync(runtime.launcher,'utf8'),'old launcher');assert.equal(fs.readFileSync(portFile,'utf8'),'old port');
});
13 changes: 13 additions & 0 deletions packages/beauticode-desktop/test/followup-package.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
import {stageDesktopAggregate} from '../../../scripts/pack-desktop-aggregate.mjs';

test('packaged WorkBuddy wiring imports every transaction dependency without the workspace',async t=>{
const root=await fs.mkdtemp(path.join(os.tmpdir(),'bc-followup-pack-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
await stageDesktopAggregate(root,{build:false});
for(const name of ['workbuddy-windows-wiring.mjs','workbuddy-linux-wiring.mjs','workbuddy-install-transaction.mjs'])await import(pathToFileURL(path.join(root,'runtime/workbuddy/scripts',name)).href);
});
38 changes: 38 additions & 0 deletions scripts/owned-file.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';

export function readOwnedFile(file) {
try {
const stat=fs.lstatSync(file);
if(!stat.isFile() || stat.isSymbolicLink()) throw new Error('Managed target is not a regular file.');
return fs.readFileSync(file,'utf8');
} catch(error) { if(error.code==='ENOENT')return null;throw error; }
}
export function replaceOwnedFile(file, before, after, mode) {
if(readOwnedFile(file)!==before)throw new Error('Managed file changed externally; preserved.');
if(after===null){if(before!==null)fs.unlinkSync(file);return;}
fs.mkdirSync(path.dirname(file),{recursive:true});
const temporary=file+'.tmp-'+randomUUID();
fs.writeFileSync(temporary,after,{flag:'wx',mode:0o600});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
try {
if(before===null)fs.linkSync(temporary,file);
else {
if(readOwnedFile(file)!==before)throw new Error('Managed file changed externally; preserved.');
fs.chmodSync(temporary, mode ?? (fs.statSync(file).mode & 0o777));
fs.renameSync(temporary,file);
}
} finally {fs.rmSync(temporary,{force:true});}
}
// Register compensation before publication. A write can succeed before temp cleanup throws.
export function undoFileChange(file, before, published, mode) {
const current = readOwnedFile(file);
if (current === before) return;
replaceOwnedFile(file, published, before, mode);
}
export function rollbackSteps(undos, original) {
const errors=[];
for(const undo of undos.reverse())try{undo();}catch(error){errors.push(error);}
if(errors.length)throw new AggregateError([...(original?[original]:[]),...errors],'Installation failed; recovery incomplete. Saved ownership records must be retained.');
if(original)throw original;
}
2 changes: 1 addition & 1 deletion scripts/pack-desktop-aggregate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ async function copyWorkbuddyRuntime(destRoot) {
rewriteWorkbuddyRunner,
);
await copyText(path.join(repoRoot, "scripts", "quick-launch.mjs"), path.join(workbuddy, "scripts", "quick-launch.mjs"));
for (const name of ["wb-startup-media.mjs", "wb-runner-log.mjs", "wb-theme-name-diagnostic.mjs", "windows-owned-env.mjs", "workbuddy-linux-wiring.mjs", "xdg-autostart.mjs"]) {
for (const name of ["wb-startup-media.mjs", "wb-runner-log.mjs", "wb-theme-name-diagnostic.mjs", "windows-owned-env.mjs", "owned-file.mjs", "workbuddy-windows-wiring.mjs", "workbuddy-install-transaction.mjs", "workbuddy-linux-wiring.mjs", "xdg-autostart.mjs"]) {
await copyText(path.join(repoRoot, "scripts", name), path.join(workbuddy, "scripts", name));
}
await copyText(
Expand Down
54 changes: 24 additions & 30 deletions scripts/wb-setup.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@
import { spawn, spawnSync, execSync } from 'node:child_process';
import { isManagedWorkBuddyRunner, readGuardianProcess } from './guardian-process.mjs';
import fs from 'node:fs';
import { workbuddyWindowsPaths, workbuddyWindowsWiring } from './workbuddy-windows-wiring.mjs';
import { commitWorkbuddyInstall } from './workbuddy-install-transaction.mjs';
import { workbuddyLinuxPaths, workbuddyLinuxWiring } from './workbuddy-linux-wiring.mjs';
import { updateOwnedPort } from './windows-owned-env.mjs';

import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
Expand All @@ -38,14 +40,14 @@ import {
beautiCodeLocalRoot,
discardStableRuntime,
hostRuntimeRoot,
renderWindowsStartupVbs,
renderRuntimeLauncherPs1,
renderRuntimeLauncherSh,
renderXdgDesktopEntry,
resolveNodeExecutable,
stableRuntimeRoot,
startDetachedLauncher,
startupDirectory,
syncStableRuntime,
writeTextAtomic,
} from './portable-runtime.mjs';

const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
Expand Down Expand Up @@ -197,8 +199,8 @@ async function prepareStableRuntime() {
activate: false,
});
try {
await resolveNodeExecutable({ stableRoot: runtime.hostRoot });
return await activateStableRuntime(runtime, { startupLogPath: PLAT === 'linux' ? LINUX_LOG : WIN_LOG });
runtime.node = await resolveNodeExecutable({ stableRoot: runtime.hostRoot });
return runtime;
} catch (error) {
await discardStableRuntime(runtime);
throw error;
Expand All @@ -210,8 +212,7 @@ const LAUNCHER_MAC = path.join(home, 'Library/LaunchAgents/com.beauticode.wb-run
const MAC_LOG = path.join(home, 'Library/Logs/beauticode-wb-runner.log');
const STABLE_ROOT = stableRuntimeRoot(process.env, home);
const STABLE_HOST_ROOT = hostRuntimeRoot(STABLE_ROOT, 'workbuddy');
const STARTUP_VBS = path.join(home, 'AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/beauticode-wb-runner.vbs');
const LEGACY_STARTUP_VBS = path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'beauticode-wb-runner.vbs');
const STARTUP_VBS = workbuddyWindowsPaths(process.env, home).startup;
const WIN_LOG = path.join(
process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'),
'beauticode', 'logs', 'wb-runner.log',
Expand Down Expand Up @@ -241,7 +242,6 @@ const macPlist = () => `<?xml version="1.0" encoding="UTF-8"?>
<key>StandardErrorPath</key><string>${MAC_LOG}</string>
</dict></plist>`;

const winVbs = (launcher) => renderWindowsStartupVbs({ launcher, args: ['--watchdog'] });

function shSingleQuote(value) {
return `'${String(value).replace(/'/g, `'\\''`)}'`;
Expand Down Expand Up @@ -284,28 +284,14 @@ function statusMac() {
}

async function installWin(runtime) {
updateOwnedPort({ journal: path.join(DATA_DIR, 'workbuddy-env-ownership.json'), port });
const transaction = workbuddyWindowsWiring({env:process.env,home,launcher:runtime.launcher,journal:path.join(DATA_DIR,'workbuddy-env-ownership.json')}).install(port);
log(' ✓ 用户端口配置已备份、写入并回读验证');
broadcastWindowsEnvironment();
log(' ✓ 已广播环境变更(无需注销即可让后续原图标启动继承端口)');
fs.mkdirSync(path.dirname(STARTUP_VBS), { recursive: true });
const startupContent = winVbs(runtime.launcher);
let currentStartupContent = null;
try { currentStartupContent = fs.readFileSync(STARTUP_VBS, 'utf8'); }
catch (error) { if (error?.code !== 'ENOENT') throw error; }
if (currentStartupContent !== startupContent) await writeTextAtomic(STARTUP_VBS, startupContent);
if (path.resolve(LEGACY_STARTUP_VBS) !== path.resolve(STARTUP_VBS)) fs.rmSync(LEGACY_STARTUP_VBS, { force: true });
log(currentStartupContent === startupContent
? ' ✓「启动」文件夹 VBS 已是当前配置(跳过无变化替换)'
: ' ✓ 已写入「启动」文件夹 VBS(登录自启、隐藏窗口)');
if (process.env[ENV_KEY] !== port) {
log(' ⚠ 当前会话还没继承新 env:注销重登一次,或先手动带 env 启动一次 WorkBuddy');
}

/* Startup ownership and reversible file writes are handled by the wiring transaction. */
return transaction;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
function uninstallWin() {
fs.rmSync(STARTUP_VBS, { force: true });
fs.rmSync(LEGACY_STARTUP_VBS, { force: true });
const restored = updateOwnedPort({ journal: path.join(DATA_DIR, 'workbuddy-env-ownership.json'), remove: true });
const restored = workbuddyWindowsWiring({env:process.env,home,launcher:path.join(STABLE_HOST_ROOT,'launcher.ps1'),journal:path.join(DATA_DIR,'workbuddy-env-ownership.json')}).remove();
broadcastWindowsEnvironment();
log(restored === 'restored' ? ' ✓ 已拆除启动项并恢复原用户环境变量' : ' ✓ 已拆除启动项;未受本次安装管理或后来修改的环境变量已保留');
}
Expand All @@ -323,8 +309,9 @@ function statusWin() {

function installLinux(runtime) {
if (!runtime) throw new Error('Stable WorkBuddy runtime required.');
workbuddyLinuxWiring({ env: process.env, home, launcher: runtime.launcher }).install(port);
const transaction = workbuddyLinuxWiring({ env: process.env, home, launcher: runtime.launcher }).install(port);
log(' ✓ environment.d + autostart 已写入(下次登录生效;当前会话可手动 export)');
return transaction;
}
function uninstallLinux() {
workbuddyLinuxWiring({ env: process.env, home, launcher: path.join(STABLE_HOST_ROOT, 'launcher.sh') }).remove();
Expand Down Expand Up @@ -473,8 +460,15 @@ if (PACKAGED_RUNTIME) {
// the stable runtime and verified Node are ready.
log(`安装 beautiCode × WorkBuddy(${PLAT},端口 ${port}):`);
const stableRuntime = PLAT === 'win32' || PLAT === 'linux' ? await prepareStableRuntime() : null;
writeConfiguredPort(port);
if (PLAT === 'darwin') installMac(); else if (PLAT === 'win32') await installWin(stableRuntime); else installLinux(stableRuntime);
if(stableRuntime) {
await commitWorkbuddyInstall({
runtime:stableRuntime, expectedLauncher:()=>PLAT==='linux'?renderRuntimeLauncherSh({host:'workbuddy',startupLogPath:LINUX_LOG,nodePath:stableRuntime.node.path}):renderRuntimeLauncherPs1({host:'workbuddy',startupLogPath:WIN_LOG}), portFile:PORT_FILE, portText:JSON.stringify({port:Number(port)},null,2)+'\n',
install:()=>PLAT==='win32'?installWin(stableRuntime):installLinux(stableRuntime),
activate:()=>activateStableRuntime(stableRuntime,{nodePath:stableRuntime.node.path,startupLogPath:PLAT==='linux'?LINUX_LOG:WIN_LOG}),
discard:()=>discardStableRuntime(stableRuntime),
});
if (PLAT === 'win32') broadcastWindowsEnvironment();
} else { writeConfiguredPort(port); installMac(); }

startDaemon(stableRuntime);

Expand Down
51 changes: 51 additions & 0 deletions scripts/workbuddy-install-transaction.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import fs from 'node:fs';
import { readOwnedFile, replaceOwnedFile, undoFileChange } from './owned-file.mjs';

/** Keep the previous runtime active until wiring succeeds; restore only this operation's values. */
export async function commitWorkbuddyInstall({runtime,expectedLauncher,portFile,portText,install,activate,discard}) {
let before;
try {
if (typeof expectedLauncher === 'function') expectedLauncher = expectedLauncher();
const launcher = readOwnedFile(runtime.launcher);
before = {
launcher,
launcherMode: launcher === null ? undefined : fs.statSync(runtime.launcher).mode & 0o777,
pointer: readOwnedFile(runtime.pointerPath),
port: readOwnedFile(portFile),
};
} catch (error) {
await discard();
throw error;
}
let wiring, portAttempted=false, activationAttempted=false;
try {
wiring=await install();
portAttempted = true;
replaceOwnedFile(portFile,before.port,portText);
activationAttempted = true;
await activate();
} catch(error) {
const errors=[];
for(const undo of [
()=>{const current=readOwnedFile(runtime.pointerPath);if(current!==before.pointer){if(JSON.parse(current)?.version!==runtime.version)throw new Error('Runtime changed externally.');replaceOwnedFile(runtime.pointerPath,current,before.pointer);}},
()=>{
if (!activationAttempted) return;
const current = readOwnedFile(runtime.launcher);
if (current !== before.launcher) {
undoFileChange(runtime.launcher, before.launcher, expectedLauncher, before.launcherMode);
} else if (current !== null && current === expectedLauncher && process.platform !== 'win32') {
const mode = fs.statSync(runtime.launcher).mode & 0o777;
if (mode !== before.launcherMode) {
if (mode !== 0o755 && mode !== (0o666 & ~process.umask())) throw new Error('Launcher mode changed externally; preserved.');
fs.chmodSync(runtime.launcher, before.launcherMode);
}
}
},
()=>{if(portAttempted)undoFileChange(portFile,before.port,portText);},
()=>wiring?.rollback(),
])try{undo();}catch(restoreError){errors.push(restoreError);}
if(!errors.length)await discard();
if(errors.length)throw new AggregateError([error,...errors],'Installation failed; recovery incomplete. Retain runtime and ownership records.');
throw error;
}
}
Loading
Loading