feat(companion): add shell bootstrap status location push controls

This commit is contained in:
William Valentin
2026-02-26 18:55:29 -08:00
parent 6620afcf1f
commit ee93061496
10 changed files with 458 additions and 13 deletions
+131
View File
@@ -16,6 +16,8 @@ const {
connect: ReturnType<typeof vi.fn>;
registerNode: ReturnType<typeof vi.fn>;
setNodeStatus: ReturnType<typeof vi.fn>;
setNodeLocation: ReturnType<typeof vi.fn>;
setNodePushToken: ReturnType<typeof vi.fn>;
sendAgentMessage: ReturnType<typeof vi.fn>;
subscribeAgentStream: ReturnType<typeof vi.fn>;
subscribeAgentTyping: ReturnType<typeof vi.fn>;
@@ -43,6 +45,24 @@ const {
heartbeatSeconds: number;
handoffTimeoutMs: number;
autoReconnect: boolean;
status?: {
appVersion?: string;
deviceName?: string;
statusText?: string;
batteryPct?: number;
powerSource?: string;
};
location?: {
latitude: number;
longitude: number;
source?: string;
};
push?: {
provider: string;
token: string;
topic?: string;
environment?: string;
};
}) => ({
schemaVersion: 1,
generatedAt: '2026-02-27T00:00:00.000Z',
@@ -61,6 +81,9 @@ const {
handoffTimeoutMs: input.handoffTimeoutMs,
autoReconnect: input.autoReconnect,
},
...(input.status ? { status: input.status } : {}),
...(input.location ? { location: input.location } : {}),
...(input.push ? { push: input.push } : {}),
}));
return {
@@ -94,6 +117,8 @@ vi.mock('../companion/index.js', () => ({
capabilities: { declared: capabilities, enabled: capabilities },
}));
setNodeStatus = vi.fn(async () => ({ updated: true, node: { id: 'n', role: 'companion' } }));
setNodeLocation = vi.fn(async () => ({ updated: true, node: { id: 'n', role: 'companion' } }));
setNodePushToken = vi.fn(async () => ({ updated: true, node: { id: 'n', role: 'companion' } }));
sendAgentMessage = vi.fn(async () => ({ content: 'handoff response' }));
subscribeAgentStream = vi.fn(() => () => undefined);
subscribeAgentTyping = vi.fn(() => () => undefined);
@@ -230,6 +255,22 @@ describe('companion command', () => {
'ios-device',
'--heartbeat',
'45',
'--app-version',
'1.2.3',
'--status-text',
'ready',
'--latitude',
'37.3349',
'--longitude',
'-122.009',
'--location-source',
'gps',
'--push-token',
'0123456789abcdef0123456789abcdef',
'--push-topic',
'com.flynn.mobile',
'--push-environment',
'production',
'--handoff-timeout',
'5000',
'--export-bootstrap',
@@ -254,6 +295,26 @@ describe('companion command', () => {
expect(manifest.runtime.heartbeatSeconds).toBe(45);
expect(manifest.runtime.handoffTimeoutMs).toBe(5000);
expect(mockCreateCompanionBootstrapManifest).toHaveBeenCalledOnce();
expect(mockCreateCompanionBootstrapManifest).toHaveBeenCalledWith(expect.objectContaining({
status: {
appVersion: '1.2.3',
statusText: 'ready',
deviceName: undefined,
batteryPct: undefined,
powerSource: undefined,
},
location: {
latitude: 37.3349,
longitude: -122.009,
source: 'gps',
},
push: {
provider: 'apns',
token: '0123456789abcdef0123456789abcdef',
topic: 'com.flynn.mobile',
environment: 'production',
},
}));
expect(mockRuntimeCtorArgs).toEqual([]);
expect(mockRuntimeInstances).toEqual([]);
expect(errSpy).not.toHaveBeenCalled();
@@ -299,6 +360,62 @@ describe('companion command', () => {
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);
const program = new Command();
const { registerCompanionCommand } = await import('./companion.js');
registerCompanionCommand(program);
await program.parseAsync([
'node',
'test',
'companion',
'--once',
'--platform',
'android',
'--battery-pct',
'73',
'--power-source',
'battery',
'--latitude',
'40.7128',
'--longitude',
'-74.0060',
'--location-accuracy-meters',
'5',
'--push-token',
'abcdef0123456789abcdef0123456789',
]);
expect(mockRuntimeInstances[0]?.setNodeStatus).toHaveBeenCalledWith(expect.objectContaining({
platform: 'android',
batteryPct: 73,
powerSource: 'battery',
statusText: 'heartbeat',
}));
expect(mockRuntimeInstances[0]?.setNodeLocation).toHaveBeenCalledWith({
latitude: 40.7128,
longitude: -74.006,
accuracyMeters: 5,
altitudeMeters: undefined,
headingDegrees: undefined,
speedMps: undefined,
source: undefined,
capturedAt: undefined,
});
expect(mockRuntimeInstances[0]?.setNodePushToken).toHaveBeenCalledWith({
provider: 'fcm',
token: 'abcdef0123456789abcdef0123456789',
topic: undefined,
environment: undefined,
});
expect(errSpy).not.toHaveBeenCalled();
logSpy.mockRestore();
errSpy.mockRestore();
});
it('sets process exit code when options are invalid', async () => {
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const program = new Command();
@@ -312,4 +429,18 @@ describe('companion command', () => {
errSpy.mockRestore();
});
it('sets process exit code when location is partially provided', 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', '--once', '--latitude', '1']);
expect(errSpy).toHaveBeenCalled();
expect(process.exitCode).toBe(1);
errSpy.mockRestore();
});
});
+245 -5
View File
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
import { writeFile } from 'node:fs/promises';
import type { Command } from 'commander';
import { CompanionRuntimeClient } from '../companion/index.js';
import type { SetNodeStatusInput } from '../companion/index.js';
import type { SetNodeLocationInput, SetNodePushTokenInput, SetNodeStatusInput } from '../companion/index.js';
import { createCompanionBootstrapManifest } from '../companion/index.js';
import { getConfigPath, loadConfigSafe } from './shared.js';
@@ -20,6 +20,23 @@ interface CompanionCommandOptions {
heartbeat?: string;
handoff?: string;
handoffTimeout?: string;
appVersion?: string;
deviceName?: string;
statusText?: string;
batteryPct?: string;
powerSource?: string;
latitude?: string;
longitude?: string;
locationSource?: string;
locationAccuracyMeters?: string;
locationAltitudeMeters?: string;
locationHeadingDegrees?: string;
locationSpeedMps?: string;
locationCapturedAt?: string;
pushProvider?: string;
pushToken?: string;
pushTopic?: string;
pushEnvironment?: string;
exportBootstrap?: string;
once?: boolean;
}
@@ -86,14 +103,202 @@ function parseHandoffTimeoutMs(value: string | undefined): number {
return parsed;
}
function parseOptionalFloat(value: string | undefined, fieldName: string): number | undefined {
if (value === undefined) {
return undefined;
}
const parsed = Number.parseFloat(value);
if (!Number.isFinite(parsed)) {
throw new Error(`${fieldName} must be a number`);
}
return parsed;
}
function parseOptionalInteger(value: string | undefined, fieldName: string): number | undefined {
if (value === undefined) {
return undefined;
}
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed)) {
throw new Error(`${fieldName} must be an integer`);
}
return parsed;
}
function hasDefinedProperties(obj: Record<string, unknown>): boolean {
return Object.values(obj).some((value) => value !== undefined);
}
function resolveStatusOverrides(
options: CompanionCommandOptions,
): Omit<SetNodeStatusInput, 'platform'> {
const appVersion = options.appVersion?.trim();
const deviceName = options.deviceName?.trim();
const statusText = options.statusText?.trim();
const batteryPct = parseOptionalFloat(options.batteryPct, 'battery-pct');
const powerSourceRaw = options.powerSource?.trim();
if (batteryPct !== undefined && (batteryPct < 0 || batteryPct > 100)) {
throw new Error('battery-pct must be between 0 and 100');
}
if (
powerSourceRaw !== undefined
&& powerSourceRaw !== ''
&& powerSourceRaw !== 'ac'
&& powerSourceRaw !== 'battery'
&& powerSourceRaw !== 'unknown'
) {
throw new Error('power-source must be one of: ac, battery, unknown');
}
return {
appVersion: appVersion && appVersion.length > 0 ? appVersion : undefined,
deviceName: deviceName && deviceName.length > 0 ? deviceName : undefined,
statusText: statusText && statusText.length > 0 ? statusText : undefined,
batteryPct,
powerSource: (powerSourceRaw && powerSourceRaw.length > 0
? powerSourceRaw
: undefined) as SetNodeStatusInput['powerSource'] | undefined,
};
}
function resolveLocationInput(options: CompanionCommandOptions): SetNodeLocationInput | undefined {
const latitude = parseOptionalFloat(options.latitude, 'latitude');
const longitude = parseOptionalFloat(options.longitude, 'longitude');
const accuracyMeters = parseOptionalFloat(options.locationAccuracyMeters, 'location-accuracy-meters');
const altitudeMeters = parseOptionalFloat(options.locationAltitudeMeters, 'location-altitude-meters');
const headingDegrees = parseOptionalFloat(options.locationHeadingDegrees, 'location-heading-degrees');
const speedMps = parseOptionalFloat(options.locationSpeedMps, 'location-speed-mps');
const capturedAt = parseOptionalInteger(options.locationCapturedAt, 'location-captured-at');
const sourceRaw = options.locationSource?.trim();
const hasLocationDetails = [
latitude,
longitude,
accuracyMeters,
altitudeMeters,
headingDegrees,
speedMps,
capturedAt,
sourceRaw,
].some((value) => value !== undefined && value !== '');
if (!hasLocationDetails) {
return undefined;
}
if (latitude === undefined || longitude === undefined) {
throw new Error('latitude and longitude must be provided together');
}
if (latitude < -90 || latitude > 90) {
throw new Error('latitude must be between -90 and 90');
}
if (longitude < -180 || longitude > 180) {
throw new Error('longitude must be between -180 and 180');
}
if (headingDegrees !== undefined && (headingDegrees < 0 || headingDegrees >= 360)) {
throw new Error('location-heading-degrees must be between 0 (inclusive) and 360 (exclusive)');
}
if (speedMps !== undefined && speedMps < 0) {
throw new Error('location-speed-mps must be >= 0');
}
if (accuracyMeters !== undefined && accuracyMeters < 0) {
throw new Error('location-accuracy-meters must be >= 0');
}
if (capturedAt !== undefined && capturedAt < 0) {
throw new Error('location-captured-at must be >= 0');
}
if (
sourceRaw !== undefined
&& sourceRaw !== ''
&& sourceRaw !== 'gps'
&& sourceRaw !== 'network'
&& sourceRaw !== 'manual'
&& sourceRaw !== 'unknown'
) {
throw new Error('location-source must be one of: gps, network, manual, unknown');
}
return {
latitude,
longitude,
accuracyMeters,
altitudeMeters,
headingDegrees,
speedMps,
source: (sourceRaw && sourceRaw.length > 0
? sourceRaw
: undefined) as SetNodeLocationInput['source'] | undefined,
capturedAt,
};
}
function defaultPushProviderForPlatform(
platform: CompanionPlatform,
): SetNodePushTokenInput['provider'] | undefined {
if (platform === 'ios' || platform === 'macos') {
return 'apns';
}
if (platform === 'android') {
return 'fcm';
}
return undefined;
}
function resolvePushInput(
options: CompanionCommandOptions,
platform: CompanionPlatform,
): SetNodePushTokenInput | undefined {
const pushToken = options.pushToken?.trim();
const pushProviderRaw = options.pushProvider?.trim();
const pushTopic = options.pushTopic?.trim();
const pushEnvironmentRaw = options.pushEnvironment?.trim();
const hasPushDetails = [pushToken, pushProviderRaw, pushTopic, pushEnvironmentRaw]
.some((value) => value !== undefined && value !== '');
if (!hasPushDetails) {
return undefined;
}
if (!pushToken || pushToken.length < 16) {
throw new Error('push-token must be provided and be at least 16 characters');
}
const provider = (pushProviderRaw && pushProviderRaw.length > 0
? pushProviderRaw
: defaultPushProviderForPlatform(platform));
if (provider !== 'apns' && provider !== 'fcm') {
throw new Error('push-provider is required for non-mobile platforms when push-token is set');
}
if (
pushEnvironmentRaw !== undefined
&& pushEnvironmentRaw !== ''
&& pushEnvironmentRaw !== 'sandbox'
&& pushEnvironmentRaw !== 'production'
) {
throw new Error('push-environment must be one of: sandbox, production');
}
return {
provider,
token: pushToken,
topic: pushTopic && pushTopic.length > 0 ? pushTopic : undefined,
environment: (pushEnvironmentRaw && pushEnvironmentRaw.length > 0
? pushEnvironmentRaw
: undefined) as SetNodePushTokenInput['environment'] | undefined,
};
}
async function publishHeartbeat(
runtime: CompanionRuntimeClient,
platform: CompanionPlatform,
statusOverrides: Omit<SetNodeStatusInput, 'platform'>,
): Promise<void> {
await runtime.setNodeStatus({
platform,
statusText: 'heartbeat',
powerSource: 'unknown',
appVersion: statusOverrides.appVersion,
deviceName: statusOverrides.deviceName,
statusText: statusOverrides.statusText ?? 'heartbeat',
batteryPct: statusOverrides.batteryPct,
powerSource: statusOverrides.powerSource ?? 'unknown',
});
}
@@ -108,6 +313,9 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
const heartbeatSeconds = parseHeartbeatSeconds(options.heartbeat);
const handoffMessage = options.handoff?.trim();
const handoffTimeoutMs = parseHandoffTimeoutMs(options.handoffTimeout);
const statusOverrides = resolveStatusOverrides(options);
const locationInput = resolveLocationInput(options);
const pushInput = resolvePushInput(options, platform);
const exportBootstrapPath = options.exportBootstrap?.trim();
if (exportBootstrapPath) {
@@ -121,6 +329,9 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
heartbeatSeconds,
handoffTimeoutMs,
autoReconnect: !options.once,
status: hasDefinedProperties(statusOverrides) ? statusOverrides : undefined,
location: locationInput,
push: pushInput,
});
const body = `${JSON.stringify(manifest, null, 2)}\n`;
if (exportBootstrapPath === '-') {
@@ -156,7 +367,7 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
return;
}
heartbeatTimer = setInterval(() => {
void publishHeartbeat(runtime, platform).catch((error: unknown) => {
void publishHeartbeat(runtime, platform, statusOverrides).catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
console.error(`Heartbeat failed: ${message}`);
});
@@ -182,12 +393,24 @@ export async function runCompanionSession(options: CompanionCommandOptions): Pro
capabilities,
});
await publishHeartbeat(runtime, platform);
await publishHeartbeat(runtime, platform, statusOverrides);
if (locationInput) {
await runtime.setNodeLocation(locationInput);
}
if (pushInput) {
await runtime.setNodePushToken(pushInput);
}
const verb = label === 'connected' ? 'Connected' : 'Reconnected';
console.log(`${verb} companion node ${register.node.id} (${platform}, role=${role})`);
console.log(`Gateway: ${gatewayUrl}`);
console.log(`Capabilities: ${capabilities.join(', ') || '(none)'}`);
if (locationInput) {
console.log(`Location bootstrap: ${locationInput.latitude},${locationInput.longitude}`);
}
if (pushInput) {
console.log(`Push bootstrap: provider=${pushInput.provider}`);
}
startHeartbeat();
})();
@@ -279,6 +502,23 @@ export function registerCompanionCommand(program: Command): void {
.option('--platform <platform>', 'Node platform (macos|ios|android|linux|windows|unknown)', 'macos')
.option('--capability <name...>', 'Capability list override')
.option('--heartbeat <seconds>', 'Heartbeat interval in seconds', '30')
.option('--app-version <value>', 'Status metadata appVersion for node.status.set')
.option('--device-name <value>', 'Status metadata deviceName for node.status.set')
.option('--status-text <value>', 'Status metadata statusText for node.status.set')
.option('--battery-pct <value>', 'Status metadata battery percent (0-100)')
.option('--power-source <value>', 'Status metadata power source (ac|battery|unknown)')
.option('--latitude <value>', 'Optional node location latitude')
.option('--longitude <value>', 'Optional node location longitude')
.option('--location-source <value>', 'Optional location source (gps|network|manual|unknown)')
.option('--location-accuracy-meters <value>', 'Optional location accuracy in meters')
.option('--location-altitude-meters <value>', 'Optional location altitude in meters')
.option('--location-heading-degrees <value>', 'Optional location heading in degrees [0,360)')
.option('--location-speed-mps <value>', 'Optional location speed in meters per second')
.option('--location-captured-at <value>', 'Optional location capturedAt epoch milliseconds')
.option('--push-provider <value>', 'Optional push provider (apns|fcm)')
.option('--push-token <value>', 'Optional push token for node.push_token.set')
.option('--push-topic <value>', 'Optional push topic (typically APNs bundle ID)')
.option('--push-environment <value>', 'Optional push environment (sandbox|production)')
.option('--handoff <message>', 'Optional one-shot agent message handoff after registration')
.option('--handoff-timeout <ms>', 'Handoff timeout in milliseconds', '120000')
.option(
+36
View File
@@ -13,6 +13,24 @@ describe('createCompanionBootstrapManifest', () => {
heartbeatSeconds: 45,
handoffTimeoutMs: 5000,
autoReconnect: true,
status: {
appVersion: '1.2.3',
deviceName: 'iPhone',
statusText: 'ready',
batteryPct: 88,
powerSource: 'battery',
},
location: {
latitude: 37.3349,
longitude: -122.009,
source: 'gps',
},
push: {
provider: 'apns',
token: '0123456789abcdef0123456789abcdef',
topic: 'com.flynn.app',
environment: 'production',
},
generatedAt: new Date('2026-02-27T00:00:00.000Z'),
});
@@ -34,6 +52,24 @@ describe('createCompanionBootstrapManifest', () => {
handoffTimeoutMs: 5000,
autoReconnect: true,
},
status: {
appVersion: '1.2.3',
deviceName: 'iPhone',
statusText: 'ready',
batteryPct: 88,
powerSource: 'battery',
},
location: {
latitude: 37.3349,
longitude: -122.009,
source: 'gps',
},
push: {
provider: 'apns',
token: '0123456789abcdef0123456789abcdef',
topic: 'com.flynn.app',
environment: 'production',
},
});
});
+15 -1
View File
@@ -1,4 +1,9 @@
import type { RegisterNodeInput, SetNodeStatusInput } from './runtimeClient.js';
import type {
RegisterNodeInput,
SetNodeStatusInput,
SetNodeLocationInput,
SetNodePushTokenInput,
} from './runtimeClient.js';
export type CompanionBootstrapPlatform = SetNodeStatusInput['platform'];
@@ -17,6 +22,9 @@ export interface CompanionBootstrapManifest {
handoffTimeoutMs: number;
autoReconnect: boolean;
};
status?: Omit<SetNodeStatusInput, 'platform'>;
location?: SetNodeLocationInput;
push?: SetNodePushTokenInput;
}
export interface CreateCompanionBootstrapManifestInput {
@@ -29,6 +37,9 @@ export interface CreateCompanionBootstrapManifestInput {
heartbeatSeconds: number;
handoffTimeoutMs: number;
autoReconnect: boolean;
status?: Omit<SetNodeStatusInput, 'platform'>;
location?: SetNodeLocationInput;
push?: SetNodePushTokenInput;
generatedAt?: Date;
}
@@ -55,5 +66,8 @@ export function createCompanionBootstrapManifest(
handoffTimeoutMs: input.handoffTimeoutMs,
autoReconnect: input.autoReconnect,
},
...(input.status ? { status: input.status } : {}),
...(input.location ? { location: input.location } : {}),
...(input.push ? { push: input.push } : {}),
};
}