Merge pull request #10285 from uinstinct/cli-background-bash-exec
feat: bash tool execution in background
This commit is contained in:
commit
c1f9518574
23 changed files with 736 additions and 10 deletions
|
|
@ -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 {
|
||||
|
|
@ -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
|
||||
|
|
|
|||
224
extensions/cli/src/services/BackgroundJobService.ts
Normal file
224
extensions/cli/src/services/BackgroundJobService.ts
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
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?.setEncoding("utf8");
|
||||
child.stderr?.setEncoding("utf8");
|
||||
|
||||
child.stdout?.on("data", (data: string) => {
|
||||
this.appendOutput(jobId, data);
|
||||
});
|
||||
|
||||
child.stderr?.on("data", (data: string) => {
|
||||
this.appendOutput(jobId, data);
|
||||
});
|
||||
|
||||
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?.setEncoding("utf8");
|
||||
child.stderr?.setEncoding("utf8");
|
||||
|
||||
child.stdout?.on("data", (data: string) => {
|
||||
this.appendOutput(id, data);
|
||||
});
|
||||
|
||||
child.stderr?.on("data", (data: string) => {
|
||||
this.appendOutput(id, data);
|
||||
});
|
||||
|
||||
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();
|
||||
|
|
@ -2,7 +2,6 @@ import {
|
|||
AUTO_MODE_POLICIES,
|
||||
PLAN_MODE_POLICIES,
|
||||
} from "src/permissions/defaultPolicies.js";
|
||||
import { ALL_BUILT_IN_TOOLS } from "src/tools/allBuiltIns.js";
|
||||
|
||||
import { ensurePermissionsYamlExists } from "../permissions/permissionsYamlLoader.js";
|
||||
import { resolvePermissionPrecedence } from "../permissions/precedenceResolver.js";
|
||||
|
|
@ -11,6 +10,7 @@ import {
|
|||
ToolPermissionPolicy,
|
||||
ToolPermissions,
|
||||
} from "../permissions/types.js";
|
||||
import { BUILT_IN_TOOL_NAMES } from "../tools/builtInToolNames.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
|
|
@ -147,7 +147,7 @@ export class ToolPermissionService
|
|||
}));
|
||||
policies.push(...allowed);
|
||||
const specificBuiltInSet = new Set(specificBuiltIns);
|
||||
const notMentioned = ALL_BUILT_IN_TOOLS.map((t) => t.name).filter(
|
||||
const notMentioned = BUILT_IN_TOOL_NAMES.filter(
|
||||
(name) => !specificBuiltInSet.has(name),
|
||||
);
|
||||
const disallowed: ToolPermissionPolicy[] = notMentioned.map((tool) => ({
|
||||
|
|
|
|||
|
|
@ -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 { backgroundJobService } from "./BackgroundJobService.js";
|
||||
import { ChatHistoryService } from "./ChatHistoryService.js";
|
||||
import { ConfigService } from "./ConfigService.js";
|
||||
import { FileIndexService } from "./FileIndexService.js";
|
||||
|
|
@ -387,6 +388,7 @@ export const services = {
|
|||
toolPermissions: toolPermissionService,
|
||||
artifactUpload: artifactUploadService,
|
||||
gitAiIntegration: gitAiIntegrationService,
|
||||
backgroundJobs: backgroundJobService,
|
||||
} as const;
|
||||
|
||||
export type ServicesType = typeof services;
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
@ -153,6 +157,7 @@ export const SERVICE_NAMES = {
|
|||
AGENT_FILE: "agentFile",
|
||||
ARTIFACT_UPLOAD: "artifactUpload",
|
||||
GIT_AI_INTEGRATION: "gitAiIntegration",
|
||||
BACKGROUND_JOBS: "backgroundJobs",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -169,6 +169,10 @@ function handleTitle(args: string[]) {
|
|||
}
|
||||
}
|
||||
|
||||
function handleJobs() {
|
||||
return { openJobsSelector: true };
|
||||
}
|
||||
|
||||
const commandHandlers: Record<string, CommandHandler> = {
|
||||
help: handleHelp,
|
||||
clear: () => {
|
||||
|
|
@ -203,6 +207,7 @@ const commandHandlers: Record<string, CommandHandler> = {
|
|||
update: () => {
|
||||
return { openUpdateSelector: true };
|
||||
},
|
||||
jobs: handleJobs,
|
||||
};
|
||||
|
||||
export async function handleSlashCommands(
|
||||
|
|
|
|||
25
extensions/cli/src/tools/builtInToolNames.ts
Normal file
25
extensions/cli/src/tools/builtInToolNames.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* Static list of built-in tool names.
|
||||
* Kept separate from allBuiltIns.ts to avoid circular dependency:
|
||||
* ToolPermissionService -> allBuiltIns -> runTerminalCommand -> services/index -> ToolPermissionService
|
||||
*
|
||||
* When adding a new built-in tool, update both this list and ALL_BUILT_IN_TOOLS in allBuiltIns.ts.
|
||||
*/
|
||||
export const BUILT_IN_TOOL_NAMES = [
|
||||
"Edit",
|
||||
"Exit",
|
||||
"Fetch",
|
||||
"List",
|
||||
"MultiEdit",
|
||||
"Read",
|
||||
"ReportFailure",
|
||||
"Bash",
|
||||
"Search",
|
||||
"Status",
|
||||
"Subagent",
|
||||
"Skills",
|
||||
"UploadArtifact",
|
||||
"Diff",
|
||||
"Checklist",
|
||||
"Write",
|
||||
] as const;
|
||||
67
extensions/cli/src/tools/checkBackgroundJob.ts
Normal file
67
extensions/cli/src/tools/checkBackgroundJob.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import type { BackgroundJob } from "../services/BackgroundJobService.js";
|
||||
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: BackgroundJob) => ({
|
||||
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);
|
||||
},
|
||||
};
|
||||
|
|
@ -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";
|
||||
|
|
@ -68,6 +69,7 @@ const BASE_BUILTIN_TOOLS: Tool[] = [
|
|||
runTerminalCommandTool,
|
||||
fetchTool,
|
||||
writeChecklistTool,
|
||||
checkBackgroundJobTool,
|
||||
];
|
||||
|
||||
const BUILTIN_SEARCH_TOOLS: Tool[] = [searchCodeTool];
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { spawn } from "child_process";
|
||||
import { ChildProcess, spawn } from "child_process";
|
||||
import fs from "fs";
|
||||
|
||||
import {
|
||||
|
|
@ -6,11 +6,15 @@ import {
|
|||
type ToolPolicy,
|
||||
} from "@continuedev/terminal-security";
|
||||
|
||||
import { backgroundJobService } from "../services/BackgroundJobService.js";
|
||||
import { services } from "../services/index.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import {
|
||||
isGitCommitCommand,
|
||||
isPullRequestCommand,
|
||||
} from "../telemetry/utils.js";
|
||||
import { backgroundSignalManager } from "../util/backgroundSignalManager.js";
|
||||
import { emitBashToolEnded, emitBashToolStarted } from "../util/cli.js";
|
||||
import {
|
||||
parseEnvNumber,
|
||||
truncateOutputFromStart,
|
||||
|
|
@ -82,6 +86,35 @@ function getShellCommand(command: string): { shell: string; args: string[] } {
|
|||
return { shell: userShell, args: ["-l", "-c", command] };
|
||||
}
|
||||
|
||||
export function runCommandInBackground(command: string): {
|
||||
success: boolean;
|
||||
jobId?: string;
|
||||
error?: string;
|
||||
} {
|
||||
const job = backgroundJobService.createJob(command);
|
||||
if (!job) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Cannot create background job: limit of 5 concurrent jobs reached",
|
||||
};
|
||||
}
|
||||
|
||||
const { shell, args } = getShellCommand(command);
|
||||
const child = backgroundJobService.startJob(job.id, shell, args);
|
||||
|
||||
if (!child) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Failed to start background job ${job.id}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
jobId: job.id,
|
||||
};
|
||||
}
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
name: "Bash",
|
||||
displayName: "Bash",
|
||||
|
|
@ -151,7 +184,9 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed
|
|||
const maxChars = Math.floor(baseMaxChars / parallelCount);
|
||||
const maxLines = Math.floor(baseMaxLines / parallelCount);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
emitBashToolStarted();
|
||||
|
||||
const terminalOutput: string = await new Promise((resolve, reject) => {
|
||||
// Use same shell logic as core implementation
|
||||
const { shell, args } = getShellCommand(command);
|
||||
const child = spawn(shell, args);
|
||||
|
|
@ -187,6 +222,47 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed
|
|||
return output;
|
||||
};
|
||||
|
||||
const moveToBackground = () => {
|
||||
if (isResolved) return;
|
||||
isResolved = true;
|
||||
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
backgroundSignalManager.off("backgroundRequested", moveToBackground);
|
||||
|
||||
// Detach stdout/stderr listeners so they don't accumulate in local
|
||||
// buffers or trigger chat history updates after the tool call resolves.
|
||||
// BackgroundJobService.createJobWithProcess attaches its own listeners.
|
||||
child.stdout.removeListener("data", onStdout);
|
||||
child.stderr.removeListener("data", onStderr);
|
||||
|
||||
const job = backgroundJobService.createJobWithProcess(
|
||||
command,
|
||||
child as ChildProcess,
|
||||
stdout,
|
||||
);
|
||||
|
||||
if (job) {
|
||||
const truncationResult = truncateOutputFromStart(stdout, {
|
||||
maxChars,
|
||||
maxLines,
|
||||
});
|
||||
const outputSoFar = truncationResult.wasTruncated
|
||||
? appendParallelLimitNote(truncationResult.output)
|
||||
: truncationResult.output;
|
||||
resolve(
|
||||
`Command moved to background. Job ID: ${job.id}\nOutput so far:\n${outputSoFar}\nUse CheckBackgroundJob("${job.id}") to check status.`,
|
||||
);
|
||||
} else {
|
||||
resolve(
|
||||
`Failed to move to background (job limit reached). Command continues in foreground.\nOutput so far: ${stdout}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
backgroundSignalManager.on("backgroundRequested", moveToBackground);
|
||||
|
||||
const resetTimeout = () => {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
|
|
@ -209,18 +285,37 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed
|
|||
}, TIMEOUT_MS);
|
||||
};
|
||||
|
||||
const showCurrentOutput = () => {
|
||||
if (!context?.toolCallId) return;
|
||||
try {
|
||||
const currentOutput = stdout + (stderr ? `\nStderr: ${stderr}` : "");
|
||||
services.chatHistory.addToolResult(
|
||||
context.toolCallId,
|
||||
currentOutput,
|
||||
"calling",
|
||||
);
|
||||
} catch {
|
||||
// Ignore errors during streaming updates
|
||||
}
|
||||
};
|
||||
|
||||
// Start the initial timeout
|
||||
resetTimeout();
|
||||
|
||||
child.stdout.on("data", (data) => {
|
||||
const onStdout = (data: Buffer) => {
|
||||
stdout += data.toString();
|
||||
resetTimeout();
|
||||
});
|
||||
showCurrentOutput();
|
||||
};
|
||||
|
||||
child.stderr.on("data", (data) => {
|
||||
const onStderr = (data: Buffer) => {
|
||||
stderr += data.toString();
|
||||
resetTimeout();
|
||||
});
|
||||
showCurrentOutput();
|
||||
};
|
||||
|
||||
child.stdout.on("data", onStdout);
|
||||
child.stderr.on("data", onStderr);
|
||||
|
||||
child.on("close", (code) => {
|
||||
if (isResolved) return;
|
||||
|
|
@ -230,6 +325,11 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed
|
|||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
backgroundSignalManager.removeListener(
|
||||
"backgroundRequested",
|
||||
moveToBackground,
|
||||
);
|
||||
|
||||
// Only reject on non-zero exit code if there's also stderr
|
||||
if (code !== 0 && stderr) {
|
||||
reject(`Error (exit code ${code}): ${stderr}`);
|
||||
|
|
@ -267,8 +367,13 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed
|
|||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
backgroundSignalManager.off("backgroundRequested", moveToBackground);
|
||||
reject(`Error: ${error.message}`);
|
||||
});
|
||||
});
|
||||
|
||||
emitBashToolEnded();
|
||||
|
||||
return terminalOutput;
|
||||
},
|
||||
};
|
||||
|
|
|
|||
201
extensions/cli/src/ui/JobsSelector.tsx
Normal file
201
extensions/cli/src/ui/JobsSelector.tsx
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
BackgroundJob,
|
||||
backgroundJobService,
|
||||
} from "../services/BackgroundJobService.js";
|
||||
import { truncateOutputFromStart } from "../util/truncateOutput.js";
|
||||
|
||||
import { defaultBoxStyles } from "./styles.js";
|
||||
|
||||
interface JobsSelectorProps {
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
type ViewMode = "list" | "detail";
|
||||
|
||||
function getStatusColor(status: BackgroundJob["status"]): string {
|
||||
if (status === "running" || status === "pending") return "yellow";
|
||||
if (status === "completed") return "green";
|
||||
return "red";
|
||||
}
|
||||
|
||||
function formatDuration(job: BackgroundJob): string {
|
||||
const endTime = job.endTime ? job.endTime.getTime() : Date.now();
|
||||
return `${Math.round((endTime - job.startTime.getTime()) / 1000)}s`;
|
||||
}
|
||||
|
||||
export function JobsSelector({ onCancel }: JobsSelectorProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [viewMode, setViewMode] = useState<ViewMode>("list");
|
||||
const [selectedJob, setSelectedJob] = useState<BackgroundJob | null>(null);
|
||||
const [jobs, setJobs] = useState(() => backgroundJobService.getAllJobs());
|
||||
|
||||
// Refetch the job details every 1 second
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (viewMode === "detail" && selectedJob) {
|
||||
const freshJob = backgroundJobService.getJob(selectedJob.id);
|
||||
if (freshJob) {
|
||||
setSelectedJob(freshJob);
|
||||
}
|
||||
} else {
|
||||
setJobs(backgroundJobService.getAllJobs());
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [viewMode, selectedJob]);
|
||||
|
||||
useInput((input, key) => {
|
||||
// Handle key input when viewing job details
|
||||
if (viewMode === "detail") {
|
||||
// Go back to list view
|
||||
if (key.escape || input === "b") {
|
||||
setViewMode("list");
|
||||
setSelectedJob(null);
|
||||
return;
|
||||
}
|
||||
// Cancel the selected job if it's still active
|
||||
if (input === "x" && selectedJob) {
|
||||
const job = backgroundJobService.getJob(selectedJob.id);
|
||||
if (job && (job.status === "running" || job.status === "pending")) {
|
||||
backgroundJobService.cancelJob(selectedJob.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle key input when viewing job list
|
||||
if (key.escape || (key.ctrl && input === "c")) {
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigate up and down the job list
|
||||
if (key.upArrow) {
|
||||
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : jobs.length - 1));
|
||||
return;
|
||||
}
|
||||
if (key.downArrow) {
|
||||
setSelectedIndex((prev) => (prev < jobs.length - 1 ? prev + 1 : 0));
|
||||
return;
|
||||
}
|
||||
|
||||
// Select a job to view its details
|
||||
if (key.return && jobs[selectedIndex]) {
|
||||
setSelectedJob(jobs[selectedIndex]);
|
||||
setViewMode("detail");
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
if (jobs.length === 0) {
|
||||
return (
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text color="blue" bold>
|
||||
Background Jobs
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
<Text color="gray">No background jobs</Text>
|
||||
<Text> </Text>
|
||||
<Text color="gray">Press Esc to go back</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (viewMode === "detail" && selectedJob) {
|
||||
const freshJob = selectedJob;
|
||||
const { output: lastOutput } = truncateOutputFromStart(freshJob.output, {
|
||||
maxLines: 10,
|
||||
maxChars: 2000,
|
||||
});
|
||||
|
||||
return (
|
||||
<Box {...defaultBoxStyles("blue")} flexDirection="column">
|
||||
<Text color="blue" bold>
|
||||
Job Details
|
||||
</Text>
|
||||
<Text color="gray">Press Esc/b to go back, x to cancel job</Text>
|
||||
<Text> </Text>
|
||||
|
||||
<Box flexDirection="row" gap={1}>
|
||||
<Text color="gray">ID:</Text>
|
||||
<Text color="cyan">{freshJob.id}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" gap={1}>
|
||||
<Text color="gray">Status:</Text>
|
||||
<Text color={getStatusColor(freshJob.status)}>{freshJob.status}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" gap={1}>
|
||||
<Text color="gray">Duration:</Text>
|
||||
<Text>{formatDuration(freshJob)}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" gap={1}>
|
||||
<Text color="gray">Command:</Text>
|
||||
<Text>{freshJob.command}</Text>
|
||||
</Box>
|
||||
|
||||
{freshJob.exitCode !== null && (
|
||||
<Box flexDirection="row" gap={1}>
|
||||
<Text color="gray">Exit Code:</Text>
|
||||
<Text color={freshJob.exitCode === 0 ? "green" : "red"}>
|
||||
{freshJob.exitCode}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{freshJob.error && (
|
||||
<Box flexDirection="row" gap={1}>
|
||||
<Text color="gray">Error:</Text>
|
||||
<Text color="red">{freshJob.error}</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Text> </Text>
|
||||
<Text color="gray">Last 10 lines of output:</Text>
|
||||
<Box borderStyle="single" borderColor="gray" paddingX={1}>
|
||||
<Text>{lastOutput || "(no output)"}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// List screen
|
||||
return (
|
||||
<Box {...defaultBoxStyles("blue")}>
|
||||
<Text color="blue" bold>
|
||||
Background Jobs ({jobs.length})
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
↑/↓ to navigate, Enter to view details, Esc to exit
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
|
||||
{jobs.map((job, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
const prefix = isSelected ? "❯ " : " ";
|
||||
|
||||
return (
|
||||
<Box key={job.id} flexDirection="row" gap={1}>
|
||||
<Text color={isSelected ? "cyan" : undefined}>{prefix}</Text>
|
||||
<Text color={getStatusColor(job.status)}>
|
||||
{job.status.padEnd(10)}
|
||||
</Text>
|
||||
<Text color="cyan">{job.id}</Text>
|
||||
<Text color="gray">({formatDuration(job)})</Text>
|
||||
<Text>
|
||||
{job.command.substring(0, 30)}
|
||||
{job.command.length > 30 ? "..." : ""}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ import {
|
|||
UpdateServiceState,
|
||||
} from "../services/types.js";
|
||||
import { getTotalSessionCost } from "../session.js";
|
||||
import { bashToolEvents } from "../util/cli.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { ActionStatus } from "./components/ActionStatus.js";
|
||||
|
|
@ -282,6 +283,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
onShowMCPSelector: () => navigateTo("mcp"),
|
||||
onShowUpdateSelector: () => navigateTo("update"),
|
||||
onShowSessionSelector: () => navigateTo("session"),
|
||||
onShowJobsSelector: () => navigateTo("jobs"),
|
||||
onReload: handleReload,
|
||||
onClear: handleClear,
|
||||
onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1),
|
||||
|
|
@ -341,6 +343,22 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
// Fetch organization name based on auth state
|
||||
const organizationName = useOrganizationName(services.auth?.organizationId);
|
||||
|
||||
// Track if a Bash tool is currently running via events
|
||||
const [isBashToolRunning, setIsBashToolRunning] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handleStarted = () => setIsBashToolRunning(true);
|
||||
const handleEnded = () => setIsBashToolRunning(false);
|
||||
|
||||
bashToolEvents.on("started", handleStarted);
|
||||
bashToolEvents.on("ended", handleEnded);
|
||||
|
||||
return () => {
|
||||
bashToolEvents.off("started", handleStarted);
|
||||
bashToolEvents.off("ended", handleEnded);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" height="100%">
|
||||
{/* Chat history - takes up all available space above input */}
|
||||
|
|
@ -379,6 +397,9 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
startTime={responseStartTime || 0}
|
||||
message=""
|
||||
showSpinner={true}
|
||||
additionalHint={
|
||||
isBashToolRunning ? "ctrl+b to background" : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Compaction Status */}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ interface ActionStatusProps {
|
|||
showSpinner?: boolean;
|
||||
color?: string;
|
||||
loadingColor?: string;
|
||||
additionalHint?: string;
|
||||
}
|
||||
|
||||
const ActionStatus: React.FC<ActionStatusProps> = ({
|
||||
|
|
@ -20,6 +21,7 @@ const ActionStatus: React.FC<ActionStatusProps> = ({
|
|||
showSpinner = false,
|
||||
color = "dim",
|
||||
loadingColor = "green",
|
||||
additionalHint,
|
||||
}) => {
|
||||
if (!visible) return null;
|
||||
|
||||
|
|
@ -29,7 +31,9 @@ const ActionStatus: React.FC<ActionStatusProps> = ({
|
|||
<Text color={color}>{message}</Text>
|
||||
<Text color="dim">(</Text>
|
||||
<Timer startTime={startTime} />
|
||||
<Text color="dim">• esc to interrupt )</Text>
|
||||
<Text color="dim">• esc to interrupt</Text>
|
||||
{additionalHint && <Text color="dim">• {additionalHint}</Text>}
|
||||
<Text color="dim">)</Text>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { DiffViewer } from "../DiffViewer.js";
|
|||
import { EditMessageSelector } from "../EditMessageSelector.js";
|
||||
import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js";
|
||||
import type { ActivePermissionRequest } from "../hooks/useChat.types.js";
|
||||
import { JobsSelector } from "../JobsSelector.js";
|
||||
import { MCPSelector } from "../MCPSelector.js";
|
||||
import { ModelSelector } from "../ModelSelector.js";
|
||||
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
|
||||
|
|
@ -156,6 +157,11 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
);
|
||||
}
|
||||
|
||||
// Jobs selector
|
||||
if (isScreenActive("jobs")) {
|
||||
return <JobsSelector onCancel={closeCurrentScreen} />;
|
||||
}
|
||||
|
||||
// Free trial transition UI
|
||||
if (isScreenActive("free-trial")) {
|
||||
return <FreeTrialTransitionUI onReload={handleReload} />;
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export type NavigationScreen =
|
|||
| "diff" // Full-screen diff overlay
|
||||
| "update" // Update selector
|
||||
| "edit" // Edit message selector
|
||||
| "jobs" // Background Jobs selector
|
||||
| "session"; // Session selector
|
||||
|
||||
interface NavigationState {
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@ interface ProcessSlashCommandResultOptions {
|
|||
onShowUpdateSelector?: () => void;
|
||||
onShowMCPSelector?: () => void;
|
||||
onShowSessionSelector?: () => void;
|
||||
onShowJobsSelector?: () => void;
|
||||
onClear?: () => void;
|
||||
}
|
||||
|
||||
|
|
@ -66,6 +67,7 @@ export function processSlashCommandResult({
|
|||
onShowModelSelector,
|
||||
onShowMCPSelector,
|
||||
onShowSessionSelector,
|
||||
onShowJobsSelector,
|
||||
onClear,
|
||||
}: ProcessSlashCommandResultOptions): string | null {
|
||||
if (result.exit) {
|
||||
|
|
@ -97,6 +99,11 @@ export function processSlashCommandResult({
|
|||
return null;
|
||||
}
|
||||
|
||||
if (result.openJobsSelector && onShowJobsSelector) {
|
||||
onShowJobsSelector();
|
||||
return null;
|
||||
}
|
||||
|
||||
if (result.clear) {
|
||||
const systemMessage = chatHistory.find(
|
||||
(item) => item.message.role === "system",
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@ export function useChat({
|
|||
onShowUpdateSelector,
|
||||
onShowMCPSelector,
|
||||
onShowSessionSelector,
|
||||
onShowJobsSelector,
|
||||
onClear,
|
||||
onRefreshStatic,
|
||||
isRemoteMode = false,
|
||||
|
|
@ -426,6 +427,7 @@ export function useChat({
|
|||
onShowModelSelector,
|
||||
onShowMCPSelector,
|
||||
onShowSessionSelector,
|
||||
onShowJobsSelector,
|
||||
onShowUpdateSelector,
|
||||
onClear,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ export interface UseChatProps {
|
|||
onShowUpdateSelector: () => void;
|
||||
onShowModelSelector?: () => void;
|
||||
onShowSessionSelector?: () => void;
|
||||
onShowJobsSelector?: () => void;
|
||||
onReload?: () => Promise<void>;
|
||||
onClear?: () => void;
|
||||
onRefreshStatic?: () => void;
|
||||
|
|
@ -63,6 +64,7 @@ export interface SlashCommandResult {
|
|||
openMcpSelector?: boolean;
|
||||
openUpdateSelector?: boolean;
|
||||
openSessionSelector?: boolean;
|
||||
openJobsSelector?: boolean;
|
||||
compact?: boolean;
|
||||
diffContent?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { PermissionMode } from "../../permissions/types.js";
|
||||
import { backgroundSignalManager } from "../../util/backgroundSignalManager.js";
|
||||
import {
|
||||
checkClipboardForImage,
|
||||
getClipboardImage,
|
||||
|
|
@ -85,6 +86,12 @@ export function handleControlKeys(options: ControlKeysOptions): boolean {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Handle Ctrl+B to send current tool execution to background
|
||||
if (key.ctrl && input === "b") {
|
||||
backgroundSignalManager.signalBackground();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle Shift+Tab to cycle through modes
|
||||
if (key.tab && key.shift && !showSlashCommands && !showFileSearch) {
|
||||
cycleModes().catch((error) => {
|
||||
|
|
|
|||
10
extensions/cli/src/util/backgroundSignalManager.ts
Normal file
10
extensions/cli/src/util/backgroundSignalManager.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { EventEmitter } from "events";
|
||||
|
||||
// Event emitter to notify that running terminal command should be moved to background
|
||||
class BackgroundSignalManager extends EventEmitter {
|
||||
signalBackground(): void {
|
||||
this.emit("backgroundRequested");
|
||||
}
|
||||
}
|
||||
|
||||
export const backgroundSignalManager = new BackgroundSignalManager();
|
||||
|
|
@ -94,3 +94,13 @@ export function hasSuppliedPrompt(): boolean {
|
|||
}
|
||||
|
||||
export const escapeEvents = new EventEmitter();
|
||||
|
||||
export const bashToolEvents = new EventEmitter();
|
||||
|
||||
export function emitBashToolStarted(): void {
|
||||
bashToolEvents.emit("started");
|
||||
}
|
||||
|
||||
export function emitBashToolEnded(): void {
|
||||
bashToolEvents.emit("ended");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import type { ChatHistoryItem } from "core/index.js";
|
||||
|
||||
import { sentryService } from "../sentry.js";
|
||||
import { backgroundJobService } from "../services/BackgroundJobService.js";
|
||||
import { getSessionUsage } from "../session.js";
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
|
||||
|
|
@ -194,6 +195,16 @@ export async function gracefulExit(code: number = 0): Promise<void> {
|
|||
// Display session usage breakdown in verbose mode
|
||||
displaySessionUsage();
|
||||
|
||||
try {
|
||||
const runningJobs = backgroundJobService.getRunningJobCount();
|
||||
if (runningJobs > 0) {
|
||||
logger.debug(`Killing ${runningJobs} background job(s) on exit`);
|
||||
backgroundJobService.killAllJobs();
|
||||
}
|
||||
} catch (err) {
|
||||
logger.debug("Background job cleanup error (ignored)", err as any);
|
||||
}
|
||||
|
||||
try {
|
||||
// Flush metrics (forceFlush + shutdown inside service)
|
||||
await telemetryService.shutdown();
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import path from "path";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
|
|
@ -22,6 +23,9 @@ export default defineConfig({
|
|||
hookTimeout: 30000,
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
src: path.resolve(__dirname, "src"),
|
||||
},
|
||||
extensions: [".js", ".ts", ".tsx", ".json"],
|
||||
},
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue