Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(cos): surface worktree cleanup warnings in UI and notifications

Adam Eivy6c08dc7ce644
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d5ff9945bc..c2d1208bdf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -30,6 +30,7 @@
- AI-powered goal check-ins — "Run Check-In" button on goal detail panel generates LLM assessment of goal health (on-track/behind/at-risk), actionable recommendations, and motivational encouragement based on progress, velocity, milestones, and activity attendance
- Chronotype-aware scheduling — Calendar Day and Week views now show genome-derived energy zone overlays (peak focus, exercise, wind-down) and cutoff markers (caffeine, last meal) based on the user's chronotype profile
- Pipeline agent cards: stage-tabbed output view — Show button displays separate output panes for each pipeline stage with status indicators and on-demand loading
+- Agent cleanup warnings now surface in the UI — worktree merge failures, PR creation failures, and preserved worktrees show as yellow warnings in the agent card, completion toast, and notification bell
## Changed
diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsx
index 7a4930b8e5..bd38af9d61 100644
--- a/client/src/components/NotificationDropdown.jsx
+++ b/client/src/components/NotificationDropdown.jsx
@@ -28,6 +28,11 @@ const NOTIFICATION_TYPE_CONFIG = {
icon: HelpCircle,
color: 'text-emerald-400',
bgColor: 'bg-emerald-500/20'
+ },
+ agent_warning: {
+ icon: AlertTriangle,
+ color: 'text-yellow-400',
+ bgColor: 'bg-yellow-500/20'
}
};
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 03c0e3f97f..0bbc845a7d 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -4,6 +4,7 @@ import {
Trash2,
CheckCircle,
AlertCircle,
+ AlertTriangle,
RotateCcw,
Loader2,
Skull,
@@ -662,6 +663,17 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
<><AlertCircle size={14} aria-hidden="true" /> {agent.result.error || 'Failed'}</>
)}
</div>
+ {/* Cleanup warnings */}
+ {agent.result.warnings?.length > 0 && (
+ <div className="text-sm text-port-warning flex items-start gap-2">
+ <AlertTriangle size={14} className="shrink-0 mt-0.5" aria-hidden="true" />
+ <div>
+ {agent.result.warnings.map((w, i) => (
+ <p key={i}>{w}</p>
+ ))}
+ </div>
+ </div>
+ )}
{/* Memory extraction status */}
{agent.result.success && (
<div className={`text-sm flex items-center gap-1 ${
diff --git a/client/src/hooks/useAgentFeedbackToast.jsx b/client/src/hooks/useAgentFeedbackToast.jsx
index 2f13915b1a..e0ce23da94 100644
--- a/client/src/hooks/useAgentFeedbackToast.jsx
+++ b/client/src/hooks/useAgentFeedbackToast.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import toast from 'react-hot-toast';
-import { ThumbsUp, ThumbsDown, Loader2 } from 'lucide-react';
+import { ThumbsUp, ThumbsDown, Loader2, AlertTriangle } from 'lucide-react';
import socket from '../services/socket';
import * as api from '../services/api';
import OutputBlocks from '../components/cos/OutputBlocks';
@@ -22,6 +22,7 @@ function AgentFeedbackToast({ t, agentData, onFeedback }) {
const taskDesc = agentData?.metadata?.taskDescription || agentData?.taskId || 'Task';
const shortDesc = taskDesc.length > 50 ? taskDesc.substring(0, 50) + '...' : taskDesc;
const success = agentData?.result?.success;
+ const warnings = agentData?.result?.warnings;
// Auto-dismiss timer: active when collapsed, cleared when expanded
useEffect(() => {
@@ -66,6 +67,14 @@ function AgentFeedbackToast({ t, agentData, onFeedback }) {
{expanded ? taskDesc : shortDesc}
</p>
+ {/* Cleanup warnings */}
+ {warnings?.length > 0 && (
+ <div className="flex items-start gap-1.5 text-yellow-400 text-xs bg-yellow-500/10 rounded px-2 py-1.5">
+ <AlertTriangle size={12} className="shrink-0 mt-0.5" />
+ <div>{warnings.map((w, i) => <p key={i}>{w}</p>)}</div>
+ </div>
+ )}
+
{/* Expanded output */}
{expanded && (
<div className="border-t border-port-border/30 pt-2 max-h-[400px] overflow-y-auto">
diff --git a/server/services/notifications.js b/server/services/notifications.js
index 3e187b3c1f..ad750d11e9 100644
--- a/server/services/notifications.js
+++ b/server/services/notifications.js
@@ -34,7 +34,8 @@ export const NOTIFICATION_TYPES = {
HEALTH_ISSUE: 'health_issue',
BRIEFING_READY: 'briefing_ready',
AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt',
- PLAN_QUESTION: 'plan_question'
+ PLAN_QUESTION: 'plan_question',
+ AGENT_WARNING: 'agent_warning'
};
// Priority levels
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 9db03fcade..5002aedf5a 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -2200,8 +2200,26 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {
if (!jiraBranch) {
const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);
const taskReviewLoop = isTruthyMeta(agent.task?.metadata?.reviewLoop);
- // When reviewLoop + openPR are both enabled, the agent handles the PR during its run — skip post-exit PR creation
- await cleanupAgentWorktree(agentId, success, { openPR: taskOpenPR && !taskReviewLoop, description: task?.description, agentOutput: outputBuffer });
+ const cleanupWarnings = await cleanupAgentWorktree(agentId, success, { openPR: taskOpenPR && !taskReviewLoop, description: task?.description, agentOutput: outputBuffer });
+
+ if (cleanupWarnings?.length > 0) {
+ // Attach warnings to agent result so they're visible in the UI
+ await updateAgent(agentId, { result: { warnings: cleanupWarnings } });
+
+ // Create a notification for significant cleanup issues
+ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
+ const appName = task?.metadata?.appName || task?.metadata?.app || 'PortOS';
+ await addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ title: `Agent cleanup issue: ${appName}`,
+ description: cleanupWarnings.join('\n'),
+ priority: PRIORITY_LEVELS.HIGH,
+ link: '/cos/agents',
+ metadata: { agentId, taskId: task?.id, warnings: cleanupWarnings }
+ }).catch(err => {
+ emitLog('warn', `Failed to create cleanup warning notification: ${err.message}`, { agentId });
+ });
+ }
}
runnerAgents.delete(agentId);
@@ -2216,12 +2234,13 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {
export async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null, agentOutput = null } = {}) {
const { getAgent: getAgentState } = await import('./cos.js');
const agentState = await getAgentState(agentId).catch(() => null);
- if (!agentState?.metadata?.isWorktree) return;
- // Skip cleanup for persistent feature agent worktrees (they survive across runs)
- if (agentState?.metadata?.isPersistentWorktree) return;
+ if (!agentState?.metadata?.isWorktree) return [];
+ if (agentState?.metadata?.isPersistentWorktree) return [];
const { sourceWorkspace, worktreeBranch } = agentState.metadata;
- if (!sourceWorkspace || !worktreeBranch) return;
+ if (!sourceWorkspace || !worktreeBranch) return [];
+
+ const warnings = [];
// When openPR is set and task succeeded, push branch and create PR instead of auto-merging
if (openPR && success) {
@@ -2229,7 +2248,6 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, d
const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);
- // Push branch and resolve target branch in parallel
const [pushResult, branchInfo] = await Promise.all([
git.push(worktreePath, worktreeBranch).then(() => true).catch(err => {
emitLog('warn', `🌳 Failed to push worktree branch ${worktreeBranch}: ${err.message}`, { agentId });
@@ -2238,9 +2256,7 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, d
git.getRepoBranches(sourceWorkspace).catch(() => ({ baseBranch: null, devBranch: null }))
]);
- // Only create PR if push succeeded; preserve worktree/branch for manual intervention if push fails
if (pushResult) {
- // Use baseBranch (not devBranch) since worktrees are created from the default branch
const targetBranch = branchInfo.baseBranch || 'main';
const taskDesc = description || 'CoS automated task';
const prTitle = taskDesc.replace(/[\r\n]+/g, ' ').trim().substring(0, 100);
@@ -2260,22 +2276,24 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, d
if (!prResult?.success) {
const reason = prResult?.error || 'unknown error (createPR returned null or threw)';
emitLog('error', `🌳 PR creation failed for ${worktreeBranch}: ${reason}`, { agentId, branchName: worktreeBranch });
- // Preserve worktree/branch for manual PR creation
- return;
+ warnings.push(`PR creation failed for branch ${worktreeBranch}: ${reason}. Worktree preserved for manual PR creation.`);
+ return warnings;
}
emitLog('success', `🌳 Created PR: ${prResult.url}`, { agentId, branchName: worktreeBranch });
- // Remove worktree without merging (PR handles merge)
- await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
+ return { warnings: [`Worktree cleanup failed: ${err.message}`] };
});
- return;
+ warnings.push(...(result?.warnings || []));
+ return warnings;
}
- // Push failed — preserve worktree/branch for manual intervention (do NOT auto-merge in openPR mode)
+ // Push failed — preserve worktree/branch for manual intervention
+ warnings.push(`Push failed for branch ${worktreeBranch} — worktree preserved at ${worktreePath} for manual retry`);
emitLog('warn', `🌳 Push failed for ${worktreeBranch} — worktree preserved at ${worktreePath} for manual retry`, { agentId, branchName: worktreeBranch });
- return;
+ return warnings;
}
// Default: auto-merge on success, just cleanup on failure
@@ -2283,9 +2301,12 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, d
agentId, branchName: worktreeBranch, merge: success
});
- await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: success }).catch(err => {
+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: success }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
+ return { warnings: [`Worktree cleanup failed: ${err.message}`] };
});
+ warnings.push(...(result?.warnings || []));
+ return warnings;
}
/**
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 7be2ebce88..eb98acf9c5 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -106,12 +106,12 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =
*/
export async function removeWorktree(agentId, sourceWorkspace, branchName, options = {}) {
const worktreePath = join(WORKTREES_DIR, agentId);
+ const warnings = [];
if (!existsSync(worktreePath)) {
console.log(`🌳 Worktree already removed for ${agentId}, cleaning up branch`);
- // Worktree dir is gone but branch may still exist — delete it
await execGit(['branch', '-D', branchName], sourceWorkspace).catch(() => {});
- return { merged: false, removed: true, uncommittedSaved: false };
+ return { merged: false, removed: true, uncommittedSaved: false, warnings };
}
// Safety check: abort removal when uncommitted changes are detected.
@@ -121,41 +121,39 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
dirtyFiles = (await execGit(['status', '--porcelain'], worktreePath)).trim();
} catch (err) {
console.log(`⚠️ git status failed for worktree ${agentId}, preserving to avoid data loss: ${err.message}`);
- return { merged: false, removed: false, uncommittedSaved: false };
+ warnings.push(`Worktree preserved — git status failed: ${err.message}`);
+ return { merged: false, removed: false, uncommittedSaved: false, warnings };
}
if (dirtyFiles) {
console.log(`⚠️ Preserving worktree for ${agentId} — uncommitted changes detected, aborting cleanup to avoid data loss`);
- return { merged: false, removed: false, uncommittedSaved: false };
+ warnings.push(`Worktree preserved — uncommitted changes detected in ${worktreePath}`);
+ return { merged: false, removed: false, uncommittedSaved: false, warnings };
}
let merged = false;
- // If merge requested, check if there are commits to merge
if (options.merge) {
const currentBranch = (await execGit(
['rev-parse', '--abbrev-ref', 'HEAD'],
sourceWorkspace
)).trim();
- // Check if worktree branch has commits ahead of the source branch
const aheadCount = (await execGit(
['rev-list', '--count', `${currentBranch}..${branchName}`],
sourceWorkspace
).catch(() => '0')).trim();
if (parseInt(aheadCount, 10) > 0) {
- // Merge worktree branch back to the source branch
await execGit(['merge', branchName, '--no-edit'], sourceWorkspace)
.then(() => { merged = true; })
.catch(async (err) => {
console.log(`⚠️ Could not auto-merge ${branchName}: ${err.message}`);
- // Abort the failed merge to leave sourceWorkspace in a clean state
await execGit(['merge', '--abort'], sourceWorkspace).catch(() => {});
+ warnings.push(`Auto-merge failed for branch ${branchName} — branch preserved for manual recovery`);
});
}
}
- // Remove the worktree
await execGit(['worktree', 'remove', worktreePath, '--force'], sourceWorkspace)
.catch(async (err) => {
console.log(`⚠️ Worktree remove failed for ${agentId}, falling back to manual cleanup: ${err.message}`);
@@ -167,8 +165,6 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
});
});
- // Only delete the branch if merge succeeded or wasn't requested.
- // When merge was requested but failed, preserve the branch so commits can be recovered.
const shouldDeleteBranch = merged || !options.merge;
if (shouldDeleteBranch) {
await execGit(['branch', '-D', branchName], sourceWorkspace)
@@ -181,7 +177,7 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);
- return { merged, removed: true, uncommittedSaved: false };
+ return { merged, removed: true, uncommittedSaved: false, warnings };
}
/**