feat(companion): export release bundle artifacts for shell packaging

This commit is contained in:
William Valentin
2026-02-26 18:58:21 -08:00
parent ee93061496
commit 484247e1c1
11 changed files with 369 additions and 19 deletions
+70
View File
@@ -10,6 +10,7 @@ const {
mockRuntimeCtorArgs,
mockRuntimeInstances,
mockCreateCompanionBootstrapManifest,
mockWriteCompanionReleaseBundle,
} = vi.hoisted(() => {
const runtimeCtorArgs: Array<{ url: string; token?: string; autoReconnect?: boolean }> = [];
const runtimeInstances: Array<{
@@ -85,6 +86,15 @@ const {
...(input.location ? { location: input.location } : {}),
...(input.push ? { push: input.push } : {}),
}));
const writeCompanionReleaseBundle = vi.fn(async (input: {
outputDir: string;
manifest: unknown;
}) => ({
outputDir: input.outputDir,
manifestPath: `${input.outputDir}/companion.bootstrap.json`,
launcherPath: `${input.outputDir}/run-companion.sh`,
readmePath: `${input.outputDir}/README.md`,
}));
return {
mockLoadConfigSafe: loadConfigSafe,
@@ -92,6 +102,7 @@ const {
mockRuntimeCtorArgs: runtimeCtorArgs,
mockRuntimeInstances: runtimeInstances,
mockCreateCompanionBootstrapManifest: createCompanionBootstrapManifest,
mockWriteCompanionReleaseBundle: writeCompanionReleaseBundle,
};
});
@@ -102,6 +113,7 @@ vi.mock('./shared.js', () => ({
vi.mock('../companion/index.js', () => ({
createCompanionBootstrapManifest: mockCreateCompanionBootstrapManifest,
writeCompanionReleaseBundle: mockWriteCompanionReleaseBundle,
CompanionRuntimeClient: class {
private connectionHandlers: Array<(event: { status: string }) => void> = [];
connect = vi.fn(async () => {
@@ -141,6 +153,7 @@ describe('companion command', () => {
mockRuntimeCtorArgs.length = 0;
mockRuntimeInstances.length = 0;
mockCreateCompanionBootstrapManifest.mockClear();
mockWriteCompanionReleaseBundle.mockClear();
mockLoadConfigSafe.mockReturnValue({
config: {
server: {
@@ -360,6 +373,41 @@ describe('companion command', () => {
errSpy.mockRestore();
});
it('exports release bundle and exits without runtime connection', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const program = new Command();
const { registerCompanionCommand } = await import('./companion.js');
registerCompanionCommand(program);
await program.parseAsync([
'node',
'test',
'companion',
'--export-release-bundle',
'/tmp/flynn-companion-bundle',
'--platform',
'android',
'--push-token',
'abcdef0123456789abcdef0123456789',
]);
expect(mockWriteCompanionReleaseBundle).toHaveBeenCalledOnce();
expect(mockWriteCompanionReleaseBundle).toHaveBeenCalledWith({
outputDir: '/tmp/flynn-companion-bundle',
manifest: expect.objectContaining({
node: expect.objectContaining({ platform: 'android' }),
push: expect.objectContaining({ provider: 'fcm' }),
}),
});
expect(mockRuntimeCtorArgs).toEqual([]);
expect(mockRuntimeInstances).toEqual([]);
expect(errSpy).not.toHaveBeenCalled();
logSpy.mockRestore();
errSpy.mockRestore();
});
it('applies location, push, and status bootstrap settings to runtime registration', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
@@ -443,4 +491,26 @@ describe('companion command', () => {
errSpy.mockRestore();
});
it('sets process exit code when export-bootstrap and export-release-bundle are combined', async () => {
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const program = new Command();
const { registerCompanionCommand } = await import('./companion.js');
registerCompanionCommand(program);
await program.parseAsync([
'node',
'test',
'companion',
'--export-bootstrap',
'-',
'--export-release-bundle',
'/tmp/flynn-companion-bundle',
]);
expect(errSpy).toHaveBeenCalled();
expect(process.exitCode).toBe(1);
errSpy.mockRestore();
});
});
+38 -14
View File
@@ -5,6 +5,7 @@ import type { Command } from 'commander';
import { CompanionRuntimeClient } from '../companion/index.js';
import type { SetNodeLocationInput, SetNodePushTokenInput, SetNodeStatusInput } from '../companion/index.js';
import { createCompanionBootstrapManifest } from '../companion/index.js';
import { writeCompanionReleaseBundle } from '../companion/index.js';
import { getConfigPath, loadConfigSafe } from './shared.js';
type CompanionPlatform = SetNodeStatusInput['platform'];
@@ -38,6 +39,7 @@ interface CompanionCommandOptions {
pushTopic?: string;
pushEnvironment?: string;
exportBootstrap?: string;
exportReleaseBundle?: string;
once?: boolean;
}
@@ -317,22 +319,28 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
const locationInput = resolveLocationInput(options);
const pushInput = resolvePushInput(options, platform);
const exportBootstrapPath = options.exportBootstrap?.trim();
const exportReleaseBundleDir = options.exportReleaseBundle?.trim();
if (exportBootstrapPath && exportReleaseBundleDir) {
throw new Error('export-bootstrap and export-release-bundle cannot be used together');
}
const manifest = createCompanionBootstrapManifest({
gatewayUrl,
gatewayToken,
nodeId,
role,
platform,
capabilities,
heartbeatSeconds,
handoffTimeoutMs,
autoReconnect: !options.once,
status: hasDefinedProperties(statusOverrides) ? statusOverrides : undefined,
location: locationInput,
push: pushInput,
});
if (exportBootstrapPath) {
const manifest = createCompanionBootstrapManifest({
gatewayUrl,
gatewayToken,
nodeId,
role,
platform,
capabilities,
heartbeatSeconds,
handoffTimeoutMs,
autoReconnect: !options.once,
status: hasDefinedProperties(statusOverrides) ? statusOverrides : undefined,
location: locationInput,
push: pushInput,
});
const body = `${JSON.stringify(manifest, null, 2)}\n`;
if (exportBootstrapPath === '-') {
console.log(body.trimEnd());
@@ -343,6 +351,18 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
return;
}
if (exportReleaseBundleDir) {
const result = await writeCompanionReleaseBundle({
outputDir: exportReleaseBundleDir,
manifest,
});
console.log(`Wrote companion release bundle to ${result.outputDir}`);
console.log(`- Manifest: ${result.manifestPath}`);
console.log(`- Launcher: ${result.launcherPath}`);
console.log(`- README: ${result.readmePath}`);
return;
}
const runtime = new CompanionRuntimeClient({
url: gatewayUrl,
token: gatewayToken,
@@ -525,6 +545,10 @@ export function registerCompanionCommand(program: Command): void {
'--export-bootstrap <path>',
'Write resolved companion bootstrap manifest JSON (`-` for stdout) and exit',
)
.option(
'--export-release-bundle <dir>',
'Write a companion release bundle (manifest + launcher + README) and exit',
)
.option('--once', 'Connect, register, publish one heartbeat, then exit', false)
.action(async (opts: CompanionCommandOptions) => {
try {
+5
View File
@@ -10,6 +10,7 @@ export {
} from './platformClients.js';
export { CompanionHeartbeatLoop } from './heartbeatLoop.js';
export { createCompanionBootstrapManifest } from './bootstrapManifest.js';
export { writeCompanionReleaseBundle } from './releaseBundle.js';
export type {
CompanionRuntimeClientOptions,
@@ -76,3 +77,7 @@ export type {
CompanionBootstrapManifest,
CreateCompanionBootstrapManifestInput,
} from './bootstrapManifest.js';
export type {
WriteCompanionReleaseBundleInput,
WriteCompanionReleaseBundleResult,
} from './releaseBundle.js';
+65
View File
@@ -0,0 +1,65 @@
import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { describe, expect, it } from 'vitest';
import { writeCompanionReleaseBundle } from './releaseBundle.js';
describe('writeCompanionReleaseBundle', () => {
it('writes manifest, launcher script, and README', async () => {
const tempDir = await mkdtemp(join(tmpdir(), 'flynn-companion-release-'));
const outputDir = join(tempDir, 'bundle');
const result = await writeCompanionReleaseBundle({
outputDir,
manifest: {
schemaVersion: 1,
generatedAt: '2026-02-27T00:00:00.000Z',
gateway: { url: 'ws://127.0.0.1:18800', token: 'token-123' },
node: {
nodeId: 'ios-node',
role: 'companion',
platform: 'ios',
capabilities: ['ui.canvas', 'node.push.register'],
},
runtime: {
heartbeatSeconds: 30,
handoffTimeoutMs: 120000,
autoReconnect: true,
},
status: {
appVersion: '1.2.3',
statusText: 'ready',
powerSource: 'battery',
},
location: {
latitude: 37.3349,
longitude: -122.009,
source: 'gps',
},
push: {
provider: 'apns',
token: '0123456789abcdef0123456789abcdef',
topic: 'com.flynn.mobile',
environment: 'production',
},
},
});
const manifestRaw = await readFile(result.manifestPath, 'utf8');
const launcherRaw = await readFile(result.launcherPath, 'utf8');
const readmeRaw = await readFile(result.readmePath, 'utf8');
const launcherStat = await stat(result.launcherPath);
expect(JSON.parse(manifestRaw)).toMatchObject({
node: { nodeId: 'ios-node', platform: 'ios' },
push: { provider: 'apns' },
});
expect(launcherRaw).toContain('exec flynn');
expect(launcherRaw).toContain('--push-token');
expect(launcherRaw).toContain('--latitude');
expect(readmeRaw).toContain('Flynn Companion Release Bundle');
expect((launcherStat.mode & 0o111) !== 0).toBe(true);
await rm(tempDir, { recursive: true, force: true });
});
});
+161
View File
@@ -0,0 +1,161 @@
import { chmod, mkdir, writeFile } from 'node:fs/promises';
import type { CompanionBootstrapManifest } from './bootstrapManifest.js';
export interface WriteCompanionReleaseBundleInput {
outputDir: string;
manifest: CompanionBootstrapManifest;
}
export interface WriteCompanionReleaseBundleResult {
outputDir: string;
manifestPath: string;
launcherPath: string;
readmePath: string;
}
function shSingleQuote(value: string): string {
return `'${value.replaceAll('\'', '\'\"\'\"\'')}'`;
}
function createLauncherScript(manifest: CompanionBootstrapManifest): string {
const args: string[] = [
'companion',
'--url',
manifest.gateway.url,
'--node-id',
manifest.node.nodeId,
'--role',
manifest.node.role,
'--platform',
manifest.node.platform,
'--heartbeat',
String(manifest.runtime.heartbeatSeconds),
'--handoff-timeout',
String(manifest.runtime.handoffTimeoutMs),
];
if (manifest.runtime.autoReconnect === false) {
args.push('--once');
}
if (manifest.gateway.token) {
args.push('--token', manifest.gateway.token);
}
for (const capability of manifest.node.capabilities) {
args.push('--capability', capability);
}
if (manifest.status?.appVersion) {
args.push('--app-version', manifest.status.appVersion);
}
if (manifest.status?.deviceName) {
args.push('--device-name', manifest.status.deviceName);
}
if (manifest.status?.statusText) {
args.push('--status-text', manifest.status.statusText);
}
if (manifest.status?.batteryPct !== undefined) {
args.push('--battery-pct', String(manifest.status.batteryPct));
}
if (manifest.status?.powerSource) {
args.push('--power-source', manifest.status.powerSource);
}
if (manifest.location) {
args.push('--latitude', String(manifest.location.latitude));
args.push('--longitude', String(manifest.location.longitude));
if (manifest.location.source) {
args.push('--location-source', manifest.location.source);
}
if (manifest.location.accuracyMeters !== undefined) {
args.push('--location-accuracy-meters', String(manifest.location.accuracyMeters));
}
if (manifest.location.altitudeMeters !== undefined) {
args.push('--location-altitude-meters', String(manifest.location.altitudeMeters));
}
if (manifest.location.headingDegrees !== undefined) {
args.push('--location-heading-degrees', String(manifest.location.headingDegrees));
}
if (manifest.location.speedMps !== undefined) {
args.push('--location-speed-mps', String(manifest.location.speedMps));
}
if (manifest.location.capturedAt !== undefined) {
args.push('--location-captured-at', String(manifest.location.capturedAt));
}
}
if (manifest.push) {
args.push('--push-provider', manifest.push.provider);
args.push('--push-token', manifest.push.token);
if (manifest.push.topic) {
args.push('--push-topic', manifest.push.topic);
}
if (manifest.push.environment) {
args.push('--push-environment', manifest.push.environment);
}
}
const quotedArgs = args.map(shSingleQuote).join(' ');
return `#!/usr/bin/env bash
set -euo pipefail
# Generated by Flynn companion release-bundle export.
exec flynn ${quotedArgs} \"$@\"
`;
}
function createReadme(manifest: CompanionBootstrapManifest): string {
const platform = manifest.node.platform;
const reconnectLabel = manifest.runtime.autoReconnect ? 'enabled' : 'disabled (--once mode)';
return `# Flynn Companion Release Bundle
Generated: ${manifest.generatedAt}
Platform: ${platform}
Node ID: ${manifest.node.nodeId}
Role: ${manifest.node.role}
Gateway: ${manifest.gateway.url}
Auto reconnect: ${reconnectLabel}
## Files
- \`companion.bootstrap.json\`: resolved gateway/node/runtime contract for packaging flows.
- \`run-companion.sh\`: launcher script that runs \`flynn companion\` with this bundle's resolved defaults.
## Usage
1. Ensure \`flynn\` is installed on the target machine.
2. Review \`companion.bootstrap.json\` and remove any embedded secrets before redistribution.
3. Run:
\`\`\`bash
./run-companion.sh
\`\`\`
Add extra flags as needed:
\`\`\`bash
./run-companion.sh --handoff "hello from packaged shell"
\`\`\`
`;
}
export async function writeCompanionReleaseBundle(
input: WriteCompanionReleaseBundleInput,
): Promise<WriteCompanionReleaseBundleResult> {
await mkdir(input.outputDir, { recursive: true });
const manifestPath = `${input.outputDir}/companion.bootstrap.json`;
const launcherPath = `${input.outputDir}/run-companion.sh`;
const readmePath = `${input.outputDir}/README.md`;
await writeFile(
manifestPath,
`${JSON.stringify(input.manifest, null, 2)}\n`,
'utf8',
);
await writeFile(launcherPath, createLauncherScript(input.manifest), 'utf8');
await chmod(launcherPath, 0o755);
await writeFile(readmePath, createReadme(input.manifest), 'utf8');
return {
outputDir: input.outputDir,
manifestPath,
launcherPath,
readmePath,
};
}