Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: make managed app updates opt-in

Adam Eivy2be39335ed4f
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index 0543658395..42baf559d3 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -56,6 +56,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
apiPort: app.apiPort || '',
tlsPort: app.tlsPort || '',
buildCommand: app.buildCommand || '',
+ updateCommand: app.updateCommand || '',
startCommands: (app.startCommands || []).join('\n'),
pm2ProcessNames: (app.pm2ProcessNames || []).join(', '),
nativeLaunchEnabled: !!app.nativeLaunch,
@@ -252,6 +253,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
apiPort: formData.apiPort ? parseInt(formData.apiPort, 10) : null,
tlsPort: formData.tlsPort ? parseInt(formData.tlsPort, 10) : null,
buildCommand: formData.buildCommand || undefined,
+ updateCommand: formData.updateCommand || undefined,
startCommands: formData.startCommands.split('\n').filter(Boolean),
pm2ProcessNames: formData.pm2ProcessNames
? formData.pm2ProcessNames.split(',').map(s => s.trim()).filter(Boolean)
@@ -497,6 +499,21 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
/>
</div>
+ <div>
+ <label htmlFor="edit-app-update-command" className="block text-sm text-gray-400 mb-1">Update Command</label>
+ <input
+ id="edit-app-update-command"
+ type="text"
+ value={formData.updateCommand}
+ onChange={e => setFormData({ ...formData, updateCommand: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden font-mono text-sm"
+ placeholder="npm run update"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Optional. Updates otherwise only switch to origin’s default branch and restart. Node apps can instead define a <code>portos:update</code> package script.
+ </p>
+ </div>
+
<div>
<label htmlFor="edit-app-build-command" className="block text-sm text-gray-400 mb-1">Build Command</label>
<input
diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsx
index 14c15afd51..8451cac0cd 100644
--- a/client/src/components/apps/EditAppDrawer.test.jsx
+++ b/client/src/components/apps/EditAppDrawer.test.jsx
@@ -244,6 +244,19 @@ describe('EditAppDrawer native launch target', () => {
});
});
+describe('EditAppDrawer update command', () => {
+ it('saves the explicitly configured app update routine', async () => {
+ renderDrawer();
+ await openTab('Commands');
+
+ fireEvent.change(screen.getByLabelText('Update Command'), { target: { value: 'npm run update' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+
+ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());
+ expect(api.updateApp.mock.calls[0][1].updateCommand).toBe('npm run update');
+ });
+});
+
describe('EditAppDrawer required-field validation across tabs', () => {
// The required Name/Repository Path inputs live on the General tab and are
// unmounted while another tab is active, so browser `required` validation
diff --git a/client/src/pages/CreateApp.jsx b/client/src/pages/CreateApp.jsx
index ab000b8436..d0741625f2 100644
--- a/client/src/pages/CreateApp.jsx
+++ b/client/src/pages/CreateApp.jsx
@@ -82,6 +82,7 @@ export default function CreateApp() {
const [devUiPort, setDevUiPort] = useState('');
const [apiPort, setApiPort] = useState('');
const [buildCommand, setBuildCommand] = useState('');
+ const [updateCommand, setUpdateCommand] = useState('');
const [startCommands, setStartCommands] = useState('');
const [pm2Names, setPm2Names] = useState('');
const [pm2Status, setPm2Status] = useState(null);
@@ -234,6 +235,7 @@ export default function CreateApp() {
devUiPort: devUiPort ? parseInt(devUiPort, 10) : null,
apiPort: apiPort ? parseInt(apiPort, 10) : null,
buildCommand: buildCommand || undefined,
+ updateCommand: updateCommand || undefined,
startCommands: startCommands ? startCommands.split('\n').filter(Boolean) : [],
pm2ProcessNames: isNonPm2
? []
@@ -424,6 +426,21 @@ export default function CreateApp() {
</div>
)}
+ <div>
+ <label htmlFor="update-command" className="block text-sm text-gray-400 mb-1">Update Command</label>
+ <input
+ id="update-command"
+ type="text"
+ value={updateCommand}
+ onChange={(e) => setUpdateCommand(e.target.value)}
+ placeholder="npm run update"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden font-mono text-sm"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Optional. Updates otherwise only check out the origin default branch and restart. A <code>portos:update</code> package script is also recognized.
+ </p>
+ </div>
+
<div>
<label htmlFor="build-command" className="block text-sm text-gray-400 mb-1">Build Command</label>
<input
diff --git a/docs/MANAGED_APP_UPDATES.md b/docs/MANAGED_APP_UPDATES.md
new file mode 100644
index 0000000000..e5a06f436b
--- /dev/null
+++ b/docs/MANAGED_APP_UPDATES.md
@@ -0,0 +1,28 @@
+# Managed app update contract
+
+PortOS updates itself through `update.sh` or `update.ps1`. That lifecycle is
+specific to PortOS and is never assumed for a separately managed app.
+
+When a managed app is updated, PortOS first fetches `origin`, checks out that
+repository's default branch, fast-forwards it, and restarts the app's configured
+PM2 processes. It does not automatically run `npm install`, `setup`, migrations,
+or a production build. If the checkout has local changes, the update stops
+without stashing or discarding them.
+
+An app can opt into its own lifecycle in either of these ways:
+
+1. Add an executable `update.sh` (or `update.ps1` on Windows) at the repository
+ root. PortOS recognizes these conventional scripts automatically.
+2. Set **Update Command** in Apps → Edit → Commands (for example,
+ `npm run update`). Commands use PortOS's normal command allowlist and run
+ from the app repository root.
+3. For Node or Bun apps, define a dedicated package script named
+ `portos:update`. PortOS runs it as `npm run portos:update` or
+ `bun run portos:update` for Bun-managed apps.
+
+The command/script is responsible for the app's own dependency installation,
+database migrations, generated assets, and build. Use the dedicated
+`portos:update` name rather than a generic lifecycle hook so an app's normal
+package-manager behavior is never invoked merely because PortOS updated it.
+When more than one is present, the configured **Update Command** wins, then
+`portos:update`, then the conventional script.
diff --git a/docs/README.md b/docs/README.md
index 83f472bb03..28bdc68dc5 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -26,6 +26,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [GITHUB_ACTIONS.md](./GITHUB_ACTIONS.md) | CI and release workflows |
| [VERSIONING.md](./VERSIONING.md) | SemVer + release process (`/do:release`) |
| [SELF_UPDATE.md](./SELF_UPDATE.md) | Fork-aware self-update flow — release polling, `FORK_SYNC_REQUIRED`, fork sync |
+| [MANAGED_APP_UPDATES.md](./MANAGED_APP_UPDATES.md) | Safe managed-app update default and the opt-in app lifecycle contract |
| [DEPS.md](./DEPS.md) | Dependency audit — every third-party package and its verdict |
| [TROUBLESHOOTING.md](./TROUBLESHOOTING.md) | Common runtime issues, known issues |
| [WINDOWS_CONSOLE.md](./WINDOWS_CONSOLE.md) | Why console windows flash and steal focus on Windows, and the two fixes |
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 7ef7ddeafc..c046186b17 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -267,6 +267,10 @@ export const appSchema = z.object({
// uiPort. See lib/tailscale-https.js for the helper apps use.
tlsPort: z.number().int().min(1).max(65535).nullable().optional(),
buildCommand: z.string().max(200).optional(),
+ // Explicit lifecycle hook for managed-app updates. PortOS runs its own
+ // update.sh/update.ps1; other apps must opt in instead of inheriting that
+ // lifecycle from their package.json.
+ updateCommand: z.string().trim().min(1).max(500).optional(),
uiUrl: z.string().url().optional(),
startCommands: z.array(z.string()).optional(),
pm2ProcessNames: z.array(z.string()).optional(),
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index e94258925e..73cccab8d4 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -566,6 +566,13 @@ describe('validation.js', () => {
const result = appSchema.safeParse(app);
expect(result.success).toBe(false);
});
+
+ it('accepts an explicit managed-app update command', () => {
+ const app = { name: 'Test', repoPath: '/path', updateCommand: 'npm run update' };
+ const result = appSchema.safeParse(app);
+ expect(result.success).toBe(true);
+ expect(result.data.updateCommand).toBe('npm run update');
+ });
});
describe('appUpdateSchema', () => {
diff --git a/server/services/appUpdater.js b/server/services/appUpdater.js
index 0b67ea1cd6..c93063092f 100644
--- a/server/services/appUpdater.js
+++ b/server/services/appUpdater.js
@@ -5,10 +5,9 @@ import { tmpdir } from 'os';
import * as gitService from './git.js';
import * as pm2Service from './pm2.js';
import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';
-import { parseCommandArgs } from '../lib/commandSecurity.js';
+import { parseCommandArgs, validateCommand } from '../lib/commandSecurity.js';
import { isDetachedRunning, spawnDetached } from '../lib/detachedSpawn.js';
import { PORTOS_APP_ID } from '../lib/appIdentity.js';
-import { parseBuildCommand } from './appBuilder.js';
import { syncManagedAppFork } from './managedAppRepositories.js';
const CMD_TIMEOUT_MS = 5 * 60 * 1000;
@@ -67,14 +66,14 @@ async function startDashboardHandoff(app) {
/**
* Run a full update cycle for an app:
- * 1. git pull --rebase --autostash
- * 2. install dependencies in each package directory (Bun apps use their
- * frozen lockfile; existing apps retain npm install)
- * 3. run setup with the same package manager when the script exists
- * 4. rebuild the production UI when a build command or `scripts.build` exists
- * (a pull that only restarts leaves `client/dist` stale and PortOS then
- * reports "install out of sync")
- * 5. Restart PM2 processes
+ * 1. switch to origin's default branch and fast-forward it
+ * 2. run an explicitly declared app update routine, when one exists
+ * 3. restart the app's PM2 processes
+ *
+ * PortOS owns its comprehensive update.sh/update.ps1 lifecycle separately.
+ * A generic managed app must opt in to dependency installs, migrations, or a
+ * build: guessing those steps from a package.json can freeze or break apps
+ * whose lifecycle does not resemble PortOS.
*
* @param {object} app - The app object (must have repoPath, pm2ProcessNames, pm2Home)
* @param {function} emit - Callback (step, status, message) for progress updates
@@ -103,7 +102,6 @@ async function _doUpdate(app, emit, { syncFork }) {
const packageManagerCommand = packageManager === 'bun' && configuredRuntime
? configuredRuntime
: packageManager;
- const installArgs = packageManager === 'bun' ? ['install', '--frozen-lockfile'] : ['install'];
if (syncFork) {
emit('git-sync-fork', 'running', 'Syncing the origin fork from canonical upstream...');
@@ -115,9 +113,9 @@ async function _doUpdate(app, emit, { syncFork }) {
steps.push({ step: 'git-sync-fork', success: true, message: syncMessage });
}
- emit('git-pull', 'running', 'Pulling latest changes...');
- const pullResult = await gitService.pull(dir);
- const pullMsg = pullResult.output?.trim() || 'Up to date';
+ emit('git-pull', 'running', 'Updating from origin default branch...');
+ const pullResult = await gitService.updateDefaultBranch(dir);
+ const pullMsg = pullResult.output?.trim() || `${pullResult.branch} is up to date`;
emit('git-pull', 'done', pullMsg);
steps.push({ step: 'git-pull', success: true, message: pullMsg });
@@ -128,47 +126,34 @@ async function _doUpdate(app, emit, { syncFork }) {
const companionPath = companionRepoPaths[index];
const stepId = `git-pull:companion-${index + 1}`;
emit(stepId, 'running', `Pulling companion repository ${index + 1}/${companionRepoPaths.length}...`);
- const companionPull = await gitService.pull(companionPath);
- const companionMessage = companionPull.output?.trim() || 'Up to date';
+ const companionPull = await gitService.updateDefaultBranch(companionPath);
+ const companionMessage = companionPull.output?.trim() || `${companionPull.branch} is up to date`;
emit(stepId, 'done', companionMessage);
steps.push({ step: stepId, success: true, message: companionMessage });
}
- for (const sub of ['', 'client', 'server', 'admin']) {
- const subDir = sub ? join(dir, sub) : dir;
- if (existsSync(join(subDir, 'package.json'))) {
- const label = sub || 'root';
- const stepId = `${packageManager}-install:${label}`;
- emit(stepId, 'running', `Installing ${label} dependencies...`);
- await runCommand(packageManagerCommand, installArgs, subDir);
- emit(stepId, 'done', `${label} dependencies installed`);
- steps.push({ step: stepId, success: true });
- }
- }
-
const pkgPath = join(dir, 'package.json');
const pkg = existsSync(pkgPath) ? JSON.parse(await readFile(pkgPath, 'utf-8')) : null;
- if (pkg?.scripts?.setup) {
- emit('setup', 'running', 'Running setup...');
- await runCommand(packageManagerCommand, ['run', 'setup'], dir);
- emit('setup', 'done', 'Setup complete');
- steps.push({ step: 'setup', success: true });
- }
-
- const configuredBuild = typeof app.buildCommand === 'string' ? app.buildCommand.trim() : '';
- let build;
- if (configuredBuild) {
- const parsed = parseBuildCommand(configuredBuild);
- if (!parsed.ok) throw new Error(parsed.message);
- build = { cmd: parsed.cmd, args: parsed.args };
- } else if (pkg?.scripts?.build) {
- build = { cmd: packageManagerCommand, args: ['run', 'build'] };
- }
- if (build) {
- emit('build', 'running', 'Building production UI...');
- await runCommand(build.cmd, build.args, dir);
- emit('build', 'done', 'Production UI built');
- steps.push({ step: 'build', success: true });
+ const configuredUpdate = typeof app.updateCommand === 'string' ? app.updateCommand.trim() : '';
+ const standardScript = process.platform === 'win32' ? 'update.ps1' : 'update.sh';
+ const standardScriptPath = join(dir, standardScript);
+ if (configuredUpdate || pkg?.scripts?.['portos:update'] || existsSync(standardScriptPath)) {
+ // A configured runtime may be an absolute Bun path, which is trusted app
+ // configuration but not a commandSecurity allowlist token. Only free-form
+ // registry commands go through that parser; the package-script form is a
+ // fixed argument list selected by PortOS.
+ const command = configuredUpdate
+ ? validateCommand(configuredUpdate)
+ : pkg?.scripts?.['portos:update']
+ ? { valid: true, baseCommand: packageManagerCommand, args: ['run', 'portos:update'] }
+ : process.platform === 'win32'
+ ? { valid: true, baseCommand: 'powershell', args: ['-ExecutionPolicy', 'Bypass', '-File', standardScriptPath] }
+ : { valid: true, baseCommand: standardScriptPath, args: [] };
+ if (!command.valid) throw new Error(`Update command is not allowed: ${command.error}`);
+ emit('app-update', 'running', 'Running the app update routine...');
+ await runCommand(command.baseCommand, command.args, dir);
+ emit('app-update', 'done', 'App update routine complete');
+ steps.push({ step: 'app-update', success: true });
}
const processNames = app.pm2ProcessNames || [];
diff --git a/server/services/appUpdater.test.js b/server/services/appUpdater.test.js
index 2a7ba3f241..9e9f9020e0 100644
--- a/server/services/appUpdater.test.js
+++ b/server/services/appUpdater.test.js
@@ -4,7 +4,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
const mock = vi.hoisted(() => ({
- pull: vi.fn(),
+ updateDefaultBranch: vi.fn(),
spawn: vi.fn(),
dashboardOpen: vi.fn(),
dashboardRunning: vi.fn(),
@@ -13,7 +13,7 @@ const mock = vi.hoisted(() => ({
syncFork: vi.fn(),
}));
-vi.mock('./git.js', () => ({ pull: mock.pull }));
+vi.mock('./git.js', () => ({ updateDefaultBranch: mock.updateDefaultBranch }));
vi.mock('./pm2.js', () => ({ restartApp: mock.restart }));
vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {
const actual = await importOriginal();
@@ -36,7 +36,7 @@ describe('managed app updates', () => {
await mkdir(join(repo, 'client'));
await writeFile(join(repo, 'package.json'), JSON.stringify({ scripts: { setup: 'example-setup' } }));
await writeFile(join(repo, 'client', 'package.json'), JSON.stringify({}));
- mock.pull.mockResolvedValue({ output: 'Already up to date' });
+ mock.updateDefaultBranch.mockResolvedValue({ branch: 'main', output: 'Already up to date' });
mock.spawn.mockResolvedValue({ stdout: '', stderr: '' });
mock.dashboardRunning.mockResolvedValue(false);
mock.dashboardOpen.mockResolvedValue(mock.dashboardHandle);
@@ -56,8 +56,8 @@ describe('managed app updates', () => {
await rm(repo, { recursive: true, force: true });
});
- it('uses Bun and its frozen lockfile for Bun-managed apps', async () => {
- await writeFile(join(repo, 'package.json'), JSON.stringify({ scripts: { setup: 'example-setup', build: 'vite build' } }));
+ it('uses the Bun portos:update script without inheriting PortOS install or build steps', async () => {
+ await writeFile(join(repo, 'package.json'), JSON.stringify({ scripts: { 'portos:update': 'example-update', setup: 'example-setup', build: 'vite build' } }));
const emit = vi.fn();
const companionRepo = join(repo, '..', 'eidoverse-video');
const bunCommand = join(repo, 'tools with spaces', 'bun');
@@ -71,15 +71,12 @@ describe('managed app updates', () => {
}, emit);
expect(result.success).toBe(true);
- expect(mock.pull).toHaveBeenNthCalledWith(1, repo);
- expect(mock.pull).toHaveBeenNthCalledWith(2, companionRepo);
- expect(mock.spawn).toHaveBeenCalledWith(bunCommand, ['install', '--frozen-lockfile'], expect.objectContaining({ cwd: repo }));
- expect(mock.spawn).toHaveBeenCalledWith(bunCommand, ['install', '--frozen-lockfile'], expect.objectContaining({ cwd: join(repo, 'client') }));
- expect(mock.spawn).toHaveBeenCalledWith(bunCommand, ['run', 'setup'], expect.objectContaining({ cwd: repo }));
- expect(mock.spawn).toHaveBeenCalledWith(bunCommand, ['run', 'build'], expect.objectContaining({ cwd: repo }));
+ expect(mock.updateDefaultBranch).toHaveBeenNthCalledWith(1, repo);
+ expect(mock.updateDefaultBranch).toHaveBeenNthCalledWith(2, companionRepo);
+ expect(mock.spawn).toHaveBeenCalledWith(bunCommand, ['run', 'portos:update'], expect.objectContaining({ cwd: repo }));
expect(mock.spawn).not.toHaveBeenCalledWith('npm', expect.anything(), expect.anything());
expect(emit).toHaveBeenCalledWith('git-pull:companion-1', 'done', 'Already up to date');
- expect(emit).toHaveBeenCalledWith('bun-install:root', 'done', 'root dependencies installed');
+ expect(emit).toHaveBeenCalledWith('app-update', 'done', 'App update routine complete');
});
it('syncs a detected fork before pulling when the managed update requests it', async () => {
@@ -89,7 +86,7 @@ describe('managed app updates', () => {
await updateApp(managed, emit, { syncFork: true });
expect(mock.syncFork).toHaveBeenCalledWith(managed);
- expect(mock.syncFork.mock.invocationCallOrder[0]).toBeLessThan(mock.pull.mock.invocationCallOrder[0]);
+ expect(mock.syncFork.mock.invocationCallOrder[0]).toBeLessThan(mock.updateDefaultBranch.mock.invocationCallOrder[0]);
expect(emit).toHaveBeenCalledWith(
'git-sync-fork',
'done',
@@ -145,66 +142,80 @@ describe('managed app updates', () => {
expect(mock.restart).toHaveBeenCalledWith('portos-server', undefined);
});
- it('rebuilds the production UI before restarting so a managed update does not leave a stale client bundle', async () => {
+ it('runs an explicit update command before restarting', async () => {
const emit = vi.fn();
const managed = {
id: 'portos-default',
name: 'PortOS',
type: 'express',
repoPath: repo,
- buildCommand: 'npm run build',
+ updateCommand: 'npm run update',
pm2ProcessNames: ['portos-server'],
};
const result = await updateApp(managed, emit);
expect(result.success).toBe(true);
- expect(result.steps.some((step) => step.step === 'build' && step.success)).toBe(true);
+ expect(result.steps.some((step) => step.step === 'app-update' && step.success)).toBe(true);
expect(mock.spawn).toHaveBeenCalledWith(
'npm',
- ['run', 'build'],
+ ['run', 'update'],
expect.objectContaining({ cwd: repo }),
);
- const buildCall = mock.spawn.mock.invocationCallOrder[
- mock.spawn.mock.calls.findIndex((call) => call[0] === 'npm' && call[1]?.[1] === 'build')
+ const updateCall = mock.spawn.mock.invocationCallOrder[
+ mock.spawn.mock.calls.findIndex((call) => call[0] === 'npm' && call[1]?.[1] === 'update')
];
- expect(buildCall).toBeLessThan(mock.restart.mock.invocationCallOrder[0]);
- expect(emit).toHaveBeenCalledWith('build', 'done', 'Production UI built');
+ expect(updateCall).toBeLessThan(mock.restart.mock.invocationCallOrder[0]);
+ expect(emit).toHaveBeenCalledWith('app-update', 'done', 'App update routine complete');
});
- it('rebuilds from package.json when no explicit build command is configured', async () => {
- await writeFile(join(repo, 'package.json'), JSON.stringify({ scripts: { build: 'vite build' } }));
+ it('runs the dedicated package script when no explicit update command is configured', async () => {
+ await writeFile(join(repo, 'package.json'), JSON.stringify({ scripts: { 'portos:update': 'vite build' } }));
const emit = vi.fn();
await updateApp({ name: 'Example App', type: 'express', repoPath: repo, pm2ProcessNames: [] }, emit);
expect(mock.spawn).toHaveBeenCalledWith(
'npm',
- ['run', 'build'],
+ ['run', 'portos:update'],
expect.objectContaining({ cwd: repo }),
);
- expect(emit).toHaveBeenCalledWith('build', 'done', 'Production UI built');
+ expect(emit).toHaveBeenCalledWith('app-update', 'done', 'App update routine complete');
});
- it('does not invent a production build when the app has none', async () => {
+ it('recognizes a conventional repository update script', async () => {
+ await writeFile(join(repo, 'update.sh'), '#!/bin/sh\nexit 0\n');
const emit = vi.fn();
await updateApp({ name: 'Example App', type: 'express', repoPath: repo, pm2ProcessNames: [] }, emit);
- expect(mock.spawn).not.toHaveBeenCalledWith('npm', ['run', 'build'], expect.anything());
- expect(emit).not.toHaveBeenCalledWith('build', expect.anything(), expect.anything());
+ expect(mock.spawn).toHaveBeenCalledWith(
+ join(repo, 'update.sh'),
+ [],
+ expect.objectContaining({ cwd: repo }),
+ );
+ });
+
+ it('defaults to checkout update and restart without guessing package lifecycle steps', async () => {
+ const emit = vi.fn();
+
+ await updateApp({ name: 'Example App', type: 'express', repoPath: repo, pm2ProcessNames: [] }, emit);
+
+ expect(mock.spawn).not.toHaveBeenCalled();
+ expect(mock.updateDefaultBranch).toHaveBeenCalledWith(repo);
+ expect(emit).not.toHaveBeenCalledWith('app-update', expect.anything(), expect.anything());
});
- it('refuses a disallowed build command before restarting', async () => {
+ it('refuses a disallowed update command before restarting', async () => {
const emit = vi.fn();
await expect(updateApp({
name: 'Example App',
type: 'express',
repoPath: repo,
- buildCommand: 'rm -rf /',
+ updateCommand: 'rm -rf /',
pm2ProcessNames: ['example-app'],
- }, emit)).rejects.toThrow(/not allowed/);
+ }, emit)).rejects.toThrow(/Update command is not allowed/);
expect(mock.restart).not.toHaveBeenCalled();
});
diff --git a/server/services/apps.js b/server/services/apps.js
index d0e3abe556..126bd31809 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -405,6 +405,7 @@ export async function createApp(appData) {
devUiPort: appData.devUiPort || null,
apiPort: appData.apiPort || null,
buildCommand: appData.buildCommand || undefined,
+ updateCommand: appData.updateCommand || undefined,
startCommands: appData.startCommands || ['npm run dev'],
pm2ProcessNames: appData.pm2ProcessNames || [appData.name.toLowerCase().replace(/\s+/g, '-')],
nativeLaunch: appData.nativeLaunch || null,
diff --git a/server/services/git.js b/server/services/git.js
index efe0af874d..cf6256a51c 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -819,6 +819,38 @@ export async function pull(dir) {
return { success: true, output: result.stdout + result.stderr };
}
+/**
+ * Move a managed application's primary checkout onto origin's default branch
+ * and fast-forward it. This is intentionally non-destructive: unlike the
+ * Git-tab reset escape hatch it neither stashes nor discards local work.
+ *
+ * @param {string} dir
+ * @returns {Promise<{success: boolean, branch: string, output: string}>}
+ */
+export async function updateDefaultBranch(dir) {
+ await execGit(['fetch', 'origin'], dir);
+ const branch = await getDefaultBranch(dir, { strict: true });
+ if (!branch) throw new ServerError('could not determine origin default branch', { status: 400, code: 'NO_DEFAULT_BRANCH' });
+
+ const status = await getStatus(dir);
+ if (!status.clean) {
+ throw new ServerError('checkout has local changes; commit or stash them before updating', {
+ status: 409,
+ code: 'DIRTY_WORKTREE'
+ });
+ }
+
+ const currentBranch = await getBranch(dir);
+ let output = '';
+ if (currentBranch !== branch) {
+ const checkout = await execGit(['checkout', branch], dir);
+ output += checkout.stdout + checkout.stderr;
+ }
+ const pull = await execGit(['pull', '--ff-only', 'origin', branch], dir);
+ output += pull.stdout + pull.stderr;
+ return { success: true, branch, output };
+}
+
/**
* Sync branch - pull then push
*/
diff --git a/server/services/git.updateDefaultBranch.test.js b/server/services/git.updateDefaultBranch.test.js
new file mode 100644
index 0000000000..7298fba245
--- /dev/null
+++ b/server/services/git.updateDefaultBranch.test.js
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const execGitMock = vi.hoisted(() => vi.fn());
+
+vi.mock('../lib/execGit.js', () => ({ execGit: execGitMock }));
+
+import { updateDefaultBranch } from './git.js';
+
+const ok = (stdout = '') => ({ stdout, stderr: '', exitCode: 0 });
+const key = (args) => args.join(' ');
+
+beforeEach(() => {
+ execGitMock.mockReset();
+ execGitMock.mockImplementation((args) => Promise.resolve({
+ 'fetch origin': ok(),
+ 'symbolic-ref --short refs/remotes/origin/HEAD': ok('origin/main'),
+ 'rev-parse --verify refs/remotes/origin/main': ok('a'.repeat(40)),
+ 'status --porcelain': ok(),
+ 'rev-parse --abbrev-ref HEAD': ok('feature/work'),
+ 'checkout main': ok('Switched to branch main'),
+ 'pull --ff-only origin main': ok('Already up to date')
+ }[key(args)] ?? ok()));
+});
+
+describe('updateDefaultBranch', () => {
+ it('checks out origin default branch and fast-forwards it without a rebase', async () => {
+ const result = await updateDefaultBranch('/repo');
+
+ expect(result).toMatchObject({ success: true, branch: 'main' });
+ expect(execGitMock.mock.calls.map(([args]) => key(args))).toEqual(expect.arrayContaining([
+ 'fetch origin',
+ 'checkout main',
+ 'pull --ff-only origin main'
+ ]));
+ expect(execGitMock.mock.calls.map(([args]) => key(args)).some(command => command.includes('rebase'))).toBe(false);
+ });
+
+ it('refuses to switch branches while the checkout has local changes', async () => {
+ execGitMock.mockImplementation((args) => Promise.resolve({
+ 'fetch origin': ok(),
+ 'symbolic-ref --short refs/remotes/origin/HEAD': ok('origin/main'),
+ 'rev-parse --verify refs/remotes/origin/main': ok('a'.repeat(40)),
+ 'status --porcelain': ok(' M package-lock.json')
+ }[key(args)] ?? ok()));
+
+ await expect(updateDefaultBranch('/repo')).rejects.toThrow(/local changes/);
+ expect(execGitMock.mock.calls.map(([args]) => key(args))).not.toContain('checkout main');
+ });
+});