fix: Set isComplete metadata when agents finish execution

Fixes issue where agent sessions stay stuck in "running" state forever
because the isComplete metadata field is never set.

Changes:
- Status tool now calls updateAgentMetadata({ isComplete: true }) when
  status is "DONE" or "FAILED"
- reportFailure tool now marks agent as complete before reporting failure
- exit tool now marks agent as complete before exiting
- Added debug logging to track inactivity timeout progress and lastActivity
  updates

This ensures the UI can properly detect when an agent has finished and
display the correct state instead of showing "running" indefinitely.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Nate 2026-01-25 15:47:56 -08:00
parent 0425f6eabc
commit 65a1e1500b
4 changed files with 72 additions and 2 deletions

View file

@ -430,6 +430,9 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
`\nServer will shut down after ${timeoutSeconds} seconds of inactivity`,
),
);
logger.info(
`Inactivity timeout configured: ${timeoutSeconds}s (${timeoutMs}ms)`,
);
// Run environment install script after server startup
runEnvironmentInstallSafe();
@ -497,6 +500,9 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
const userMessage = queuedMessage.message;
state.isProcessing = true;
state.lastActivity = Date.now();
logger.debug(
`Updated lastActivity: processing message "${userMessage.substring(0, 50)}${userMessage.length > 50 ? "..." : ""}"`,
);
processedMessage = true;
// Add user message via ChatHistoryService (single source of truth)
@ -525,6 +531,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// No direct persistence here; ChatHistoryService handles persistence when appropriate
state.lastActivity = Date.now();
logger.debug("Updated lastActivity: after successful agent turn");
// Update metadata after successful agent turn
try {
@ -584,13 +591,32 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Check for inactivity and shutdown
let inactivityCheckCount = 0;
inactivityChecker = setInterval(() => {
if (!state.isProcessing && Date.now() - state.lastActivity > timeoutMs) {
inactivityCheckCount++;
const now = Date.now();
const timeSinceLastActivity = now - state.lastActivity;
const isProcessing = state.isProcessing;
const shouldShutdown = !isProcessing && timeSinceLastActivity > timeoutMs;
// Log every 30 seconds to track timeout progress
if (inactivityCheckCount % 30 === 0) {
logger.debug(
`Inactivity check #${inactivityCheckCount}: processing=${isProcessing}, ` +
`timeSinceLastActivity=${Math.floor(timeSinceLastActivity / 1000)}s, ` +
`timeout=${timeoutSeconds}s, shouldShutdown=${shouldShutdown}`,
);
}
if (shouldShutdown) {
console.log(
chalk.yellow(
`\nShutting down due to ${timeoutSeconds} seconds of inactivity`,
),
);
logger.info(
`Inactivity timeout triggered after ${inactivityCheckCount} checks`,
);
state.serverRunning = false;
stopStorageSync();
server.close(async () => {
@ -600,6 +626,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
try {
const history = services.chatHistory?.getHistory();
await updateAgentMetadata({ history, isComplete: true });
logger.info("Marked agent as complete due to inactivity timeout");
} catch (err) {
logger.debug("Failed to update metadata (non-critical)", err as any);
}

View file

@ -12,7 +12,18 @@ export const exitTool: Tool = {
readonly: false,
isBuiltIn: true,
run: async (): Promise<string> => {
const { gracefulExit } = await import("../util/exit.js");
const { gracefulExit, updateAgentMetadata } = await import(
"../util/exit.js"
);
// Mark agent as complete before exiting
try {
await updateAgentMetadata({ isComplete: true });
} catch (err) {
// Non-critical: log but don't block exit
console.debug("Failed to update completion metadata (non-critical)", err);
}
await gracefulExit(1);
return "";
},

View file

@ -6,6 +6,7 @@ import {
AuthenticationRequiredError,
post,
} from "../util/apiClient.js";
import { updateAgentMetadata } from "../util/exit.js";
import { logger } from "../util/logger.js";
import { Tool } from "./types.js";
@ -74,6 +75,18 @@ export const reportFailureTool: Tool = {
errorMessage: trimmedMessage,
});
// Mark agent as complete since it failed
try {
await updateAgentMetadata({ isComplete: true });
logger.debug("Marked agent as complete due to failure");
} catch (metadataErr) {
// Non-critical: log but don't fail the failure report
logger.debug(
"Failed to update completion metadata (non-critical)",
metadataErr as any,
);
}
logger.info(`Failure reported: ${trimmedMessage}`);
return "Failure reported to user.";
} catch (error) {

View file

@ -5,6 +5,7 @@ import {
AuthenticationRequiredError,
post,
} from "../util/apiClient.js";
import { updateAgentMetadata } from "../util/exit.js";
import { logger } from "../util/logger.js";
import { Tool } from "./types.js";
@ -62,6 +63,24 @@ You should use this tool to notify the user whenever the state of your work chan
await post(`agents/${agentId}/status`, { status: args.status });
logger.info(`Status: ${args.status}`);
// If status is DONE or FAILED, mark agent as complete
const normalizedStatus = args.status.toUpperCase();
if (normalizedStatus === "DONE" || normalizedStatus === "FAILED") {
try {
await updateAgentMetadata({ isComplete: true });
logger.debug(
`Marked agent as complete due to status: ${args.status}`,
);
} catch (metadataErr) {
// Non-critical: log but don't fail the status update
logger.debug(
"Failed to update completion metadata (non-critical)",
metadataErr as any,
);
}
}
return `Status set: ${args.status}`;
} catch (error) {
if (error instanceof ContinueError) {