Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion extensions/cli/src/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { type AssistantConfig } from "@continuedev/sdk";

// Export command functions
export { chat } from "./chat.js";
export { review } from "./review.js";
export { login } from "./login.js";
export { logout } from "./logout.js";
export { listSessionsCommand } from "./ls.js";
export { remote } from "./remote.js";
export { review } from "./review.js";
export { serve } from "./serve.js";

export interface SlashCommand {
Expand Down Expand Up @@ -101,6 +101,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [
description: "Exit the chat",
category: "system",
},
{
name: "jobs",
description: "List background jobs",
category: "system",
},
];

// Remote mode specific commands
Expand Down
220 changes: 220 additions & 0 deletions extensions/cli/src/services/BackgroundJobManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import { ChildProcess, spawn } from "child_process";
import { EventEmitter } from "events";

import { logger } from "../util/logger.js";

export type BackgroundJobStatus =
| "pending"
| "running"
| "completed"
| "failed"
| "cancelled";

export interface BackgroundJob {
id: string;
status: BackgroundJobStatus;
command: string;
output: string;
exitCode: number | null;
startTime: Date;
endTime: Date | null;
error?: string;
}

const MAX_CONCURRENT_JOBS = 5;

export class BackgroundJobManager extends EventEmitter {
private jobs: Map<string, BackgroundJob> = new Map();
private processes: Map<string, ChildProcess> = new Map();
private jobCounter = 0;

createJob(command: string): BackgroundJob | null {
const runningCount = this.getRunningJobCount();
if (runningCount >= MAX_CONCURRENT_JOBS) {
logger.warn(
`Cannot create background job: limit of ${MAX_CONCURRENT_JOBS} reached`,
);
return null;
}

const id = `bg-${++this.jobCounter}-${Date.now()}`;
const job: BackgroundJob = {
id,
status: "pending",
command,
output: "",
exitCode: null,
startTime: new Date(),
endTime: null,
};

this.jobs.set(id, job);
this.emit("jobCreated", job);
return job;
}

startJob(jobId: string, shell: string, args: string[]): ChildProcess | null {
const job = this.jobs.get(jobId);
if (!job) {
logger.error(`Cannot start job ${jobId}: job not found`);
return null;
}

job.status = "running";
this.emit("jobStarted", job);

const child = spawn(shell, args, { stdio: "pipe" });
this.processes.set(jobId, child);

child.stdout?.on("data", (data: Buffer) => {
this.appendOutput(jobId, data.toString());
});

child.stderr?.on("data", (data: Buffer) => {
this.appendOutput(jobId, data.toString());
});

child.on("close", (code: number | null) => {
this.completeJob(jobId, code ?? 0);
});

child.on("error", (error: Error) => {
this.failJob(jobId, error.message);
});

return child;
}

createJobWithProcess(
command: string,
child: ChildProcess,
existingOutput: string = "",
): BackgroundJob | null {
const runningCount = this.getRunningJobCount();
if (runningCount >= MAX_CONCURRENT_JOBS) {
logger.warn(
`Cannot create background job: limit of ${MAX_CONCURRENT_JOBS} reached`,
);
return null;
}

const id = `bg-${++this.jobCounter}-${Date.now()}`;
const job: BackgroundJob = {
id,
status: "running",
command,
output: existingOutput,
exitCode: null,
startTime: new Date(),
endTime: null,
};

this.jobs.set(id, job);
this.processes.set(id, child);
this.emit("jobCreated", job);

child.stdout?.on("data", (data: Buffer) => {
this.appendOutput(id, data.toString());
});

child.stderr?.on("data", (data: Buffer) => {
this.appendOutput(id, data.toString());
});

child.on("close", (code: number | null) => {
this.completeJob(id, code ?? 0);
});

child.on("error", (error: Error) => {
this.failJob(id, error.message);
});

return job;
}

appendOutput(jobId: string, data: string): void {
const job = this.jobs.get(jobId);
if (job) {
job.output += data;
this.emit("jobOutput", job, data);
}
}

completeJob(jobId: string, exitCode: number): void {
const job = this.jobs.get(jobId);
if (job) {
job.status = exitCode === 0 ? "completed" : "failed";
job.exitCode = exitCode;
job.endTime = new Date();
this.processes.delete(jobId);
this.emit("jobCompleted", job);
}
}

failJob(jobId: string, error: string): void {
const job = this.jobs.get(jobId);
if (job) {
job.status = "failed";
job.error = error;
job.endTime = new Date();
this.processes.delete(jobId);
this.emit("jobFailed", job);
}
}

cancelJob(jobId: string): boolean {
const job = this.jobs.get(jobId);
const process = this.processes.get(jobId);

if (!job) return false;

if (process) {
process.kill();
this.processes.delete(jobId);
}

job.status = "cancelled";
job.endTime = new Date();
this.emit("jobCancelled", job);
return true;
}

getJob(jobId: string): BackgroundJob | undefined {
return this.jobs.get(jobId);
}

getRunningJobs(): BackgroundJob[] {
return Array.from(this.jobs.values()).filter(
(job) => job.status === "running" || job.status === "pending",
);
}

getAllJobs(): BackgroundJob[] {
return Array.from(this.jobs.values());
}

getRunningJobCount(): number {
return this.getRunningJobs().length;
}

killAllJobs(): void {
for (const [jobId, process] of this.processes) {
process.kill();
const job = this.jobs.get(jobId);
if (job) {
job.status = "cancelled";
job.endTime = new Date();
}
}
this.processes.clear();
this.emit("allJobsKilled");
}

reset(): void {
this.killAllJobs();
this.jobs.clear();
this.jobCounter = 0;
}
}

