Skip to content
Open
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
218 changes: 218 additions & 0 deletions extensions/cli/src/services/BackgroundJobService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import { ChildProcess, spawn } from "child_process";

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;
const MAX_OUTPUT_LINES = 1000;

/**
* Service for managing background job execution and lifecycle
* Handles spawning, tracking, and cleanup of background processes
*/
export class BackgroundJobService {
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);
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";

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

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

@cubic-dev-ai cubic-dev-ai bot Feb 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Output capture decodes each Buffer chunk with toString(), which can corrupt multi‑byte characters split across chunks. Use StringDecoder or setEncoding on the streams to preserve UTF‑8 sequences across chunk boundaries.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At extensions/cli/src/services/BackgroundJobService.ts, line 72:

<comment>Output capture decodes each Buffer chunk with toString(), which can corrupt multi‑byte characters split across chunks. Use StringDecoder or setEncoding on the streams to preserve UTF‑8 sequences across chunk boundaries.</comment>

<file context>
@@ -0,0 +1,218 @@
+    this.processes.set(jobId, child);
+
+    child.stdout?.on("data", (data: Buffer) => {
+      this.appendOutput(jobId, data.toString());
+    });
+
</file context>
Fix with Cubic

});

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);

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;
}

// todo: improve write efficiency with ring buffer or similar
appendOutput(jobId: string, data: string): void {
const job = this.jobs.get(jobId);
if (job) {
job.output += data;
const lines = job.output.split("\n");
if (lines.length > MAX_OUTPUT_LINES) {
job.output = lines.slice(-MAX_OUTPUT_LINES).join("\n");
}
}
}

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

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);
}
}

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();
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();
}
}

export const backgroundJobService = new BackgroundJobService();
1 change: 1 addition & 0 deletions extensions/cli/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ export const services = {
toolPermissions: toolPermissionService,
artifactUpload: artifactUploadService,
gitAiIntegration: gitAiIntegrationService,
backgroundJobs: backgroundJobService,
} 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 "./BackgroundJobService.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
5 changes: 5 additions & 0 deletions extensions/cli/src/slashCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ function handleTitle(args: string[]) {
}
}

function handleJobs() {
return { openJobsSelector: true };
}

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

export async function handleSlashCommands(
Expand Down
64 changes: 64 additions & 0 deletions extensions/cli/src/tools/checkBackgroundJob.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { services } from "../services/index.js";

import { Tool } from "./types.js";

export const checkBackgroundJobTool: Tool = {
name: "CheckBackgroundJob",
displayName: "Check Background Job",
description: `Check the status and output of a background job.
Returns the current status, exit code (if finished), and all available output.
If the job is still running, returns partial output with "running" status.`,
parameters: {
type: "object",
required: ["job_id"],
properties: {
job_id: {
type: "string",
description:
"The ID of the background job to check (e.g., bg-1-1234567890)",
},
},
},
readonly: true,
isBuiltIn: true,
run: async ({ job_id }: { job_id: string }): Promise<string> => {
const job = services.backgroundJobs.getJob(job_id);

if (!job) {
return JSON.stringify({
error: `Job ${job_id} not found`,
available_jobs: services.backgroundJobs.getAllJobs().map((j) => ({
id: j.id,
status: j.status,
command:
j.command.substring(0, 50) + (j.command.length > 50 ? "..." : ""),
})),
});
}

const result: Record<string, unknown> = {
job_id: job.id,
status: job.status,
command: job.command,
output: job.output,
started_at: job.startTime.toISOString(),
};

if (job.endTime) {
result.ended_at = job.endTime.toISOString();
result.duration_seconds = Math.round(
(job.endTime.getTime() - job.startTime.getTime()) / 1000,
);
}

if (job.exitCode !== null) {
result.exit_code = job.exitCode;
}

if (job.error) {
result.error = job.error;
}

return JSON.stringify(result, null, 2);
},
};
2 changes: 2 additions & 0 deletions extensions/cli/src/tools/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { telemetryService } from "../telemetry/telemetryService.js";
import { logger } from "../util/logger.js";

import { ALL_BUILT_IN_TOOLS } from "./allBuiltIns.js";
import { checkBackgroundJobTool } from "./checkBackgroundJob.js";
import { editTool } from "./edit.js";
import { exitTool } from "./exit.js";
import { fetchTool } from "./fetch.js";
Expand Down Expand Up @@ -68,6 +69,7 @@ const BASE_BUILTIN_TOOLS: Tool[] = [
runTerminalCommandTool,
fetchTool,
writeChecklistTool,
checkBackgroundJobTool,
];

const BUILTIN_SEARCH_TOOLS: Tool[] = [searchCodeTool];
Expand Down
Loading
Loading