Spaces:
Running
Running
File size: 10,755 Bytes
6ce4ca6 c3f65a8 6ce4ca6 3cdf7b9 3165745 6ce4ca6 c3f65a8 6ce4ca6 8173aa6 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 c3f65a8 6ce4ca6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
import { RemoteCompute } from './RemoteCompute.svelte';
import type { Position3D } from '$lib/types/positionable.js';
import { generateName } from '$lib/utils/generateName.js';
import { positionManager } from '$lib/utils/positionManager.js';
import {
rootGet,
healthCheckHealthGet,
listSessionsSessionsGet,
createSessionSessionsPost,
startInferenceSessionsSessionIdStartPost,
stopInferenceSessionsSessionIdStopPost,
deleteSessionSessionsSessionIdDelete
} from '@robothub/inference-server-client';
import { settings } from '$lib/runes/settings.svelte';
import type {
CreateSessionRequest,
CreateSessionResponse
} from '@robothub/inference-server-client';
export interface AISessionConfig {
sessionId: string;
policyPath: string;
cameraNames: string[];
transportServerUrl: string;
workspaceId?: string;
}
export interface AISessionResponse {
workspace_id: string;
camera_room_ids: Record<string, string>;
joint_input_room_id: string;
joint_output_room_id: string;
}
export interface AISessionStatus {
session_id: string;
status: 'initializing' | 'ready' | 'running' | 'stopped';
policy_path: string;
camera_names: string[];
workspace_id: string;
rooms: {
workspace_id: string;
camera_room_ids: Record<string, string>;
joint_input_room_id: string;
joint_output_room_id: string;
};
stats: {
inference_count: number;
commands_sent: number;
joints_received: number;
images_received: Record<string, number>;
errors: number;
actions_in_queue: number;
};
inference_stats?: {
inference_count: number;
total_inference_time: number;
average_inference_time: number;
average_fps: number;
is_loaded: boolean;
device: string;
};
error_message?: string;
}
export class RemoteComputeManager {
private _computes = $state<RemoteCompute[]>([]);
constructor() {
// No client initialization needed anymore
}
// Reactive getters
get computes(): RemoteCompute[] {
return this._computes;
}
get computeCount(): number {
return this._computes.length;
}
get runningComputes(): RemoteCompute[] {
return this._computes.filter(compute => compute.status === 'running');
}
/**
* Create a new AI compute instance
*/
createCompute(id?: string, name?: string, position?: Position3D): RemoteCompute {
const computeId = id || generateName();
// Check if compute already exists
if (this._computes.find(c => c.id === computeId)) {
throw new Error(`Compute with ID ${computeId} already exists`);
}
// Create compute instance
const compute = new RemoteCompute(computeId, name);
// Set position (from position manager if not provided)
compute.position = position || positionManager.getNextPosition();
// Add to reactive array
this._computes.push(compute);
console.log(`Created compute ${computeId} at position (${compute.position.x.toFixed(1)}, ${compute.position.y.toFixed(1)}, ${compute.position.z.toFixed(1)}). Total computes: ${this._computes.length}`);
return compute;
}
/**
* Get compute by ID
*/
getCompute(id: string): RemoteCompute | undefined {
return this._computes.find(c => c.id === id);
}
/**
* Remove a compute instance
*/
async removeCompute(id: string): Promise<void> {
const computeIndex = this._computes.findIndex(c => c.id === id);
if (computeIndex === -1) return;
const compute = this._computes[computeIndex];
// Clean up compute resources
await this.stopSession(id);
await this.deleteSession(id);
// Remove from reactive array
this._computes.splice(computeIndex, 1);
console.log(`Removed compute ${id}. Remaining computes: ${this._computes.length}`);
}
/**
* Create an Inference Session
*/
async createSession(computeId: string, config: AISessionConfig): Promise<{ success: boolean; error?: string; data?: AISessionResponse }> {
const compute = this.getCompute(computeId);
if (!compute) {
return { success: false, error: `Compute ${computeId} not found` };
}
try {
const request: CreateSessionRequest = {
session_id: config.sessionId,
policy_path: config.policyPath,
camera_names: config.cameraNames,
transport_server_url: config.transportServerUrl,
workspace_id: config.workspaceId || undefined,
};
const response = await createSessionSessionsPost({
body: request,
baseUrl: settings.inferenceServerUrl
});
if (!response.data) {
throw new Error('Failed to create session - no data returned');
}
const data: CreateSessionResponse = response.data;
// Update compute with session info
compute.sessionId = config.sessionId;
compute.status = 'ready';
compute.sessionConfig = config;
compute.sessionData = {
workspace_id: data.workspace_id,
camera_room_ids: data.camera_room_ids,
joint_input_room_id: data.joint_input_room_id,
joint_output_room_id: data.joint_output_room_id
};
return { success: true, data: compute.sessionData };
} catch (error) {
console.error(`Failed to create session for compute ${computeId}:`, error);
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
/**
* Start inference for a session
*/
async startSession(computeId: string): Promise<{ success: boolean; error?: string }> {
const compute = this.getCompute(computeId);
if (!compute || !compute.sessionId) {
return { success: false, error: 'No session to start' };
}
try {
await startInferenceSessionsSessionIdStartPost({
path: { session_id: compute.sessionId },
baseUrl: settings.inferenceServerUrl
});
compute.status = 'running';
return { success: true };
} catch (error) {
console.error(`Failed to start session for compute ${computeId}:`, error);
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
/**
* Stop inference for a session
*/
async stopSession(computeId: string): Promise<{ success: boolean; error?: string }> {
const compute = this.getCompute(computeId);
if (!compute || !compute.sessionId) {
return { success: false, error: 'No session to stop' };
}
try {
await stopInferenceSessionsSessionIdStopPost({
path: { session_id: compute.sessionId },
baseUrl: settings.inferenceServerUrl
});
compute.status = 'stopped';
return { success: true };
} catch (error) {
console.error(`Failed to stop session for compute ${computeId}:`, error);
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
/**
* Delete a session
*/
async deleteSession(computeId: string): Promise<{ success: boolean; error?: string }> {
const compute = this.getCompute(computeId);
if (!compute || !compute.sessionId) {
return { success: true }; // Already deleted
}
try {
await deleteSessionSessionsSessionIdDelete({
path: { session_id: compute.sessionId },
baseUrl: settings.inferenceServerUrl
});
// Reset compute session info
compute.sessionId = null;
compute.status = 'disconnected';
compute.sessionConfig = null;
compute.sessionData = null;
return { success: true };
} catch (error) {
console.error(`Failed to delete session for compute ${computeId}:`, error);
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
/**
* Get session status
*/
async getSessionStatus(computeId: string): Promise<{ success: boolean; data?: AISessionStatus; error?: string }> {
const compute = this.getCompute(computeId);
if (!compute || !compute.sessionId) {
return { success: false, error: 'No session found' };
}
try {
// Get all sessions and find the one we want
const response = await listSessionsSessionsGet({
baseUrl: settings.inferenceServerUrl
});
if (!response.data) {
throw new Error('Failed to get sessions list');
}
const session = response.data.find(s => s.session_id === compute.sessionId);
if (!session) {
throw new Error(`Session ${compute.sessionId} not found`);
}
// Update compute status
compute.status = session.status as 'initializing' | 'ready' | 'running' | 'stopped';
// Convert to AISessionStatus format
const sessionStatus: AISessionStatus = {
session_id: session.session_id,
status: session.status as 'initializing' | 'ready' | 'running' | 'stopped',
policy_path: session.policy_path,
camera_names: session.camera_names,
workspace_id: session.workspace_id,
rooms: session.rooms as any,
stats: session.stats as any,
inference_stats: session.inference_stats as any,
error_message: session.error_message || undefined
};
return { success: true, data: sessionStatus };
} catch (error) {
console.error(`Failed to get session status for compute ${computeId}:`, error);
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
/**
* Check AI server health
*/
async checkServerHealth(): Promise<{ success: boolean; data?: any; error?: string }> {
try {
const healthResponse = await rootGet({
baseUrl: settings.inferenceServerUrl
});
if (!healthResponse.data) {
return { success: false, error: 'Server is not healthy' };
}
// Get detailed health info
const detailedHealthResponse = await healthCheckHealthGet({
baseUrl: settings.inferenceServerUrl
});
return { success: true, data: detailedHealthResponse.data };
} catch (error) {
console.error('Failed to check AI server health:', error);
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
/**
* Clean up all computes
*/
async destroy(): Promise<void> {
const cleanupPromises = this._computes.map(async (compute) => {
await this.stopSession(compute.id);
await this.deleteSession(compute.id);
});
await Promise.allSettled(cleanupPromises);
this._computes.length = 0;
}
}
// Global compute manager instance
export const remoteComputeManager = new RemoteComputeManager(); |