export const backgroundJobManager = new BackgroundJobManager();
9 changes: 9 additions & 0 deletions extensions/cli/src/services/BackgroundSignalManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { EventEmitter } from "events";

export class BackgroundSignalManager extends EventEmitter {
signalBackground(): void {
this.emit("backgroundRequested");
}
}

export const backgroundSignalManager = new BackgroundSignalManager();
2 changes: 2 additions & 0 deletions extensions/cli/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AgentFileService } from "./AgentFileService.js";
import { ApiClientService } from "./ApiClientService.js";
import { ArtifactUploadService } from "./ArtifactUploadService.js";
import { AuthService } from "./AuthService.js";
import { backgroundJobManager } from "./BackgroundJobManager.js";
import { ChatHistoryService } from "./ChatHistoryService.js";
import { ConfigService } from "./ConfigService.js";
import { FileIndexService } from "./FileIndexService.js";
Expand Down Expand Up @@ -387,6 +388,7 @@ export const services = {
toolPermissions: toolPermissionService,
artifactUpload: artifactUploadService,
gitAiIntegration: gitAiIntegrationService,
backgroundJobs: backgroundJobManager,
} as const;

export type ServicesType = typeof services;
Expand Down
5 changes: 5 additions & 0 deletions extensions/cli/src/services/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ export interface ArtifactUploadServiceState {
lastError: string | null;
}

export type {
BackgroundJob,
BackgroundJobStatus,
} from "./BackgroundJobManager.js";
export type { ChatHistoryState } from "./ChatHistoryService.js";
export type { FileIndexServiceState } from "./FileIndexService.js";
export type { GitAiIntegrationServiceState } from "./GitAiIntegrationService.js";
Expand All @@ -153,6 +157,7 @@ export const SERVICE_NAMES = {
AGENT_FILE: "agentFile",
ARTIFACT_UPLOAD: "artifactUpload",
GIT_AI_INTEGRATION: "gitAiIntegration",
BACKGROUND_JOBS: "backgroundJobs",
} as const;

/**
Expand Down
32 changes: 32 additions & 0 deletions extensions/cli/src/slashCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { getAllSlashCommands } from "./commands/commands.js";
import { handleInit } from "./commands/init.js";
import { handleInfoSlashCommand } from "./infoScreen.js";
import { backgroundJobManager } from "./services/BackgroundJobManager.js";
import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
import { getCurrentSession, updateSessionTitle } from "./session.js";
import { posthogService } from "./telemetry/posthogService.js";
Expand Down Expand Up @@ -169,6 +170,36 @@ function handleTitle(args: string[]) {
}
}

function handleJobs() {
const allJobs = backgroundJobManager.getAllJobs();
if (allJobs.length === 0) {
return {
exit: false,
output: chalk.dim("No background jobs"),
};
}

const lines = [chalk.bold("Background Jobs:")];
for (const job of allJobs) {
const statusColor =
job.status === "running" || job.status === "pending"
? chalk.yellow
: job.status === "completed"
? chalk.green
: chalk.red;
const duration = job.endTime
? `${Math.round((job.endTime.getTime() - job.startTime.getTime()) / 1000)}s`
: `${Math.round((Date.now() - job.startTime.getTime()) / 1000)}s`;
lines.push(
` ${statusColor(job.status.padEnd(10))} ${chalk.cyan(job.id)} ${chalk.dim(`(${duration})`)} ${job.command.substring(0, 40)}${job.command.length > 40 ? "..." : ""}`,
);
}
return {
exit: false,
output: lines.join("\n"),
};
}

const commandHandlers: Record<string, CommandHandler> = {
help: handleHelp,
clear: () => {
Expand Down Expand Up @@ -203,6 +234,7 @@ const commandHandlers: Record<string, CommandHandler> = {
update: () => {
return { openUpdateSelector: true };
},
jobs: handleJobs,
};

export async function handleSlashCommands(
Expand Down
Loading
Loading