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

test: preserve forge command outcomes (#6938)

[._.]/ Adam Eivy5f56fedd3bea
diff --git a/server/services/git.forgeTimeout.test.js b/server/services/git.forgeTimeout.test.js
index e4f4b885ea..ff3d8aeacf 100644
--- a/server/services/git.forgeTimeout.test.js
+++ b/server/services/git.forgeTimeout.test.js
@@ -47,10 +47,10 @@ describe('bounded forge mutations', () => {
});
it.each([
- ['createPR', () => createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic' })],
- ['mergePR', () => mergePR('/repo', 42)],
- ['requestCopilotReview', () => requestCopilotReview('/repo', 'https://github.com/example-owner/repo/pull/42')],
- ])('kills a stalled gh process and returns a structured timeout from %s', async (_name, invoke) => {
+ ['createPR', ['pr', 'create'], () => createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic' })],
+ ['mergePR', ['pr', 'merge', '42', '--merge', '--delete-branch'], () => mergePR('/repo', 42)],
+ ['requestCopilotReview', ['api', 'repos/example-owner/repo/pulls/42/requested_reviewers'], () => requestCopilotReview('/repo', 'https://github.com/example-owner/repo/pull/42')],
+ ])('kills a stalled gh process and returns a structured timeout from %s', async (_name, expectedArgs, invoke) => {
const child = hungChild();
mocks.spawn.mockReturnValue(child);
@@ -65,7 +65,7 @@ describe('bounded forge mutations', () => {
expect(child.kill).toHaveBeenCalledWith('SIGKILL');
expect(mocks.spawn).toHaveBeenCalledWith(
'gh',
- expect.any(Array),
+ expect.arrayContaining(expectedArgs),
expect.objectContaining({ cwd: '/repo', env: expect.objectContaining({ GH_TOKEN: 'test-owner-token', PWD: '/repo' }) }),
);
});
@@ -112,4 +112,30 @@ describe('bounded forge mutations', () => {
error: 'GraphQL: No commits between main and topic',
});
});
+
+ it.each([
+ ['gh', 'https://github.com/example-owner/repo/pull/42\n'],
+ ['glab', 'Creating merge request...\nhttps://gitlab.example.com/example-owner/repo/-/merge_requests/42\n'],
+ ])('returns the trailing PR URL after a successful %s create', async (cli, stdout) => {
+ mocks.resolveForgeForRepo.mockResolvedValue({
+ cli,
+ env: pinnedEnv,
+ host: cli === 'gh' ? 'github.com' : 'gitlab.example.com',
+ owner: 'example-owner',
+ account: cli === 'gh' ? 'example-owner' : null,
+ });
+ const child = hungChild();
+ mocks.spawn.mockReturnValue(child);
+
+ const pending = createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic' });
+ await vi.dynamicImportSettled();
+ child.stdout.emit('data', Buffer.from(stdout));
+ child.emit('close', 0);
+
+ await expect(pending).resolves.toMatchObject({
+ success: true,
+ url: expect.stringContaining('/42'),
+ cli,
+ });
+ });
});
diff --git a/server/services/git.js b/server/services/git.js
index bca28b426a..5eb9bc9258 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1,4 +1,3 @@
-import { spawn } from '../lib/childProcess.js';
import { existsSync } from 'fs';
import { join, resolve } from 'path';
import { safeJSONParse, PATHS, sleep } from '../lib/fileUtils.js';
@@ -362,7 +361,7 @@ export async function checkout(dir, branchName) {
async function execForgeCli(cli, args, dir, env) {
if (cli === 'glab') {
const { execGlab } = await import('./gitlab.js');
- return execGlab(args, dir, undefined, { env });
+ return execGlab(args, dir, undefined, { env, rejectOnError: true });
}
const { execGh } = await import('./github.js');
return execGh(args, undefined, { cwd: dir, env });
@@ -393,7 +392,7 @@ export async function createPR(dir, { title, body, base, head }) {
try {
const stdout = await execForgeCli(cli, args, dir, env);
if (stdout === null) {
- return { success: false, error: 'glab command failed or timed out', ...meta };
+ return { success: false, error: `${cli} command failed or timed out`, ...meta };
}
// Both gh and glab print the resulting URL on stdout (gh: just the URL;
// glab: a couple lines ending in the URL — extract the last http(s)-looking line).
@@ -422,7 +421,8 @@ export async function mergePR(dir, prNumber) {
}
try {
- await execForgeCli('gh', ['pr', 'merge', String(prNumber), '--merge', '--delete-branch'], dir, env);
+ const output = await execForgeCli('gh', ['pr', 'merge', String(prNumber), '--merge', '--delete-branch'], dir, env);
+ if (output === null) return { success: false, error: 'gh command failed or timed out', ...meta };
return { success: true, ...meta };
} catch (err) {
return { success: false, error: err.message || 'gh command failed', ...meta };
@@ -474,7 +474,8 @@ export async function requestCopilotReview(dir, prUrl) {
);
try {
- await execForgeCli('gh', args, dir, env);
+ const output = await execForgeCli('gh', args, dir, env);
+ if (output === null) return { success: false, error: 'gh command failed or timed out' };
return { success: true };
} catch (err) {
return { success: false, error: err.message || 'gh command failed' };
diff --git a/server/services/gitlab.js b/server/services/gitlab.js
index 904a783ea4..db97dd375b 100644
--- a/server/services/gitlab.js
+++ b/server/services/gitlab.js
@@ -17,7 +17,8 @@ const DEFAULT_EXEC_GLAB_TIMEOUT_MS = 60000;
* it MUST run inside the repo checkout. Resolves to trimmed stdout on success and
* `null` on ANY failure (non-zero exit, spawn error, glab not installed, timeout)
* — callers treat null as "unavailable / transient", mirroring the
- * `.catch(() => null)` pattern used around `execGh`.
+ * `.catch(() => null)` pattern used around `execGh`. Mutation callers that need
+ * the original stderr contract can opt into rejection with `rejectOnError`.
*
* Most PortOS callers want JSON and go through `execGlabJson`, which owns the
* output flag (see lib/glabArgs.js). This is exported for the genuine non-JSON
@@ -29,29 +30,37 @@ const DEFAULT_EXEC_GLAB_TIMEOUT_MS = 60000;
* @param {number} [timeoutMs] - kills the child and resolves null past this
* @param {object} [options]
* @param {NodeJS.ProcessEnv} [options.env] - Explicit forge credentials/environment
+ * @param {boolean} [options.rejectOnError=false] - Reject with stderr/timeout detail instead of resolving null
* @returns {Promise<string|null>}
*/
-export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS, { env = null } = {}) {
- return new Promise((resolve) => {
+export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS, { env = null, rejectOnError = false } = {}) {
+ return new Promise((resolve, reject) => {
const child = spawn('glab', args, { cwd, shell: false, env: withSpawnCwdEnv(env || process.env, cwd) });
let stdout = '';
+ let stderr = '';
let settled = false;
// One settle path so the timeout can't resolve a promise `close` already
// settled, and so the timer is always cleared.
- const done = (value) => { if (!settled) { settled = true; clearTimeout(timer); resolve(value); } };
+ const done = (value, error = null) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (error && rejectOnError) reject(error);
+ else resolve(value);
+ };
const timer = setTimeout(() => {
// setTimeout callback boundary — a kill() throw here would be uncaught.
try { child.kill('SIGKILL'); } catch (err) { console.error(`❌ execGlab: failed to kill timed-out 'glab ${args.join(' ')}': ${err.message}`); }
console.error(`❌ execGlab: 'glab ${args.join(' ')}' timed out after ${timeoutMs}ms`);
- done(null);
+ done(null, new Error(`glab command timed out after ${timeoutMs}ms`));
}, timeoutMs);
child.stdout.on('data', (d) => { stdout += d.toString(); });
- // We never surface glab's stderr to the caller (a failed call resolves to null
- // via the exit code), but stderr MUST still be drained — an unread pipe can
- // fill its buffer and block the child on a chatty warning.
- child.stderr.on('data', () => {});
- child.on('close', (code) => done(code === 0 ? stdout.trim() : null));
- child.on('error', () => done(null));
+ child.stderr.on('data', (d) => { stderr += d.toString(); });
+ child.on('close', (code) => {
+ if (code === 0) done(stdout.trim());
+ else done(null, new Error(stderr.trim() || `glab exited with code ${code}`));
+ });
+ child.on('error', (err) => done(null, new Error(`glab not available: ${err.message}`)));
});
}