show separate screen for background jobs

This commit is contained in:
uinstinct 2026-02-09 18:58:11 +05:30
parent 5a5a90826d
commit c7d6a73df1
9 changed files with 224 additions and 28 deletions

View file

@ -144,6 +144,9 @@ export class BackgroundJobManager {
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();

View file

@ -9,7 +9,6 @@ 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";
@ -171,33 +170,7 @@ 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"),
};
return { openJobsSelector: true };
}
const commandHandlers: Record<string, CommandHandler> = {

View file

@ -0,0 +1,201 @@
import { Box, Text, useInput } from "ink";
import React, { useEffect, useState } from "react";
import {
BackgroundJob,
backgroundJobManager,
} from "../services/BackgroundJobManager.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(() => backgroundJobManager.getAllJobs());
// Refetch the job details every 1 second
useEffect(() => {
const interval = setInterval(() => {
if (viewMode === "detail" && selectedJob) {
const freshJob = backgroundJobManager.getJob(selectedJob.id);
if (freshJob) {
setSelectedJob(freshJob);
}
} else {
setJobs(backgroundJobManager.getAllJobs());
}
}, 1000);
return () => clearInterval(interval);
}, []);
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 = backgroundJobManager.getJob(selectedJob.id);
if (job && (job.status === "running" || job.status === "pending")) {
backgroundJobManager.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>
);
}

View file

@ -283,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),

View file

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

View file

@ -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 {

View file

@ -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",

View file

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

View file

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