diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 931ad15cdb64c..9194b0f91eef4 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -76,6 +76,7 @@ import {
ThreadListV2SettledShelfHeader,
ThreadListV2ShowMoreRow,
ThreadListV2SnoozedShelfHeader,
+ ThreadListV2StuckShelfHeader,
ThreadListV2WorkingShelfHeader,
} from "../threads/thread-list-v2-items";
import { useThreadRowProviderInstanceResolver } from "../threads/thread-provider-instance";
@@ -386,10 +387,12 @@ export function HomeScreen(props: HomeScreenProps) {
snoozedShelfExpanded,
workingShelfEnabled,
workingShelfExpanded,
+ stuckShelfExpanded,
expandedPipelineKeys,
toggleSettledShelf,
toggleSnoozedShelf,
toggleWorkingShelf,
+ toggleStuckShelf,
togglePipelineExpanded,
} = useThreadListV2ShelfPreferences();
const now = useThreadListNow(props.threads);
@@ -433,6 +436,7 @@ export function HomeScreen(props: HomeScreenProps) {
shelfPreferencesLoaded,
workingShelfEnabled,
workingShelfExpanded,
+ stuckShelfExpanded,
snoozedShelfExpanded,
settledShelfExpanded,
expandedPipelineKeys,
@@ -505,6 +509,16 @@ export function HomeScreen(props: HomeScreenProps) {
/>
);
}
+ if (item.type === "v2-stuck-shelf") {
+ return (
+
+ );
+ }
if (item.type === "v2-snoozed-shelf") {
return (
({
updateMobilePreferencesAtom: {},
}));
vi.mock("./components/AutoSettleDaysField", () => ({ AutoSettleDaysField: () => null }));
+vi.mock("./components/PossiblyStuckHoursField", () => ({ PossiblyStuckHoursField: () => null }));
vi.mock("./components/SourceControlSignInSection", () => ({
SourceControlSignInSection: () => null,
}));
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
index 5026a90e13b9a..b3d7857d9cbdd 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
@@ -139,6 +139,7 @@ const AUTO_SETTLE_SETTING_KEYS: ReadonlySet = new Set([
"sidebarAutoSettleAfterDays",
"autoResumeLimitedThreads",
"snoozeLimitedThreads",
+ "possiblyStuckAfterHours",
]);
function planServerSettingsWrites(
diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
index 41600619b3a47..9afa24500cc7a 100644
--- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
+++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
@@ -6,6 +6,7 @@ import {
} from "@t3tools/contracts";
import { useEnvironmentsWithScope } from "../../state/session";
import { AutoSettleDaysField } from "./components/AutoSettleDaysField";
+import { PossiblyStuckHoursField } from "./components/PossiblyStuckHoursField";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/reactivity";
@@ -13,7 +14,7 @@ import type { ComponentProps } from "react";
import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
-import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
+import { DEFAULT_POSSIBLY_STUCK_AFTER_HOURS, DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings";
import { AppText as Text } from "../../components/ui/AppText";
import { useEnvironments } from "../../state/environments";
@@ -101,6 +102,7 @@ export function AutoSettleSettingsRows(props: {
patch: Partial & {
autoResumeLimitedThreads?: boolean;
snoozeLimitedThreads?: boolean;
+ possiblyStuckAfterHours?: number;
},
) => props.write(patch);
@@ -145,6 +147,28 @@ export function AutoSettleSettingsRows(props: {
/>
) : null}
+ {!projectSelected ? (
+
+
+
+
+ Mark threads as possibly stuck after
+
+
+ A thread whose last turn ended while background work kept running this long is
+ listed under Possibly stuck. Pull request watches never count. 0 turns it off.
+
+
+ writeToAll({ possiblyStuckAfterHours: value })}
+ />
+
+
+ ) : null}
,
+ "value" | "onValueChange" | "disabled"
+>;
+
+export function PossiblyStuckHoursField(props: PossiblyStuckHoursFieldProps) {
+ return (
+ (value === 0 ? "Off" : `${value} ${value === 1 ? "hour" : "hours"}`)}
+ />
+ );
+}
diff --git a/apps/mobile/src/features/threads/PipelineRunPanel.tsx b/apps/mobile/src/features/threads/PipelineRunPanel.tsx
index 294a1cfe4e8d6..5c7ae23de427e 100644
--- a/apps/mobile/src/features/threads/PipelineRunPanel.tsx
+++ b/apps/mobile/src/features/threads/PipelineRunPanel.tsx
@@ -18,10 +18,15 @@ import {
pipelineStepAwaitsHandoff,
pipelineStepPosition,
pipelineStepStatusLabel,
+ pipelineStepWaitLabel,
stepName,
- threadWatchesPullRequest,
} from "@t3tools/client-runtime/pipeline-run-presentation";
-import { pipelineRunStepShells } from "@t3tools/client-runtime/state/pipeline-nesting";
+import {
+ pipelineRunStepShells,
+ possiblyStuckClock,
+ threadBackgroundWait,
+ type PipelineStepWait,
+} from "@t3tools/client-runtime/state/pipeline-nesting";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -38,6 +43,8 @@ import { Button } from "../../components/ui/Button";
import * as Dialog from "../../components/ui/Dialog";
import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
import { formatMessageTime } from "../../lib/time";
+import { useNowMinuteMs } from "../../lib/clock";
+import { environmentPresentations } from "../../state/presentation";
import { useQuietThreadShell, useQuietThreadShells } from "../../state/entities";
import { resolveThreadListV2Status, threadHasUnseenCompletion } from "./threadListV2";
import { useEnvironmentQuery } from "../../state/query";
@@ -73,25 +80,32 @@ function reportFailure(title: string, result: AtomCommandResult[0]) => threadBackgroundWait(step, clock),
+ afterHours: clock?.afterHours,
+ };
}
-function runTone(run: PipelineRun, waitingOnPullRequest: boolean): StatusTone {
+function runTone(run: PipelineRun, wait: PipelineStepWait | null): StatusTone {
switch (run.status) {
case "running":
return { label: "Running", ...STEP_TONES.active };
case "paused":
- if (!pipelineRunNeedsAttention(run, waitingOnPullRequest)) {
+ if (!pipelineRunNeedsAttention(run, wait)) {
return { label: "Waiting", ...STEP_TONES.active };
}
+ if (wait === "possibly_stuck")
+ return { label: pipelineStepWaitLabel(wait), ...ATTENTION_TONE };
return {
label: run.pauseReason === "awaiting_continue" ? "Paused" : "Needs attention",
...ATTENTION_TONE,
@@ -155,9 +169,9 @@ export function PipelineRunSummaryHeader(props: {
}),
);
const run = runQuery.data?.run ?? null;
- const waitingOnPullRequest = useRunWaitingOnPullRequest(props.environmentId, run);
+ const { wait } = useStepWait(props.environmentId, run);
if (run === null) return ;
- const tone = runTone(run, waitingOnPullRequest);
+ const tone = runTone(run, wait);
const stepIndex = Math.min(run.currentStepIndex, run.steps.length - 1);
return (
(null);
@@ -296,7 +310,7 @@ export function PipelineRunPanel(props: {
const actions = availablePipelineActions(run);
const stepIndex = run.currentStepIndex;
- const tone = runTone(run, waitingOnPullRequest);
+ const tone = runTone(run, wait);
const stepInput = { runId: run.id, stepIndex };
const startingText = composerContextProse(run.input);
// Image and file chips only bind the attachments listed above them.
@@ -309,6 +323,8 @@ export function PipelineRunPanel(props: {
run,
pipelineRunStepShells(shells, environmentId, run.id),
resolveThreadListV2Status,
+ waitOf,
+ afterHours,
);
const needsYouThreadId = needsYou?.threadId ?? null;
@@ -339,8 +355,7 @@ export function PipelineRunPanel(props: {
- {runProgressLabel(run)} · {currentStepName} ·{" "}
- {pipelineRunStateLabel(run, waitingOnPullRequest)}
+ {runProgressLabel(run)} · {currentStepName} · {pipelineRunStateLabel(run, wait)}
{needsYou !== null ? (
@@ -506,6 +521,7 @@ export function PipelineRunPanel(props: {
environmentId={environmentId}
run={run}
step={step}
+ wait={step.index === stepIndex ? wait : null}
current={step.index === stepIndex && run.status !== "completed"}
needsYou={needsYou?.threadId != null && needsYou.stepIndex === step.index}
pauseBeforeEditable={
@@ -544,6 +560,8 @@ function PipelineStepRow(props: {
readonly environmentId: EnvironmentId;
readonly run: PipelineRun;
readonly step: PipelineRun["steps"][number];
+ /** What the step's thread waits on after ending its turn without a handoff. */
+ readonly wait: PipelineStepWait | null;
readonly current: boolean;
/** The step the run's "needs you" line points at. */
readonly needsYou: boolean;
@@ -563,11 +581,22 @@ function PipelineStepRow(props: {
const childShell = useQuietThreadShell(
childThreadId === null ? null : { environmentId: props.environmentId, threadId: childThreadId },
);
- const tone = props.needsYou ? ATTENTION_TONE : STEP_TONES[pipelineStepTone(step.status)];
+ // A wake turn runs the step again, so it reads as running whatever work is still pending.
+ const awaitsHandoff =
+ step.status === "running" &&
+ pipelineStepAwaitsHandoff(run, step.index) &&
+ childShell?.runtime?.activeRunId == null;
+ const tone = props.needsYou
+ ? ATTENTION_TONE
+ : awaitsHandoff && props.wait !== null
+ ? STEP_TONES.muted
+ : STEP_TONES[pipelineStepTone(step.status)];
const statusLabel =
- props.needsYou && step.status === "running" && pipelineStepAwaitsHandoff(run, step.index)
- ? "No handoff"
- : pipelineStepStatusLabel(step);
+ awaitsHandoff && props.wait !== null
+ ? pipelineStepWaitLabel(props.wait)
+ : props.needsYou && awaitsHandoff
+ ? "No handoff"
+ : pipelineStepStatusLabel(step);
const revisions = stepRevisions(run, step.index);
const needsInput = childShell?.runtime?.status === "waiting";
const details = [
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index a7878bac88fa9..beaa4e5d5bd03 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -66,6 +66,7 @@ import {
ThreadListV2SettledShelfHeader,
ThreadListV2ShowMoreRow,
ThreadListV2SnoozedShelfHeader,
+ ThreadListV2StuckShelfHeader,
ThreadListV2WorkingShelfHeader,
} from "./thread-list-v2-items";
import { useThreadRowProviderInstanceResolver } from "./thread-provider-instance";
@@ -245,10 +246,12 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
snoozedShelfExpanded,
workingShelfEnabled,
workingShelfExpanded,
+ stuckShelfExpanded,
expandedPipelineKeys,
toggleSettledShelf,
toggleSnoozedShelf,
toggleWorkingShelf,
+ toggleStuckShelf,
togglePipelineExpanded,
} = useThreadListV2ShelfPreferences();
const now = useThreadListNow(threads);
@@ -292,6 +295,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
shelfPreferencesLoaded,
workingShelfEnabled,
workingShelfExpanded,
+ stuckShelfExpanded,
snoozedShelfExpanded,
settledShelfExpanded,
expandedPipelineKeys,
@@ -425,6 +429,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
stepStatus={item.item.stepStatus}
stepLabel={item.item.stepLabel}
suppressUnseenDone={item.item.suppressUnseenDone}
+ possiblyStuck={item.item.possiblyStuck}
earlierAttempt={item.item.earlierAttempt}
earlierFold={item.item.earlierFold}
attentionTarget={item.item.attentionTarget}
@@ -511,6 +516,16 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
pane="sidebar"
/>
);
+ case "v2-stuck-shelf":
+ return (
+
+ );
case "v2-snoozed-shelf":
return (
> =
className: "text-foreground-muted",
iconTintClassName: "accent-foreground-muted",
},
+ stuck: {
+ label: "Possibly stuck",
+ icon: "exclamationmark.circle",
+ className: "text-warning-foreground",
+ iconTintClassName: "accent-warning-foreground",
+ },
failed: {
label: "Failed",
icon: "exclamationmark.circle",
@@ -385,7 +391,12 @@ type ThreadListV2ShelfHeaderProps = {
readonly pane?: "screen" | "sidebar";
};
-const SHELF_LABEL = { working: "Working", snoozed: "Snoozed", settled: "Settled" } as const;
+const SHELF_LABEL = {
+ working: "Working",
+ stuck: "Possibly stuck",
+ snoozed: "Snoozed",
+ settled: "Settled",
+} as const;
function ThreadListV2ShelfHeader(
props: ThreadListV2ShelfHeaderProps & { readonly kind: keyof typeof SHELF_LABEL },
@@ -400,8 +411,8 @@ function ThreadListV2ShelfHeader(
expanded: props.expanded,
disabled: props.disabled,
onToggle: props.onToggle,
- accessibilityLabel: `${props.count} ${props.kind} ${props.count === 1 ? "thread" : "threads"}`,
- accessibilityHint: `${props.expanded ? "Collapses" : "Expands"} the ${props.kind} threads.`,
+ accessibilityLabel: `${props.count} ${label.toLowerCase()} ${props.count === 1 ? "thread" : "threads"}`,
+ accessibilityHint: `${props.expanded ? "Collapses" : "Expands"} the ${label.toLowerCase()} threads.`,
}}
/>
);
@@ -413,6 +424,12 @@ export const ThreadListV2WorkingShelfHeader = memo(function ThreadListV2WorkingS
return ;
});
+export const ThreadListV2StuckShelfHeader = memo(function ThreadListV2StuckShelfHeader(
+ props: ThreadListV2ShelfHeaderProps,
+) {
+ return ;
+});
+
export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedShelfHeader(
props: ThreadListV2ShelfHeaderProps,
) {
@@ -758,6 +775,8 @@ const ThreadListV2ThreadRow = memo(function ThreadListV2ThreadRow(props: {
readonly stepLabel?: string;
/** On a step of a live run that will redo it: no unseen "Done". */
readonly suppressUnseenDone?: boolean;
+ /** Background work outlived the user's threshold since the last turn ended. */
+ readonly possiblyStuck?: boolean;
/** On an earlier attempt of a step: its number; the row is dimmed. */
readonly earlierAttempt?: number;
/** On a pipeline's parent: the step its attention badge opens; null opens the parent. */
@@ -896,7 +915,7 @@ const ThreadListV2ThreadRow = memo(function ThreadListV2ThreadRow(props: {
const rawStatus = resolveThreadListV2Status(thread);
const status = mergePipelineParentStatus(
- resolveThreadListV2RowStatus(thread),
+ resolveThreadListV2RowStatus(thread, props.possiblyStuck === true),
props.stepStatus ?? null,
);
const isUnread =
diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts
index 9e21f641b691d..11e22d67f373c 100644
--- a/apps/mobile/src/features/threads/threadListV2.test.ts
+++ b/apps/mobile/src/features/threads/threadListV2.test.ts
@@ -43,6 +43,7 @@ import {
resolveThreadListV2SnoozePresets,
resolveThreadListV2RowStatus,
resolveThreadListV2Status,
+ possiblyStuckThreadKeys,
resolveThreadListV2WokeAt,
threadListV2ListItemsAreEqual,
threadListV2RowAccessibilityLabel,
@@ -624,6 +625,45 @@ describe("buildThreadListV2Items", () => {
expect(build(new Set(["one"])).items[1]?.stepLabel).toBe("one");
});
+ it("lists a thread whose background work outlived the threshold on the Possibly stuck shelf", () => {
+ const withWork = (id: string, endedAt: string, taskId = "dev-server") =>
+ makeThread({
+ id: ThreadId.make(id),
+ title: id,
+ runtime: null,
+ latestRun: { completedAt: endedAt } as never,
+ pendingBackgroundTasks: [{ taskId, kind: "command" }],
+ });
+ const threads = [
+ withWork("stale", "2026-06-01T20:00:00.000Z"),
+ withWork("fresh", "2026-06-01T23:00:00.000Z"),
+ withWork("watching", "2026-06-01T20:00:00.000Z", "pull-request-watch:github.com/o/r#1"),
+ ];
+ const build = (afterHours: number) =>
+ buildThreadListV2Items({
+ threads,
+ environmentId: null,
+ searchQuery: "",
+ now: NOW,
+ stuckThreadKeys: new Set(
+ possiblyStuckThreadKeys(threads, () => ({ nowMs: Date.parse(NOW), afterHours })),
+ ),
+ stuckShelfExpanded: true,
+ });
+
+ const layout = build(2);
+ expect(layout.stuckCount).toBe(1);
+ expect(layout.items.map((item) => [item.thread.id, item.possiblyStuck === true])).toEqual([
+ ["fresh", false],
+ ["watching", false],
+ ["stale", true],
+ ]);
+ expect(layout.stuckShelfHeaderIndex).toBe(2);
+ expect(resolveThreadListV2RowStatus(layout.items[2]!.thread, true)).toBe("stuck");
+ // 0 turns the indicator off.
+ expect(build(0).stuckCount).toBe(0);
+ });
+
it("moves a settled pinned thread into the settled shelf — parity with web (#7969)", () => {
const layout = buildThreadListV2Items({
threads: [
diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts
index 209c2c7ed6173..8e03e1bbf41f8 100644
--- a/apps/mobile/src/features/threads/threadListV2.ts
+++ b/apps/mobile/src/features/threads/threadListV2.ts
@@ -27,6 +27,11 @@ import {
pipelineStepAttempts,
pipelineStepLabel,
pipelineStepsOfParents,
+ isShellPossiblyStuck,
+ pipelineHasStuckStep,
+ threadBackgroundWait,
+ type PipelineStepWaitOf,
+ type PossiblyStuckClock,
type PipelineLiveRuns,
type PipelineNestable,
type PipelineNesting,
@@ -95,6 +100,7 @@ export type ThreadListV2Status =
| "request"
| "working"
| "waiting"
+ | "stuck"
| "failed"
| "limited"
| "ready";
@@ -353,23 +359,42 @@ export function threadListV2RowAccessibilityLabel(input: {
.join(", ");
}
+/**
+ * The threads past the user's threshold. The list keys its layout on this set, not on the
+ * clock, so a minute tick rebuilds nothing until a thread actually crosses the line.
+ */
+export function possiblyStuckThreadKeys(
+ threads: ReadonlyArray,
+ stuckClockOf: (environmentId: EnvironmentId) => PossiblyStuckClock | undefined,
+): ReadonlyArray {
+ return threads
+ .filter((thread) => isShellPossiblyStuck(thread, stuckClockOf(thread.environmentId)))
+ .map((thread) => `${thread.environmentId}:${thread.id}`)
+ .sort();
+}
+
/** Row status: a failure the user has already opened settles to ready, like Done. */
export function resolveThreadListV2RowStatus(
thread: Parameters[0] &
Pick,
+ possiblyStuck = false,
): ThreadListV2Status {
const status = resolveThreadListV2Status(thread);
+ if (possiblyStuck && (status === "ready" || status === "waiting")) return "stuck";
// A runtime failure without a failed run has nothing to date it, so it stays.
if (status !== "failed" || thread.latestRun?.status !== "failed") return status;
return hasUnseenRunFailure(thread) ? status : "ready";
}
/** What a pipeline's parent row shows for its steps and live run; the row merges it with its own status. */
-export function resolveThreadListV2StepStatus(
- steps: ReadonlyArray[0] & PipelineNestable>,
- run?: Pick | null,
+export function resolveThreadListV2StepStatus<
+ T extends Parameters[0] & PipelineNestable,
+>(
+ steps: ReadonlyArray,
+ run?: Pick | null,
+ waitOf?: PipelineStepWaitOf,
) {
- return aggregatePipelineStepStatus(steps, resolveThreadListV2Status, run);
+ return aggregatePipelineStepStatus(steps, resolveThreadListV2Status, run, waitOf);
}
/**
@@ -461,6 +486,8 @@ export interface ThreadListV2Item {
readonly nested?: boolean;
/** Whether this is the last step of its pipeline. */
readonly isLastStep?: boolean;
+ /** Background work outlived the user's threshold since the last turn ended. */
+ readonly possiblyStuck?: boolean;
/** On a pipeline's parent: what its steps and live run need. On a step: what it needs, merged with its own status. */
readonly stepStatus?: ReturnType;
/** On a pipeline step: its label under the parent. */
@@ -509,6 +536,8 @@ export interface ThreadListV2Layout {
readonly listedSettledThreads: ReadonlyArray;
readonly workingCount: number;
readonly workingShelfHeaderIndex: number | null;
+ readonly stuckCount: number;
+ readonly stuckShelfHeaderIndex: number | null;
readonly snoozedCount: number;
readonly snoozedShelfHeaderIndex: number | null;
readonly settledCount: number;
@@ -549,6 +578,14 @@ export interface ThreadListV2WorkingShelfListItem {
readonly disabled: boolean;
}
+export interface ThreadListV2StuckShelfListItem {
+ readonly type: "v2-stuck-shelf";
+ readonly key: "v2-stuck-shelf";
+ readonly count: number;
+ readonly expanded: boolean;
+ readonly disabled: boolean;
+}
+
export interface ThreadListV2SnoozedShelfListItem {
readonly type: "v2-snoozed-shelf";
readonly key: "v2-snoozed-shelf";
@@ -570,6 +607,7 @@ export type ThreadListV2ListItem =
| ThreadListV2ThreadListItem
| ThreadListV2PendingListItem
| ThreadListV2WorkingShelfListItem
+ | ThreadListV2StuckShelfListItem
| ThreadListV2SnoozedShelfListItem
| ThreadListV2SettledShelfListItem;
@@ -580,6 +618,7 @@ export function isThreadListV2ListItem(value: {
value.type === "v2-thread" ||
value.type === "v2-pending" ||
value.type === "v2-working-shelf" ||
+ value.type === "v2-stuck-shelf" ||
value.type === "v2-snoozed-shelf" ||
value.type === "v2-settled-shelf"
);
@@ -600,6 +639,7 @@ export function threadListV2ListItemsAreEqual(
previous.item.snoozed === item.item.snoozed &&
previous.item.pinned === item.item.pinned &&
previous.item.wokeAt === item.item.wokeAt &&
+ previous.item.possiblyStuck === item.item.possiblyStuck &&
previous.item.nested === item.item.nested &&
previous.item.isLastStep === item.item.isLastStep &&
previous.item.stepStatus === item.item.stepStatus &&
@@ -636,6 +676,13 @@ export function threadListV2ListItemsAreEqual(
previous.expanded === item.expanded &&
previous.disabled === item.disabled
);
+ case "v2-stuck-shelf":
+ return (
+ previous.type === "v2-stuck-shelf" &&
+ previous.count === item.count &&
+ previous.expanded === item.expanded &&
+ previous.disabled === item.disabled
+ );
case "v2-snoozed-shelf":
return (
previous.type === "v2-snoozed-shelf" &&
@@ -679,6 +726,9 @@ export function buildThreadListV2ListItems(input: {
readonly workingCount?: number;
readonly workingShelfExpanded?: boolean;
readonly workingShelfHeaderIndex?: number | null;
+ readonly stuckCount?: number;
+ readonly stuckShelfExpanded?: boolean;
+ readonly stuckShelfHeaderIndex?: number | null;
readonly snoozedCount?: number;
readonly snoozedShelfExpanded?: boolean;
readonly snoozedShelfHeaderIndex?: number | null;
@@ -734,12 +784,15 @@ export function buildThreadListV2ListItems(input: {
}));
const workingCount = input.workingCount ?? 0;
const workingShelfHeaderIndex = input.workingShelfHeaderIndex ?? null;
+ const stuckCount = input.stuckCount ?? 0;
+ const stuckShelfHeaderIndex = input.stuckShelfHeaderIndex ?? null;
const snoozedCount = input.snoozedCount ?? 0;
const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null;
const settledCount = input.settledCount ?? 0;
const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null;
const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length;
- const workingEnd = snoozedShelfHeaderIndex ?? snoozedEnd;
+ const stuckEnd = snoozedShelfHeaderIndex ?? snoozedEnd;
+ const workingEnd = stuckShelfHeaderIndex ?? stuckEnd;
const activeEnd = workingShelfHeaderIndex ?? workingEnd;
const result: ThreadListV2ListItem[] = [...pendingItems, ...threadItems.slice(0, activeEnd)];
const shelfDisabled = input.shelfPreferencesLoading === true;
@@ -753,6 +806,16 @@ export function buildThreadListV2ListItems(input: {
});
result.push(...threadItems.slice(workingShelfHeaderIndex, workingEnd));
}
+ if (stuckShelfHeaderIndex !== null && stuckCount > 0) {
+ result.push({
+ type: "v2-stuck-shelf",
+ key: "v2-stuck-shelf",
+ count: stuckCount,
+ expanded: input.stuckShelfExpanded === true,
+ disabled: shelfDisabled,
+ });
+ result.push(...threadItems.slice(stuckShelfHeaderIndex, stuckEnd));
+ }
if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) {
result.push({
type: "v2-snoozed-shelf",
@@ -823,6 +886,9 @@ export function buildThreadListV2Items(input: {
readonly workingShelfEnabled?: boolean;
readonly workingShelfExpanded?: boolean;
readonly isWorking?: (thread: EnvironmentThreadShell) => boolean;
+ /** Threads past the Possibly stuck threshold, as `environmentId:threadId`; see `possiblyStuckThreadKeys`. */
+ readonly stuckThreadKeys?: ReadonlySet;
+ readonly stuckShelfExpanded?: boolean;
/** Live pipeline runs of every environment that offers pipelines. */
readonly pipelineRuns?: PipelineLiveRuns;
/** Pipeline parents, as `environmentId:threadId`, that list all their steps. */
@@ -859,6 +925,7 @@ export function buildThreadListV2Items(input: {
const pinned: EnvironmentThreadShell[] = [];
const active: EnvironmentThreadShell[] = [];
const working: EnvironmentThreadShell[] = [];
+ const stuck: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
let nextSnoozeWakeAt: string | null = null;
@@ -887,6 +954,12 @@ export function buildThreadListV2Items(input: {
const contentOnlyThreadKeys = new Set();
const parentOfStep = pipelineParentsOfSteps(listedThreads);
const stepsOfParent = pipelineStepsOfParents(listedThreads, parentOfStep);
+ const isStuck = (thread: EnvironmentThreadShell) =>
+ input.stuckThreadKeys?.has(`${thread.environmentId}:${thread.id}`) === true;
+ const waitOf: PipelineStepWaitOf = (thread) => {
+ const wait = threadBackgroundWait(thread);
+ return wait !== null && isStuck(thread) ? "possibly_stuck" : wait;
+ };
for (const thread of listedThreads) {
if (matchingThreads !== null && !matchingThreads.has(thread)) {
const key = threadSearchMatchKey({
@@ -917,6 +990,15 @@ export function buildThreadListV2Items(input: {
settled.push(thread);
} else if (owner.pinnedAt != null) {
pinned.push(thread);
+ } else if (
+ isStuck(owner) ||
+ pipelineHasStuckStep(
+ livePipelineRunOf(input.pipelineRuns, owner),
+ stepsOfParent.get(`${owner.environmentId}:${owner.id}`) ?? [],
+ waitOf,
+ )
+ ) {
+ stuck.push(thread);
} else if (
// A pipeline counts as working while any of its steps does, so it stays on the shelf.
workingShelfEnabled &&
@@ -964,6 +1046,8 @@ export function buildThreadListV2Items(input: {
listedSettledThreads: [],
workingCount: 0,
workingShelfHeaderIndex: null,
+ stuckCount: 0,
+ stuckShelfHeaderIndex: null,
snoozedCount: 0,
snoozedShelfHeaderIndex: null,
settledCount: 0,
@@ -982,6 +1066,7 @@ export function buildThreadListV2Items(input: {
workingShelfEnabled ? null : "active",
);
const nestedWorking = nestThreadListV2Section(sortWorkingThreadsBySend(working), null);
+ const nestedStuck = nestThreadListV2Section(sortWorkingThreadsBySend(stuck), null);
const nestedSnoozed = nestThreadListV2Section(
[...snoozed].sort(
(left, right) =>
@@ -994,6 +1079,7 @@ export function buildThreadListV2Items(input: {
...nestedPinned.stepsByParentKey,
...nestedActive.stepsByParentKey,
...nestedWorking.stepsByParentKey,
+ ...nestedStuck.stepsByParentKey,
...nestedSnoozed.stepsByParentKey,
...nestedSettled.stepsByParentKey,
]);
@@ -1001,6 +1087,7 @@ export function buildThreadListV2Items(input: {
? nestedActive.rows
: applyPendingThreadOrder(nestedActive.rows, "active", pending);
const orderedWorking = nestedWorking.rows;
+ const orderedStuck = nestedStuck.rows;
const orderedSnoozed = nestedSnoozed.rows;
const selectedThreadKey = input.selectedThreadKey ?? null;
// A collapsed shelf keeps the open thread's row, and the parent's row when a step is open.
@@ -1011,6 +1098,8 @@ export function buildThreadListV2Items(input: {
?.some((step) => `${step.environmentId}:${step.id}` === selectedThreadKey) === true;
const visibleWorking =
input.workingShelfExpanded === true ? orderedWorking : orderedWorking.filter(holdsSelected);
+ const visibleStuck =
+ input.stuckShelfExpanded === true ? orderedStuck : orderedStuck.filter(holdsSelected);
const visibleSnoozed =
input.snoozedShelfExpanded === true ? orderedSnoozed : orderedSnoozed.filter(holdsSelected);
const orderedSettled = nestedSettled.rows;
@@ -1044,13 +1133,13 @@ export function buildThreadListV2Items(input: {
const run = livePipelineRunOf(input.pipelineRuns, thread);
const progress =
thread.pipeline != null && thread.pipeline.stepId === null
- ? pipelineProgressSegments(run, steps ?? [], resolveThreadListV2Status)
+ ? pipelineProgressSegments(run, steps ?? [], resolveThreadListV2Status, waitOf)
: [];
const expanded = expandedPipelines.has(key);
const isRun = thread.pipeline != null && thread.pipeline.stepId === null;
const attempts = steps === undefined ? undefined : pipelineStepAttempts(run, steps);
const attention = isRun
- ? pipelineAttentionTargets(run, steps ?? [], resolveThreadListV2Status)
+ ? pipelineAttentionTargets(run, steps ?? [], resolveThreadListV2Status, waitOf)
: undefined;
const foldKey = pipelineEarlierFoldKey(key);
const foldExpanded = expandedPipelines.has(foldKey);
@@ -1069,10 +1158,11 @@ export function buildThreadListV2Items(input: {
items.push({
thread,
...row,
+ ...(isStuck(thread) ? { possiblyStuck: true } : {}),
isLast: false,
...(steps === undefined && run === undefined
? {}
- : { stepStatus: resolveThreadListV2StepStatus(steps ?? [], run) }),
+ : { stepStatus: resolveThreadListV2StepStatus(steps ?? [], run, waitOf) }),
...(progress.length === 0
? {}
: {
@@ -1094,6 +1184,7 @@ export function buildThreadListV2Items(input: {
wokeAt: null,
isLast: false,
nested: true,
+ ...(isStuck(step) ? { possiblyStuck: true } : {}),
stepLabel: pipelineStepLabel(input.pipelineRuns, step),
...(attentionStatus === undefined ? {} : { stepStatus: attentionStatus }),
...(attempts?.redoKeys.has(stepKey) ? { suppressUnseenDone: true } : {}),
@@ -1147,6 +1238,15 @@ export function buildThreadListV2Items(input: {
wokeAt: resolveThreadListV2WokeAt(thread, { now }),
});
}
+ const stuckShelfHeaderIndex = orderedStuck.length > 0 ? items.length : null;
+ for (const thread of visibleStuck) {
+ pushRow(thread, {
+ variant: "card",
+ snoozed: false,
+ pinned: false,
+ wokeAt: resolveThreadListV2WokeAt(thread, { now }),
+ });
+ }
const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null;
for (const thread of visibleSnoozed) {
pushRow(thread, { variant: "slim", snoozed: true, pinned: false, wokeAt: null });
@@ -1165,6 +1265,8 @@ export function buildThreadListV2Items(input: {
listedSettledThreads: listedSettled,
workingCount: orderedWorking.length,
workingShelfHeaderIndex,
+ stuckCount: orderedStuck.length,
+ stuckShelfHeaderIndex,
snoozedCount: orderedSnoozed.length,
snoozedShelfHeaderIndex,
settledCount: settledTotal,
diff --git a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts
index 3e907f18dbaa2..81a1270c4e82e 100644
--- a/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts
+++ b/apps/mobile/src/features/threads/use-thread-list-v2-shelf-preferences.ts
@@ -19,6 +19,8 @@ export function useThreadListV2ShelfPreferences() {
const workingShelfEnabled = loaded && preferencesResult.value.workingShelfEnabled !== false;
const workingShelfExpanded =
loaded && preferencesResult.value.threadListWorkingShelfExpanded === true;
+ const stuckShelfExpanded =
+ loaded && preferencesResult.value.threadListStuckShelfExpanded === true;
const expandedPipelineKeys =
(loaded ? preferencesResult.value.threadListExpandedPipelines : undefined) ??
NO_EXPANDED_PIPELINES;
@@ -48,6 +50,14 @@ export function useThreadListV2ShelfPreferences() {
}),
});
};
+ const toggleStuckShelf = () => {
+ if (!loaded) return;
+ savePreferences({
+ transform: (current) => ({
+ threadListStuckShelfExpanded: current.threadListStuckShelfExpanded !== true,
+ }),
+ });
+ };
const togglePipelineExpanded = (threadKey: string) => {
if (!loaded) return;
savePreferences({
@@ -71,10 +81,12 @@ export function useThreadListV2ShelfPreferences() {
snoozedShelfExpanded,
workingShelfEnabled,
workingShelfExpanded,
+ stuckShelfExpanded,
expandedPipelineKeys,
toggleSettledShelf,
toggleSnoozedShelf,
toggleWorkingShelf,
+ toggleStuckShelf,
togglePipelineExpanded,
} as const;
}
diff --git a/apps/mobile/src/features/threads/useThreadListV2.test.tsx b/apps/mobile/src/features/threads/useThreadListV2.test.tsx
index be527e0ae316e..a93a7422a38da 100644
--- a/apps/mobile/src/features/threads/useThreadListV2.test.tsx
+++ b/apps/mobile/src/features/threads/useThreadListV2.test.tsx
@@ -17,6 +17,10 @@ vi.mock("../../state/threads", () => ({
threadFamilies: { mountRows: () => () => {} },
}));
vi.mock("../../state/atom-registry", () => ({ appAtomRegistry: undefined }));
+vi.mock("../../state/presentation", async () => {
+ const { Atom } = await import("effect/reactivity");
+ return { environmentPresentations: { serverConfigsAtom: Atom.make(new Map()) } };
+});
vi.mock("../../state/server", async () => {
const { Atom } = await import("effect/reactivity");
const noPipelineRuns = Atom.make(undefined);
@@ -62,6 +66,7 @@ it("reuses a large thread list across tab renders and updates when its inputs ch
shelfPreferencesLoaded: true,
workingShelfEnabled: true,
workingShelfExpanded: false,
+ stuckShelfExpanded: false,
snoozedShelfExpanded: false,
settledShelfExpanded: true,
pipelineEnvironmentIds: environmentIds,
diff --git a/apps/mobile/src/features/threads/useThreadListV2.ts b/apps/mobile/src/features/threads/useThreadListV2.ts
index 12f5dcec00c7a..10f8234982daf 100644
--- a/apps/mobile/src/features/threads/useThreadListV2.ts
+++ b/apps/mobile/src/features/threads/useThreadListV2.ts
@@ -2,7 +2,9 @@ import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads";
import type { EnvironmentId } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useMemo, useSyncExternalStore } from "react";
+import { possiblyStuckClock } from "@t3tools/client-runtime/state/pipeline-nesting";
+import { environmentPresentations } from "../../state/presentation";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";
import { serverEnvironment } from "../../state/server";
@@ -11,6 +13,7 @@ import {
buildThreadListV2Items,
buildThreadListV2ListItems,
getThreadListV2OrderedSection,
+ possiblyStuckThreadKeys,
threadListInboxReturns,
threadListV2LayoutTime,
} from "./threadListV2";
@@ -66,12 +69,18 @@ export function useThreadListV2(input: {
readonly shelfPreferencesLoaded: boolean;
readonly workingShelfEnabled: boolean;
readonly workingShelfExpanded: boolean;
+ readonly stuckShelfExpanded: boolean;
readonly snoozedShelfExpanded: boolean;
readonly settledShelfExpanded: boolean;
readonly expandedPipelineKeys: ReadonlyArray;
readonly selectedThreadKey: string | null;
}) {
const { threads, workingShelfEnabled } = input;
+ const serverConfigs = useAtomValue(environmentPresentations.serverConfigsAtom);
+ const nowMs = Date.parse(input.now);
+ const stuckClockOf = (environmentId: EnvironmentId) =>
+ possiblyStuckClock(serverConfigs.get(environmentId)?.settings, nowMs);
+ const stuckThreadKeys = useKeySet(possiblyStuckThreadKeys(threads, stuckClockOf).join("\n"));
// Hermes lacks toSorted.
const pipelineRuns = useAtomValue(
serverEnvironment.pipelineLiveRunsAtom([...input.pipelineEnvironmentIds].sort().join("\n")),
@@ -156,6 +165,8 @@ export function useThreadListV2(input: {
now: layoutTime,
workingShelfEnabled,
workingShelfExpanded: input.workingShelfExpanded,
+ stuckThreadKeys,
+ stuckShelfExpanded: input.stuckShelfExpanded,
inboxReturnAt: inbox.returnedAt,
isWorking: inbox.isWorking,
pipelineRuns,
@@ -190,6 +201,8 @@ export function useThreadListV2(input: {
layoutTime,
workingShelfEnabled,
input.workingShelfExpanded,
+ stuckThreadKeys,
+ input.stuckShelfExpanded,
inbox.returnedAt,
inbox.isWorking,
pipelineRuns,
@@ -230,6 +243,9 @@ export function useThreadListV2(input: {
workingCount: layout.workingCount,
workingShelfExpanded: input.workingShelfExpanded,
workingShelfHeaderIndex: layout.workingShelfHeaderIndex,
+ stuckCount: layout.stuckCount,
+ stuckShelfExpanded: input.stuckShelfExpanded,
+ stuckShelfHeaderIndex: layout.stuckShelfHeaderIndex,
snoozedCount: layout.snoozedCount,
snoozedShelfExpanded: input.snoozedShelfExpanded,
snoozedShelfHeaderIndex: layout.snoozedShelfHeaderIndex,
@@ -246,6 +262,7 @@ export function useThreadListV2(input: {
layout,
pendingTasks,
input.workingShelfExpanded,
+ input.stuckShelfExpanded,
input.snoozedShelfExpanded,
input.settledShelfExpanded,
input.now,
diff --git a/apps/mobile/src/lib/clock.test.ts b/apps/mobile/src/lib/clock.test.ts
deleted file mode 100644
index a72efe95e36ee..0000000000000
--- a/apps/mobile/src/lib/clock.test.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { describe, expect, it } from "vite-plus/test";
-
-import { minuteTickToEpochMs } from "./clock";
-
-describe("minuteTickToEpochMs", () => {
- it("reads the minute tick as UTC regardless of the device timezone", () => {
- expect(minuteTickToEpochMs("2026-10-26T02:14")).toBe(Date.UTC(2026, 9, 26, 2, 14));
- });
-});
diff --git a/apps/mobile/src/lib/clock.ts b/apps/mobile/src/lib/clock.ts
index 58dc38cfd5f13..76afe7ed1aa21 100644
--- a/apps/mobile/src/lib/clock.ts
+++ b/apps/mobile/src/lib/clock.ts
@@ -1,4 +1,4 @@
-import { deadlineStore, minuteTick } from "@t3tools/client-runtime/clock";
+import { deadlineStore, minuteTick, minuteTickToEpochMs } from "@t3tools/client-runtime/clock";
import { useState, useSyncExternalStore } from "react";
/** Re-renders once when `deadlineMs` (epoch ms) is reached; `null` never passes. */
@@ -22,14 +22,6 @@ export function useNowAfter(deadlineMs: number | null): number {
return snapshot.nowMs;
}
-/**
- * `minuteTick`'s UTC `YYYY-MM-DDTHH:mm` as epoch ms. The snapshot carries no
- * offset, and `Date.parse` reads offset-less date-times as local time.
- */
-export function minuteTickToEpochMs(minute: string): number {
- return Date.parse(`${minute}:00Z`);
-}
-
/** Epoch ms floored to the minute, advancing each wall-clock minute. */
export function useNowMinuteMs(): number {
return minuteTickToEpochMs(
diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts
index b529b185c9957..33a4d00df5551 100644
--- a/apps/mobile/src/persistence/mobile-preferences.ts
+++ b/apps/mobile/src/persistence/mobile-preferences.ts
@@ -138,6 +138,7 @@ export interface Preferences {
readonly threadListSettledShelfExpanded?: boolean;
readonly threadListSnoozedShelfExpanded?: boolean;
readonly threadListWorkingShelfExpanded?: boolean;
+ readonly threadListStuckShelfExpanded?: boolean;
/** Pipeline parents, as `environmentId:threadId`, that list all their steps. */
readonly threadListExpandedPipelines?: readonly string[];
readonly threadListFilters?: ThreadListFilters;
@@ -224,6 +225,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
threadListSettledShelfExpanded?: boolean;
threadListSnoozedShelfExpanded?: boolean;
threadListWorkingShelfExpanded?: boolean;
+ threadListStuckShelfExpanded?: boolean;
threadListExpandedPipelines?: readonly string[];
threadListFilters?: ThreadListFilters;
pullRequestListFilters?: PullRequestListPreferences;
@@ -374,6 +376,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
if (typeof parsed.threadListWorkingShelfExpanded === "boolean") {
preferences.threadListWorkingShelfExpanded = parsed.threadListWorkingShelfExpanded;
}
+ if (typeof parsed.threadListStuckShelfExpanded === "boolean") {
+ preferences.threadListStuckShelfExpanded = parsed.threadListStuckShelfExpanded;
+ }
if (Array.isArray(parsed.threadListExpandedPipelines)) {
preferences.threadListExpandedPipelines = parsed.threadListExpandedPipelines.filter(
(key): key is string => typeof key === "string",
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts
index 0151f7a3f27ed..9c1554f0535c8 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts
@@ -5980,7 +5980,36 @@ describe("OrchestratorMcpService pipelines", () => {
steps: runningStep(1, "thread:busy-step"),
}),
run({ id: PipelineRunId.make("pipeline-run:handoff"), pauseReason: "awaiting_handoff" }),
+ run({
+ id: PipelineRunId.make("pipeline-run:background"),
+ pauseReason: "awaiting_handoff",
+ steps: runningStep(1, "thread:background-step"),
+ }),
+ run({
+ id: PipelineRunId.make("pipeline-run:stuck"),
+ pauseReason: "awaiting_handoff",
+ steps: runningStep(1, "thread:stuck-step"),
+ }),
+ run({
+ id: PipelineRunId.make("pipeline-run:finished-work"),
+ pauseReason: "awaiting_handoff",
+ steps: runningStep(1, "thread:finished-step"),
+ }),
+ run({
+ id: PipelineRunId.make("pipeline-run:waking"),
+ pauseReason: "awaiting_handoff",
+ steps: runningStep(1, "thread:waking-step"),
+ }),
];
+ // A step thread whose turn ended with work still running; the clock below sits 3 hours in.
+ const endedWithWork = (id: string, endedAtMs: number, taskId = "command:dev-server") => ({
+ ...liveThreadShell(ThreadId.make(id), { activeRunId: null }),
+ status: "completed" as const,
+ latestRunCompletedAt: DateTime.makeUnsafe(endedAtMs),
+ pendingBackgroundTasks: [{ taskId, kind: "command" as const }],
+ });
+ const hours = (count: number) => count * 3_600_000;
+ yield* TestClock.adjust(Duration.hours(3));
const asking = {
...liveThreadShell(ThreadId.make("thread:asking-step")),
pendingRuntimeRequest: {
@@ -5991,13 +6020,27 @@ describe("OrchestratorMcpService pipelines", () => {
};
const h = harness(
{ runtimeMode: "full-access", interactionMode: "default" },
- { runs, shells: [asking, liveThreadShell(ThreadId.make("thread:busy-step"))] },
+ {
+ runs,
+ shells: [
+ asking,
+ liveThreadShell(ThreadId.make("thread:busy-step")),
+ endedWithWork("thread:background-step", hours(2.5)),
+ endedWithWork("thread:stuck-step", 0),
+ {
+ ...endedWithWork("thread:finished-step", 0),
+ pendingBackgroundTasks: [],
+ },
+ // Work that ended woke the agent; the run stays paused until that turn hands off.
+ liveThreadShell(ThreadId.make("thread:waking-step")),
+ ],
+ },
);
const waiting = yield* withService(h, (service) =>
service.listPipelineRuns(h.scope, { needsAttention: true, limit: 1 }),
);
- assert.equal(waiting.total, 2);
+ assert.equal(waiting.total, 4);
assert.equal(waiting.nextCursor, 1);
assert.deepEqual(
waiting.runs.map((entry) => [entry.runId, entry.attention]),
@@ -6008,15 +6051,28 @@ describe("OrchestratorMcpService pipelines", () => {
);
assert.deepEqual(
rest.runs.map((entry) => [entry.runId, entry.attention]),
- [["pipeline-run:handoff", "awaiting_handoff"]],
+ [
+ ["pipeline-run:handoff", "awaiting_handoff"],
+ ["pipeline-run:stuck", "possibly_stuck"],
+ ["pipeline-run:finished-work", "awaiting_handoff"],
+ ],
);
assert.equal(rest.nextCursor, null);
const all = yield* withService(h, (service) => service.listPipelineRuns(h.scope, {}));
- assert.equal(all.total, 4);
+ assert.equal(all.total, 8);
assert.deepEqual(
all.runs.map((entry) => entry.attention),
- [null, "pending_request", null, "awaiting_handoff"],
+ [
+ null,
+ "pending_request",
+ null,
+ "awaiting_handoff",
+ null,
+ "possibly_stuck",
+ "awaiting_handoff",
+ null,
+ ],
);
assert.isString(all.runs[1]?.steps[1]?.link);
assert.notProperty(all.runs[0]?.steps[0], "outputPreview");
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 3a4568e51df9c..72e925499f80e 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -104,7 +104,10 @@ import {
SECRET_REQUEST_UNSAVED_NOTE,
} from "@t3tools/contracts";
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
-import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
+import {
+ backgroundWorkHoldsCompletion,
+ classifyBackgroundWait,
+} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
@@ -2503,14 +2506,37 @@ const make = Effect.gen(function* () {
const runAttention = Effect.fn("OrchestratorMcpService.runAttention")(function* (
run: PipelineRun,
) {
- if (run.status === "paused") return run.pauseReason ?? "awaiting_continue";
- if (run.status !== "running") return null;
+ const pauseReason = run.status === "paused" ? (run.pauseReason ?? "awaiting_continue") : null;
+ if (run.status !== "running" && run.status !== "paused") return null;
+ if (pauseReason !== null && pauseReason !== "awaiting_handoff") return pauseReason;
const threadId = run.steps[run.currentStepIndex]?.childThreadId ?? null;
- if (threadId === null) return null;
+ if (threadId === null) return pauseReason;
const shell = yield* threadManagement
.getThreadShell(threadId)
.pipe(Effect.mapError(threadManagementFailure));
- return shell?.pendingRuntimeRequest == null ? null : ("pending_request" as const);
+ // A turn running again (a wake turn or the user's reply) is busy, as clients show it.
+ if (pauseReason === null || shell?.activeRunId != null) {
+ return shell?.pendingRuntimeRequest == null ? null : ("pending_request" as const);
+ }
+ if (shell === null) return pauseReason;
+ const settings = yield* serverSettings.getSettings.pipe(
+ Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")),
+ );
+ const nowMs = yield* Clock.currentTimeMillis;
+ // A step waiting on its own background work is not waiting on the user, until it looks stuck.
+ const wait = classifyBackgroundWait(
+ {
+ activeRunId: shell.activeRunId,
+ archived: shell.archivedAt !== null,
+ pendingBackgroundTasks: shell.pendingBackgroundTasks,
+ lastRunEndedAtMs:
+ shell.latestRunCompletedAt == null
+ ? null
+ : DateTime.toEpochMillis(shell.latestRunCompletedAt),
+ },
+ { nowMs, afterHours: settings.possiblyStuckAfterHours },
+ );
+ return wait === null ? pauseReason : wait === "possibly_stuck" ? wait : null;
});
const resolvePipeline = Effect.fn("OrchestratorMcpService.resolvePipeline")(function* (
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index 96549d3530641..d105732da7457 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -291,7 +291,7 @@ const StartPipelineTool = Tool.make("start_pipeline", {
const PipelineStatusTool = Tool.make("pipeline_status", {
description:
- "Status of a pipeline run: each step's status, thread `link`, output preview, and the feedback sent to steps so far (`revisions`). `paused` with `awaiting_continue`: `continue_pipeline` if you started the run, or if you are the run's own coordinator chat and the user's latest message asks you to; else wait for the user. The user's feedback on an earlier step: `revise_pipeline_step`. `awaiting_handoff`: the step's agent ended its turn without handing off, usually with a question; tell the user. No tool retries or skips a failed or stopped step: tell the user.",
+ "Status of a pipeline run: each step's status, thread `link`, output preview, and the feedback sent to steps so far (`revisions`). `paused` with `awaiting_continue`: `continue_pipeline` if you started the run, or if you are the run's own coordinator chat and the user's latest message asks you to; else wait for the user. The user's feedback on an earlier step: `revise_pipeline_step`. `awaiting_handoff`: the step's agent ended its turn without handing off, usually with a question; tell the user, unless its thread still has background work: it waits on that until `list_pipeline_runs` reports `possibly_stuck`. No tool retries or skips a failed or stopped step: tell the user.",
parameters: OrchestratorMcpPipelineRunInput,
success: OrchestratorMcpPipelineRun,
failure: OrchestratorMcpFailure,
@@ -305,7 +305,7 @@ const PipelineStatusTool = Tool.make("pipeline_status", {
const ListPipelineRunsTool = Tool.make("list_pipeline_runs", {
description:
- "List pipeline runs newest first, with each step's status and thread `link`. Filter by `pipeline`, `projectId`, `statuses`. What waits for the user: `needsAttention=true`; each run's `attention` says why (a pause reason, or `pending_request`: the running step asks an approval or question in its thread). Details and feedback: `pipeline_status`. Page with `cursor`.",
+ "List pipeline runs newest first, with each step's status and thread `link`. Filter by `pipeline`, `projectId`, `statuses`. What waits for the user: `needsAttention=true`; each run's `attention` says why (a pause reason; `pending_request`: the running step asks an approval or question in its thread; `possibly_stuck`: a step without a handoff has had background work running for hours). A step still waiting on background work has none. Details and feedback: `pipeline_status`. Page with `cursor`.",
parameters: OrchestratorMcpListPipelineRunsInput,
success: OrchestratorMcpListPipelineRunsResult,
failure: OrchestratorMcpFailure,
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index 943072b1c94f1..1b69e139a87dc 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 5959,
"codexAdditionalContextBytes": 7353,
- "mcpToolListJsonBytes": 58052
+ "mcpToolListJsonBytes": 58300
}
diff --git a/apps/web/src/components/Sidebar.drag.ts b/apps/web/src/components/Sidebar.drag.ts
index 76f2c9bf3a3ec..e53495d70f4b5 100644
--- a/apps/web/src/components/Sidebar.drag.ts
+++ b/apps/web/src/components/Sidebar.drag.ts
@@ -16,6 +16,7 @@ type Layout = Parameters[0];
const isShelfHeader = (item: SidebarListItem | undefined) =>
item?.kind === "marker" &&
(item.marker === "working-header" ||
+ item.marker === "stuck-header" ||
item.marker === "snoozed-header" ||
item.marker === "settled-header");
@@ -56,7 +57,9 @@ export function createSidebarCollisionDetection(
if (pointer.x >= boundary.left && pointer.x <= boundary.right) {
if (pointer.y < previousY && pointer.y <= boundary.bottom) boundarySection = "pinned";
else if (pointer.y > previousY && pointer.y >= boundary.top) boundarySection = "active";
- const nextHeader = (["working-header", "snoozed-header", "settled-header"] as const)
+ const nextHeader = (
+ ["working-header", "stuck-header", "snoozed-header", "settled-header"] as const
+ )
.map((marker) =>
args.droppableContainers.find((container) => container.id === sidebarMarkerId(marker)),
)
@@ -118,6 +121,7 @@ export function createSidebarSortingStrategy(input: {
pinned: [],
active: [],
working: [],
+ stuck: [],
snoozed: [],
settled: [],
};
@@ -132,7 +136,12 @@ export function createSidebarSortingStrategy(input: {
}
continue;
}
- if (item.section === "pinned" || item.section === "active" || item.section === "working")
+ if (
+ item.section === "pinned" ||
+ item.section === "active" ||
+ item.section === "working" ||
+ item.section === "stuck"
+ )
cardHeight ??= rects[index]?.height;
else slimHeight ??= rects[index]?.height;
if (item.key !== active.key) groups[item.section].push(item);
@@ -180,6 +189,10 @@ export function createSidebarSortingStrategy(input: {
marker("working-header");
projected.push(...groups.working);
}
+ if (items.some((item) => item.kind === "marker" && item.marker === "stuck-header")) {
+ marker("stuck-header");
+ projected.push(...groups.stuck);
+ }
if (
groups.snoozed.length > 0 ||
((active.section !== "snoozed" || (input.snoozedThreadCount ?? 0) > 1) &&
@@ -195,7 +208,10 @@ export function createSidebarSortingStrategy(input: {
const rect = index === undefined ? undefined : rects[index];
const fallback =
item.kind === "thread" &&
- (item.section === "pinned" || item.section === "active" || item.section === "working")
+ (item.section === "pinned" ||
+ item.section === "active" ||
+ item.section === "working" ||
+ item.section === "stuck")
? cardHeight
: slimHeight;
const moved = item.kind === "thread" && item.key === active.key;
diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts
index 2fa0d608b1f1d..c448599fd80c1 100644
--- a/apps/web/src/components/Sidebar.logic.test.ts
+++ b/apps/web/src/components/Sidebar.logic.test.ts
@@ -318,6 +318,17 @@ describe("resolveSidebarRowStatus", () => {
expect(resolveSidebarRowStatus({ ...opened, latestRun: null })).toBe("failed");
});
+ it("marks a quiet thread possibly stuck, but never hides a status that needs the user", () => {
+ const quiet = {
+ ...failed,
+ runtime: { ...failedRuntime, status: "idle" as const, lastError: null },
+ latestRun: makeLatestRun(),
+ };
+ expect(resolveSidebarRowStatus(quiet, true)).toBe("stuck");
+ expect(resolveSidebarRowStatus({ ...quiet, hasPendingUserInput: true }, true)).toBe("input");
+ expect(resolveSidebarRowStatus({ ...failed, lastVisitedAt: undefined }, true)).toBe("failed");
+ });
+
it("does not show a stopped run as an unseen completion", () => {
for (const status of ["interrupted", "cancelled"] as const) {
const stopped = {
@@ -1123,12 +1134,16 @@ describe("Working shelf (beta)", () => {
row("a2", "active"),
marker("working-header"),
row("w1", "working"),
+ marker("stuck-header"),
+ row("k1", "stuck"),
marker("settled-header"),
row("s1", "settled"),
];
- it("never drops into the Working shelf, and keeps it out of the inbox order", () => {
+ it("never drops into the Working or Possibly stuck shelf, and keeps them out of the inbox order", () => {
expect(resolveSidebarDropTarget(items, "a1", "w1")).toBeNull();
+ expect(resolveSidebarDropTarget(items, "a1", "k1")).toBeNull();
+ expect(resolveSidebarDropVerb("active", "stuck")).toBeNull();
expect(resolveSidebarDropTarget(items, "p1", "a2")).toEqual({
section: "active",
pinnedOrder: [],
@@ -1138,18 +1153,19 @@ describe("Working shelf (beta)", () => {
});
it.each([
- ["pinned", "p1"],
- ["active", "a2"],
- ["settled", "s1"],
+ ["working", "w1", "pinned", "p1"],
+ ["working", "w1", "active", "a2"],
+ ["working", "w1", "settled", "s1"],
+ ["stuck", "k1", "active", "a2"],
] as const)(
- "does not move a Working thread into %s when its reference drag ends in the sidebar",
- (section, overKey) => {
- const target = resolveSidebarDropTarget(items, "w1", overKey);
+ "does not move a %s thread into %s when its reference drag ends in the sidebar",
+ (from, activeKey, section, overKey) => {
+ const target = resolveSidebarDropTarget(items, activeKey, overKey);
expect(target?.section).toBe(section);
expect(
planSidebarThreadDrop({
- activeKey: "w1",
- activeSection: "working",
+ activeKey,
+ activeSection: from,
target: target!,
pinnedOrder: ["p1"],
pinnedKeysById: new Map([["p1", "m"]]),
diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts
index e8ef73e7c11b5..4cb6b054e64c7 100644
--- a/apps/web/src/components/Sidebar.logic.ts
+++ b/apps/web/src/components/Sidebar.logic.ts
@@ -8,6 +8,9 @@ import {
type PipelineNestable,
type PipelineProgressStatus,
type PipelineStepStatus,
+ possiblyStuckClock,
+ type PipelineStepWaitOf,
+ type PossiblyStuckClock,
} from "@t3tools/client-runtime/state/pipeline-nesting";
import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
@@ -51,7 +54,12 @@ import { normalizeSearchText } from "../lib/utils";
import { isLatestRunSettled } from "../session-logic";
import { THREAD_STATUS_TEXT } from "@t3tools/client-runtime/state/thread-activity-announcement";
import { observeIntersection } from "../lib/observeIntersection";
-import { deadlineAfter, deadlineStore, type ClockStore } from "@t3tools/client-runtime/clock";
+import {
+ deadlineAfter,
+ deadlineStore,
+ minuteTickToEpochMs,
+ type ClockStore,
+} from "@t3tools/client-runtime/clock";
import { useDeadlinePassed } from "../hooks/useDeadline";
import { legacyProjectCwdPreferenceKey } from "../uiStateStore";
import { isElectron } from "../env";
@@ -198,7 +206,15 @@ export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
// Snoozed rows cannot accept drops without a wake time. Working rows only drag out as chat context.
-export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
+/** The staleness inputs for an environment; undefined until its config loads, so nothing flashes stuck. */
+export function resolveSidebarStuckClock(
+ config: EnvironmentServerConfig | undefined,
+ nowMinute: string,
+): PossiblyStuckClock | undefined {
+ return possiblyStuckClock(config?.settings, minuteTickToEpochMs(nowMinute));
+}
+
+export type SidebarSection = "pinned" | "active" | "working" | "stuck" | "snoozed" | "settled";
export function resolveSidebarThreadSection(input: {
readonly snoozed: boolean;
@@ -219,6 +235,7 @@ export type SidebarListMarker =
| "settled-placeholder"
| "pinned-divider"
| "working-header"
+ | "stuck-header"
| "snoozed-header"
| "settled-header";
@@ -241,6 +258,7 @@ function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number):
if (item.kind !== "marker") continue;
if (item.marker === "pinned-divider") section = "active";
else if (item.marker === "working-header") section = "working";
+ else if (item.marker === "stuck-header") section = "stuck";
else if (item.marker === "snoozed-header") section = "snoozed";
else if (item.marker === "settled-header") section = "settled";
}
@@ -264,7 +282,7 @@ export function resolveSidebarDropTarget(
const moved = items.filter((_, index) => index !== activeIndex);
moved.splice(overIndex, 0, items[activeIndex]!);
const section = sectionAtSidebarSlot(moved, overIndex);
- if (section === "working" || section === "snoozed") return null;
+ if (section === "working" || section === "stuck" || section === "snoozed") return null;
const pinnedOrder: string[] = [];
const activeOrder: string[] = [];
let currentSection: SidebarSection = "pinned";
@@ -273,6 +291,7 @@ export function resolveSidebarDropTarget(
if (item.marker === "pinned-divider") currentSection = "active";
else if (
item.marker === "working-header" ||
+ item.marker === "stuck-header" ||
item.marker === "snoozed-header" ||
item.marker === "settled-header"
)
@@ -312,7 +331,9 @@ export function resolveSidebarDropVerb(
from: SidebarSection,
to: SidebarSection | null,
): SidebarDropVerb | null {
- if (to === null || to === from || to === "working" || to === "snoozed") return null;
+ if (to === null || to === from || to === "working" || to === "stuck" || to === "snoozed") {
+ return null;
+ }
if (to === "pinned") return "pin";
if (to === "settled") return "settle";
if (from === "pinned") return "unpin";
@@ -397,7 +418,7 @@ export function planSidebarThreadDrop(input: {
activeKeysById,
activeReorderableKeys,
} = input;
- if (activeSection === "working") return { kind: "none" };
+ if (activeSection === "working" || activeSection === "stuck") return { kind: "none" };
if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
return { kind: "none" };
}
@@ -899,6 +920,7 @@ export type SidebarThreadStatus =
| "preparing"
| "working"
| "waiting"
+ | "stuck"
| "failed"
| "limited"
| "ready";
@@ -972,8 +994,10 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si
/** Sidebar row status: a failure the user has already opened settles to ready, like Done. */
export function resolveSidebarRowStatus(
thread: ThreadStatusInput & SidebarThreadStatusInput,
+ possiblyStuck = false,
): SidebarThreadStatus {
const status = resolveSidebarThreadStatus(thread);
+ if (possiblyStuck && (status === "ready" || status === "waiting")) return "stuck";
// A runtime failure without a failed run has nothing to date it, so it stays.
if (status !== "failed" || thread.latestRun?.status !== "failed") return status;
return hasUnseenRunFailure(thread) ? status : "ready";
@@ -999,18 +1023,21 @@ export function resolveWindowTitleThreadStatus(thread: SidebarThreadStatusInput)
}
/** What a pipeline's parent row shows for its steps and live run; see `mergePipelineParentStatus`. */
-export function resolveSidebarPipelineStepStatus(
- steps: ReadonlyArray,
- run?: Pick | null,
+export function resolveSidebarPipelineStepStatus<
+ T extends SidebarThreadStatusInput & PipelineNestable,
+>(
+ steps: ReadonlyArray,
+ run?: Pick | null,
+ waitOf?: PipelineStepWaitOf,
): PipelineStepStatus | null {
- return aggregatePipelineStepStatus(steps, resolveSidebarThreadStatus, run);
+ return aggregatePipelineStepStatus(steps, resolveSidebarThreadStatus, run, waitOf);
}
/** Which of a pipeline's step threads need the user, and the one its parent's attention badge opens. */
export function resolveSidebarPipelineAttention<
T extends SidebarThreadStatusInput & PipelineNestable & { readonly title: string },
->(run: PipelineRunSummary | undefined, steps: readonly T[]) {
- return pipelineAttentionTargets(run, steps, resolveSidebarThreadStatus);
+>(run: PipelineRunSummary | undefined, steps: readonly T[], waitOf?: PipelineStepWaitOf) {
+ return pipelineAttentionTargets(run, steps, resolveSidebarThreadStatus, waitOf);
}
/** One segment of a pipeline parent's progress bar, flat so row props compare by value. */
@@ -1028,8 +1055,9 @@ export function resolveSidebarPipelineProgress<
>(
run: PipelineRunSummary | undefined,
steps: readonly T[],
+ waitOf?: PipelineStepWaitOf,
): ReadonlyArray | undefined {
- const segments = pipelineProgressSegments(run, steps, resolveSidebarThreadStatus);
+ const segments = pipelineProgressSegments(run, steps, resolveSidebarThreadStatus, waitOf);
if (segments.length === 0) return undefined;
return segments.map((segment) => ({
stepId: segment.stepId,
@@ -1046,7 +1074,7 @@ export function resolveSidebarPipelineProgress<
export function resolveSidebarFolderDot(
threads: ReadonlyArray,
): "attention" | "failed" | "unread" | "working" | null {
- const statuses = new Set(threads.map(resolveSidebarRowStatus));
+ const statuses = new Set(threads.map((thread) => resolveSidebarRowStatus(thread)));
if (
statuses.has("input") ||
statuses.has("approval") ||
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 2b5d4f3254b09..4a79720a7254b 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -37,7 +37,9 @@ import {
import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
import {
isPipelineGroupActive,
+ isShellPossiblyStuck,
livePipelineRunOf,
+ pipelineHasStuckStep,
nestPipelineSteps,
pipelineParentsOfSteps,
pipelineEarlierFoldKey,
@@ -45,8 +47,10 @@ import {
pipelineStepAttempts,
pipelineStepLabel,
pipelineStepsOfParents,
+ threadBackgroundWait,
type PipelineLiveRuns,
type PipelineStepAttempts,
+ type PossiblyStuckClock,
} from "@t3tools/client-runtime/state/pipeline-nesting";
import {
nextShownOrder,
@@ -211,6 +215,7 @@ import {
resolveSidebarPipelineAttention,
resolveSidebarPipelineProgress,
resolveSidebarPipelineStepStatus,
+ resolveSidebarStuckClock,
resolveSidebarThreadSection,
resolveSidebarReorderableThreadKeys,
searchSidebarThreads,
@@ -351,6 +356,7 @@ const SETTLED_TAIL_PAGE_COUNT = 25;
const SETTLED_SHELF_EXPANDED_KEY = "t3code:sidebar:settled-expanded";
const SNOOZED_SHELF_EXPANDED_KEY = "t3code:sidebar:snoozed-expanded";
const WORKING_SHELF_EXPANDED_KEY = "t3code:sidebar:working-expanded";
+const STUCK_SHELF_EXPANDED_KEY = "t3code:sidebar:stuck-expanded";
const inboxReturns = createInboxReturnTracker();
@@ -381,6 +387,8 @@ interface SidebarThreadPartitionInput {
// on the clock, so the minute tick, the precise snooze-wake tick and the inbox
// tracker's expiry version are inputs: a new key repartitions.
readonly clockKey: string;
+ /** The minute clock, for the Possibly stuck check. */
+ readonly nowMinute: string;
}
function scrollSidebarToTop(content: HTMLElement | null) {
@@ -494,6 +502,11 @@ function useSidebarThreads(input: {
false,
Schema.Boolean,
);
+ const [stuckShelfExpanded, setStuckShelfExpanded] = useLocalStorage(
+ STUCK_SHELF_EXPANDED_KEY,
+ false,
+ Schema.Boolean,
+ );
// Shared with the old per-project sidebar, so folders keep their open state.
const projectExpandedById = useUiStateStore((store) => store.projectExpandedById);
const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
@@ -520,12 +533,14 @@ function useSidebarThreads(input: {
workingShelfEnabled,
sortActiveBySend: folderGroups !== null,
clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`,
+ nowMinute,
});
const {
pinnedThreads,
activeThreads,
workingThreads,
+ stuckThreads,
snoozedThreads,
settledThreads,
pipelineStepsByParentKey,
@@ -561,6 +576,9 @@ function useSidebarThreads(input: {
const visibleSnoozedThreads = snoozedShelfExpanded
? snoozedThreads
: routeThreadOnly(snoozedThreads, routeRowThreadKey, pipelineStepsByParentKey);
+ const visibleStuckThreads = stuckShelfExpanded
+ ? stuckThreads
+ : routeThreadOnly(stuckThreads, routeRowThreadKey, pipelineStepsByParentKey);
const visibleWorkingThreads = workingShelfExpanded
? workingThreads
: routeThreadOnly(workingThreads, routeRowThreadKey, pipelineStepsByParentKey);
@@ -638,6 +656,7 @@ function useSidebarThreads(input: {
projectFolders === null ? activeThreads : projectFolders.flatMap((folder) => folder.threads),
),
...withShownSteps(visibleWorkingThreads),
+ ...withShownSteps(visibleStuckThreads),
...withShownSteps(visibleSnoozedThreads),
...withShownSteps(renderedSettledThreads),
];
@@ -646,6 +665,7 @@ function useSidebarThreads(input: {
[pinnedThreads, "pinned"],
[activeThreads, "active"],
[workingThreads, "working"],
+ [stuckThreads, "stuck"],
[snoozedThreads, "snoozed"],
[settledThreads, "settled"],
] as const) {
@@ -659,6 +679,7 @@ function useSidebarThreads(input: {
...withSteps(pinnedThreads),
...withSteps(activeThreads),
...withSteps(workingThreads),
+ ...withSteps(stuckThreads),
...withSteps(snoozedThreads),
...withSteps(settledThreads),
],
@@ -677,6 +698,8 @@ function useSidebarThreads(input: {
toggleSnoozedShelf: () => setSnoozedShelfExpanded((value) => !value),
workingShelfExpanded,
toggleWorkingShelf: () => setWorkingShelfExpanded((value) => !value),
+ stuckShelfExpanded,
+ toggleStuckShelf: () => setStuckShelfExpanded((value) => !value),
shownPipelineStepsByParentKey,
pipelineAttemptsByParentKey,
expandedPipelines,
@@ -689,6 +712,7 @@ function useSidebarThreads(input: {
renderedSettledThreads,
visibleSnoozedThreads,
visibleWorkingThreads,
+ visibleStuckThreads,
orderedThreadKeys: orderedThreads.map(threadShellKey),
threadByKey: new Map(orderedThreads.map((thread) => [threadShellKey(thread), thread] as const)),
settledThreadKeys: new Set(withSteps(settledThreads).map(threadShellKey)),
@@ -717,24 +741,45 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
sortActiveBySend,
} = input;
const preciseNow = new Date().toISOString();
+ const stuckClocks = new Map();
+ const stuckClockOf = (environmentId: EnvironmentId) => {
+ if (!stuckClocks.has(environmentId)) {
+ stuckClocks.set(
+ environmentId,
+ resolveSidebarStuckClock(serverConfigs.get(environmentId), input.nowMinute),
+ );
+ }
+ return stuckClocks.get(environmentId);
+ };
+ const waitOf = (shell: EnvironmentThreadShell) =>
+ threadBackgroundWait(shell, stuckClockOf(shell.environmentId));
const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent);
const inboxObservation = inboxReturns.observe(workingShelfEnabled ? threads : null);
const pinned: EnvironmentThreadShell[] = [];
const active: EnvironmentThreadShell[] = [];
const working: EnvironmentThreadShell[] = [];
+ const stuck: EnvironmentThreadShell[] = [];
const pipelineParentOf = pipelineParentsOfSteps(visible);
const pipelineStepsOf = pipelineStepsOfParents(visible, pipelineParentOf);
// A pipeline counts as working while any of its steps does, so it stays on the shelf.
const inbox = (thread: EnvironmentThreadShell, manuallyMoved = false) =>
- workingShelfEnabled &&
- isPipelineGroupActive(
- thread,
- pipelineStepsOf,
- manuallyMoved ? isThreadWorking : inboxObservation.isWorking,
- pipelineLiveRuns,
+ // A thread whose background work outlived the threshold leaves the inbox for its own shelf.
+ isShellPossiblyStuck(thread, stuckClockOf(thread.environmentId)) ||
+ pipelineHasStuckStep(
+ livePipelineRunOf(pipelineLiveRuns, thread),
+ pipelineStepsOf.get(threadShellKey(thread)) ?? [],
+ waitOf,
)
- ? working
- : active;
+ ? stuck
+ : workingShelfEnabled &&
+ isPipelineGroupActive(
+ thread,
+ pipelineStepsOf,
+ manuallyMoved ? isThreadWorking : inboxObservation.isWorking,
+ pipelineLiveRuns,
+ )
+ ? working
+ : active;
const snoozed: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
const { draggableThreadKeys, activeReorderableThreadKeys } = resolveSidebarReorderableThreadKeys({
@@ -816,6 +861,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
},
);
const nestedWorking = nestPipelineSteps(sortWorkingThreadsBySend(working));
+ const nestedStuck = nestPipelineSteps(sortWorkingThreadsBySend(stuck));
const nestedSnoozed = nestPipelineSteps(
snoozed.toSorted(
(left, right) =>
@@ -830,6 +876,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
...nestedPinned.stepsByParentKey,
...nestedActive.stepsByParentKey,
...nestedWorking.stepsByParentKey,
+ ...nestedStuck.stepsByParentKey,
...nestedSnoozed.stepsByParentKey,
...nestedSettled.stepsByParentKey,
]);
@@ -841,6 +888,8 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
return {
pipelineStepsByParentKey,
pipelineParentKeyByStepKey,
+ stuckClockOf,
+ waitOf,
pinnedThreads:
optimisticDrop?.section !== "pinned" || optimisticDrop.order === null
? sortedPinned
@@ -860,6 +909,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
}),
workingThreads: nestedWorking.rows,
+ stuckThreads: nestedStuck.rows,
snoozedThreads: nestedSnoozed.rows,
settledThreads: nestedSettled.rows,
visibleThreads: visible,
@@ -1454,12 +1504,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
);
const {
+ stuckClockOf,
+ waitOf,
workingShelfEnabled,
pinnedThreads,
draggableThreadKeys,
activeReorderableThreadKeys,
activeThreads,
workingThreads,
+ stuckThreads,
snoozedThreads,
settledThreads,
snoozeNow,
@@ -1481,11 +1534,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
toggleSnoozedShelf,
workingShelfExpanded,
toggleWorkingShelf,
+ stuckShelfExpanded,
+ toggleStuckShelf,
projectFolders,
toggleProjectFolder,
renderedSettledThreads,
visibleSnoozedThreads,
visibleWorkingThreads,
+ visibleStuckThreads,
orderedThreadKeys,
threadByKey,
settledThreadKeys,
@@ -1907,7 +1963,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
const isContextDrag =
projectFolders !== null ||
dragState?.contextDrag === true ||
- dragState?.activeSection === "working";
+ dragState?.activeSection === "working" ||
+ dragState?.activeSection === "stuck";
const dragTargetSection = isContextDrag ? null : (dragState?.targetSection ?? null);
const finishThreadDrag = (started: boolean) => {
dragSensorRef.current = null;
@@ -2131,6 +2188,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
pinnedThreads.length +
activeThreads.length +
workingThreads.length +
+ stuckThreads.length +
snoozedThreads.length +
settledCount ===
0
@@ -2148,6 +2206,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
items.push({ kind: "marker", marker: "working-header" });
items.push(...rowsOf(visibleWorkingThreads, "working"));
}
+ if (stuckThreads.length > 0) {
+ items.push({ kind: "marker", marker: "stuck-header" });
+ items.push(...rowsOf(visibleStuckThreads, "stuck"));
+ }
if (snoozedThreads.length > 0) {
items.push({ kind: "marker", marker: "snoozed-header" });
items.push(...rowsOf(visibleSnoozedThreads, "snoozed"));
@@ -2193,9 +2255,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
dragState === null && sidebarListItems.length + visibleDraftSessionCount > 0;
// Cache on both fields so layout-key changes trigger the effect even when animate is unchanged.
const listMotionPass = { layoutKey: listMotionLayoutKey, animate: listMotionAnimate };
- const shelfExpansionKey = [workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded].join(
- ":",
- );
+ const shelfExpansionKey = [
+ workingShelfExpanded,
+ stuckShelfExpanded,
+ snoozedShelfExpanded,
+ settledShelfExpanded,
+ ].join(":");
const previousShelfExpansionKeyRef = useRef(shelfExpansionKey);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records moved rows and updates list motion after each layout-affecting commit
useLayoutEffect(() => {
@@ -3555,7 +3620,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
scopeThreadRef(thread.environmentId, thread.id),
);
const isCard =
- section === "active" || section === "pinned" || section === "working";
+ section === "active" ||
+ section === "pinned" ||
+ section === "working" ||
+ section === "stuck";
const rowVariant = folderRow
? folderRowsMultiline
? "folder-multiline"
@@ -3567,6 +3635,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
const key = scopedThreadKey(scopeThreadRef(row.environmentId, row.id));
return {
thread: row,
+ possiblyStuck: isShellPossiblyStuck(
+ row,
+ stuckClockOf(row.environmentId),
+ ),
// Steps follow their parent's section, so they offer no settle, snooze or pin of their own.
settlementSupported: !isStep && serverConfigs.has(row.environmentId),
snoozeSupported: !isStep && serverConfigs.has(row.environmentId),
@@ -3642,7 +3714,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
const isPipelineParent =
thread.pipeline != null && thread.pipeline.stepId === null;
const attention = isPipelineParent
- ? resolveSidebarPipelineAttention(liveRun, steps ?? EMPTY_THREADS)
+ ? resolveSidebarPipelineAttention(liveRun, steps ?? EMPTY_THREADS, waitOf)
: undefined;
const attemptInfo = pipelineAttemptsByParentKey.get(threadKey);
const stepRowProps = (step: EnvironmentThreadShell) => {
@@ -3672,6 +3744,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
navigationParent={
folderRow ??
(section === "working" ||
+ section === "stuck" ||
section === "snoozed" ||
section === "settled"
? `shelf:${section}`
@@ -3680,6 +3753,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
stepStatus={resolveSidebarPipelineStepStatus(
steps ?? EMPTY_THREADS,
liveRun,
+ waitOf,
)}
pipelineSteps={shownPipelineStepsByParentKey
.get(threadKey)
@@ -3697,7 +3771,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
pipelineEarlierIndex={attemptInfo?.currentShown}
pipelineProgress={
thread.pipeline != null && thread.pipeline.stepId === null
- ? resolveSidebarPipelineProgress(liveRun, steps ?? EMPTY_THREADS)
+ ? resolveSidebarPipelineProgress(
+ liveRun,
+ steps ?? EMPTY_THREADS,
+ waitOf,
+ )
: undefined
}
pipelineExpanded={expandedPipelines.has(threadKey)}
@@ -3805,12 +3883,29 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
/>,
);
break;
+ case "stuck-header":
+ items.push(
+ ,
+ );
+ break;
case "snoozed-header":
items.push(
);
}
- const segments = pipelineProgressSegments(summarizeRun(run), [], () => "ready").map(
- (segment, index) => ({
- stepId: segment.stepId,
- label: segment.label,
- status: segment.status,
- threadId: run.steps[index]?.childThreadId ?? null,
- }),
- );
+ // Only the current step's thread matters here: it waits on the user unless its own work holds it.
+ const segments = pipelineProgressSegments(
+ summarizeRun(run),
+ awaitingShell === null ? [] : [awaitingShell],
+ () => "ready",
+ waitOf,
+ ).map((segment, index) => ({
+ stepId: segment.stepId,
+ label: segment.label,
+ status: segment.status,
+ threadId: run.steps[index]?.childThreadId ?? null,
+ }));
const currentIndex = run.currentStepIndex;
const openThread = (target: ScopedThreadRef) =>
void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(target) });
@@ -105,7 +110,7 @@ export const PipelineCoordinatorPanel = memo(function PipelineCoordinatorPanel(p
}
>
Step {currentIndex + 1}/{run.steps.length} · {stepName(run, currentIndex)} ·{" "}
- {pipelineRunStateLabel(run, threadWatchesPullRequest(awaitingShell))}
+ {pipelineRunStateLabel(run, waitOf(awaitingShell))}
Open the run's main page
diff --git a/apps/web/src/components/chat/PipelineRunView.logic.test.ts b/apps/web/src/components/chat/PipelineRunView.logic.test.ts
index 48ea6187f43a7..5704145fdc472 100644
--- a/apps/web/src/components/chat/PipelineRunView.logic.test.ts
+++ b/apps/web/src/components/chat/PipelineRunView.logic.test.ts
@@ -40,20 +40,30 @@ describe("pipelineChildLiveState", () => {
describe("pipelineStepStatusDisplay", () => {
it("shows a step that waits on its watched pull request as waiting, not as attention", () => {
- expect(pipelineStepStatusDisplay({ status: "running" }, null, true, true)).toEqual({
+ expect(pipelineStepStatusDisplay({ status: "running" }, null, true, "pull_request")).toEqual({
label: "Waiting on pull request",
tone: "default",
});
- expect(pipelineStepStatusDisplay({ status: "running" }, null, true, false).tone).toBe(
+ expect(pipelineStepStatusDisplay({ status: "running" }, null, true, "background_work")).toEqual(
+ {
+ label: "Waiting on background work",
+ tone: "default",
+ },
+ );
+ expect(
+ pipelineStepStatusDisplay({ status: "running" }, "working", true, "possibly_stuck"),
+ ).toEqual({
+ label: "Possibly stuck",
+ tone: "attention",
+ });
+ expect(pipelineStepStatusDisplay({ status: "running" }, null, true, null).tone).toBe(
"attention",
);
});
it("reads a failed or stopped step a paused run waits at as attention", () => {
for (const status of ["failed", "cancelled"] as const) {
- expect(pipelineStepStatusDisplay({ status }, null, false, false, true).tone).toBe(
- "attention",
- );
+ expect(pipelineStepStatusDisplay({ status }, null, false, null, true).tone).toBe("attention");
expect(pipelineStepStatusDisplay({ status }, null).tone).toBe("default");
}
});
diff --git a/apps/web/src/components/chat/PipelineRunView.logic.ts b/apps/web/src/components/chat/PipelineRunView.logic.ts
index e4e0e88708188..977d9ac7c3311 100644
--- a/apps/web/src/components/chat/PipelineRunView.logic.ts
+++ b/apps/web/src/components/chat/PipelineRunView.logic.ts
@@ -1,7 +1,11 @@
import { formatModelSelectionEffort } from "@t3tools/client-runtime/state/thread-execution";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/models";
-import { pipelineStepStatusLabel } from "@t3tools/client-runtime/pipeline-run-presentation";
+import {
+ pipelineStepStatusLabel,
+ pipelineStepWaitLabel,
+} from "@t3tools/client-runtime/pipeline-run-presentation";
+import type { PipelineStepWait } from "@t3tools/client-runtime/state/pipeline-nesting";
import type { ModelSelection, PipelineRun, PipelineRunStep } from "@t3tools/contracts";
import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
@@ -70,19 +74,22 @@ export function pipelineStepStatusDisplay(
liveState: PipelineChildLiveState | null,
/** The run paused because this step ended its turn without handing off. */
awaitingHandoff = false,
- /** The step's thread watches a pull request, so it is waiting rather than stuck. */
- watchingPullRequest = false,
+ /** What the step's thread waits on, so it reads as waiting rather than needing the user. */
+ wait: PipelineStepWait | null = null,
/** The run is paused at this step: a failed or stopped one waits on the user. */
pausedAtStep = false,
): PipelineStepStatusDisplay {
+ if (step.status === "running" && awaitingHandoff && wait === "possibly_stuck") {
+ return { label: pipelineStepWaitLabel(wait), tone: "attention" };
+ }
if (step.status === "running" && liveState !== null) {
return {
label: PIPELINE_CHILD_LIVE_STATE_LABEL[liveState],
tone: liveState === "working" ? "working" : "attention",
};
}
- if (step.status === "running" && awaitingHandoff && watchingPullRequest) {
- return { label: "Waiting on pull request", tone: "default" };
+ if (step.status === "running" && awaitingHandoff && wait !== null) {
+ return { label: pipelineStepWaitLabel(wait), tone: "default" };
}
if (step.status === "running" && awaitingHandoff) {
return { label: "No handoff", tone: "attention" };
diff --git a/apps/web/src/components/chat/PipelineRunView.tsx b/apps/web/src/components/chat/PipelineRunView.tsx
index 303fc560dc6ee..7737c805817b0 100644
--- a/apps/web/src/components/chat/PipelineRunView.tsx
+++ b/apps/web/src/components/chat/PipelineRunView.tsx
@@ -9,7 +9,6 @@ import {
pipelineRunNeedsYou,
pipelineRunStatusLabel,
pipelineStepAwaitsHandoff,
- threadWatchesPullRequest,
stepName,
} from "@t3tools/client-runtime/pipeline-run-presentation";
import { pipelineRunStepShells } from "@t3tools/client-runtime/state/pipeline-nesting";
@@ -45,6 +44,7 @@ import { useState } from "react";
import { requestConfirmDialog } from "../../confirmDialog";
import { useClientSettings } from "../../hooks/useSettings";
+import { useStepWait } from "../../hooks/useStepWait";
import { deriveProviderInstanceEntries } from "../../providerInstances";
import { useEnvironmentQuery } from "../../state/query";
import { useQuietThreadShell, useQuietThreadShells } from "../../state/entities";
@@ -268,10 +268,13 @@ function PipelineRunBody(props: {
const actionsVisible = actions.continue || actions.retry || actions.skip || actions.cancel;
const shells = useQuietThreadShells();
+ const { waitOf, stuckAfterHours } = useStepWait(environmentId);
const needsYou = pipelineRunNeedsYou(
run,
pipelineRunStepShells(shells, environmentId, run.id),
resolveSidebarThreadStatus,
+ waitOf,
+ stuckAfterHours,
);
const needsYouThreadId = needsYou?.threadId ?? null;
return (
@@ -407,6 +410,7 @@ function PipelineRunBody(props: {
environmentId={environmentId}
run={run}
step={step}
+ waitOf={waitOf}
providerEntries={providerEntries}
cwd={props.cwd}
canTogglePauseBefore={
@@ -456,11 +460,13 @@ function useRunStatusLabel(environmentId: EnvironmentId, run: PipelineRun | null
const awaitingShell = useQuietThreadShell(
awaitingChildId === null ? null : scopeThreadRef(environmentId, awaitingChildId),
);
+ const { waitOf, stuckAfterHours } = useStepWait(environmentId);
if (run === null) return null;
return pipelineRunStatusLabel(
run,
feeding !== null && pipelineChildLiveState(shell) === "working",
- threadWatchesPullRequest(awaitingShell),
+ waitOf(awaitingShell),
+ stuckAfterHours,
);
}
@@ -468,6 +474,7 @@ function PipelineStepRow(props: {
readonly environmentId: EnvironmentId;
readonly run: PipelineRun;
readonly step: PipelineRunStep;
+ readonly waitOf: ReturnType["waitOf"];
readonly providerEntries: ReturnType;
readonly cwd: string | undefined;
readonly canTogglePauseBefore: boolean;
@@ -495,7 +502,7 @@ function PipelineStepRow(props: {
step,
liveState,
pipelineStepAwaitsHandoff(run, step.index),
- threadWatchesPullRequest(shell),
+ props.waitOf(shell),
isCurrent && run.status === "paused",
);
const childThreadId = step.childThreadId;
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 633e18a567b2f..b5f2e2b48a310 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -18,6 +18,7 @@ import {
import {
DEFAULT_UNIFIED_SETTINGS,
type DiffLayout,
+ MAX_POSSIBLY_STUCK_AFTER_HOURS,
MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
type ResponseStreamingMode,
@@ -506,6 +507,9 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.sidebarAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge
? ["Auto-settle merged threads"]
: []),
+ ...(settings.possiblyStuckAfterHours !== DEFAULT_UNIFIED_SETTINGS.possiblyStuckAfterHours
+ ? ["Mark threads as possibly stuck after"]
+ : []),
...(settings.autoResumeLimitedThreads !== DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads
? ["Resume after usage limits"]
: []),
@@ -680,6 +684,7 @@ export function useSettingsRestore(onRestored?: () => void) {
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays,
sidebarAutoSettleKeepPullRequests: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleKeepPullRequests,
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
+ possiblyStuckAfterHours: DEFAULT_UNIFIED_SETTINGS.possiblyStuckAfterHours,
autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads,
snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads,
snoozePresets: DEFAULT_UNIFIED_SETTINGS.snoozePresets,
@@ -731,6 +736,53 @@ export function useSettingsRestore(onRestored?: () => void) {
};
}
+/** Whole hours; 0 turns the indicator off. An invalid draft snaps back to the saved value. */
+function PossiblyStuckHoursInput({
+ value,
+ onCommit,
+}: {
+ value: number;
+ onCommit: (hours: number) => void;
+}) {
+ const [draft, setDraft] = useState(null);
+ const commit = () => {
+ if (draft === null) return;
+ const hours = Number(draft);
+ setDraft(null);
+ if (
+ draft.trim() !== "" &&
+ Number.isInteger(hours) &&
+ hours >= 0 &&
+ hours <= MAX_POSSIBLY_STUCK_AFTER_HOURS &&
+ hours !== value
+ ) {
+ onCommit(hours);
+ }
+ };
+ return (
+ setDraft(event.target.value)}
+ onBlur={commit}
+ onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing) return;
+ if (event.key === "Enter") commit();
+ if (event.key === "Escape" && draft !== null) {
+ event.preventDefault();
+ event.stopPropagation();
+ setDraft(null);
+ }
+ }}
+ aria-label="Hours before a thread is marked possibly stuck"
+ />
+ );
+}
+
const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 7;
function AutoSettleDaysInput({
@@ -1881,6 +1933,34 @@ export function ThreadsSettingsPanel() {
/>
+
+
+ updateSettings({
+ possiblyStuckAfterHours: DEFAULT_UNIFIED_SETTINGS.possiblyStuckAfterHours,
+ })
+ }
+ />
+ ) : null
+ }
+ control={
+ updateSettings({ possiblyStuckAfterHours: hours })}
+ />
+ }
+ />
+
+
{hasServerTargets ? (
, iconClassName: string) => (
+ shell === null ? null : threadBackgroundWait(shell, clock),
+ };
+}
diff --git a/docs/user/pipelines.md b/docs/user/pipelines.md
index b39756b7129c7..6d1c660d5a363 100644
--- a/docs/user/pipelines.md
+++ b/docs/user/pipelines.md
@@ -81,10 +81,21 @@ and the step shows **No handoff**. Answer in the step's thread; when the agent t
run continues on its own. **Continue with last message** moves on with the thread's latest answer
instead.
+A step that ends its turn while its thread still has background work, such as a dev server, a
+monitor, a background task, a subagent or a pull request watch, is waiting on that work, not on you.
+The run shows **Waiting on background work** instead of **No handoff** and does not ask for your
+attention; **Continue with last message** stays available. When the work ends, the agent normally
+wakes and hands off. If it ends its turn again without handing off and nothing is running, the run
+shows **No handoff** as above.
+
A step that waits on checks, reviews or a merge watches its pull request and ends its turn; the run
-then shows **Waiting on pull request** instead of **No handoff**. The watch ends when the step
-hands off or stops being the run's current step, and when the pull request merges; the merge wakes the
-step, so a repository that merges through a queue needs no one to confirm it.
+then shows **Waiting on pull request**. The watch ends when the step hands off or stops being the
+run's current step, and when the pull request merges; the merge wakes the step, so a repository that
+merges through a queue needs no one to confirm it.
+
+If background work, other than a pull request watch, keeps running for hours after the step's last
+turn ended, the step shows **Possibly stuck** and the run asks for your attention. See
+[Find threads that may be stuck](thread-sidebar.md#find-threads-that-may-be-stuck).
If a step's turn fails or you stop it, the run pauses and the step shows **Failed** or **Stopped**.
Fix the cause and ask the agent to go on in the step's thread; when it hands off, the run continues
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 905f3a5bfbe9c..a1a26b1f8545d 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -148,6 +148,19 @@ choice.
While this is on, the active list is ordered by when each thread last came back to you, so you
cannot drag or move threads within it. Your saved order returns when you turn it off.
+### Find threads that may be stuck
+
+A thread whose last turn ended while background work kept running, such as a dev server, a monitor,
+a background task or a subagent, shows **Possibly stuck** once that work has run longer than a set
+time. These threads move into a collapsed **Possibly stuck** section below the Working section.
+Watched pull requests never count, because they wait on people or checks by design. The mark clears
+when the work ends, when the thread starts a new turn, or when you archive it. Stop the work or send a
+message to clear it sooner. A pipeline step marked this way also needs your attention.
+
+Set the time with **Settings → Threads → Mark threads as possibly stuck after** on web and desktop,
+or **Settings → Threads** on iOS and Android. The default is 2 hours, and 0 turns it off. The
+setting belongs to the environment, so every device connected to it agrees.
+
### Group threads by project (beta)
Turn on **Settings → Labs → Boring sidebar (group by project)** on web and desktop to put active
diff --git a/packages/client-runtime/src/clock.test.ts b/packages/client-runtime/src/clock.test.ts
index 1f45860addf7c..9fb3ecf409b62 100644
--- a/packages/client-runtime/src/clock.test.ts
+++ b/packages/client-runtime/src/clock.test.ts
@@ -1,6 +1,12 @@
import { EnvironmentId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
-import { deadlineStore, recordServerClock, secondTick, toServerClock } from "./clock.ts";
+import {
+ deadlineStore,
+ minuteTickToEpochMs,
+ recordServerClock,
+ secondTick,
+ toServerClock,
+} from "./clock.ts";
describe("deadlineStore", () => {
afterEach(() => {
@@ -173,3 +179,19 @@ describe("server clock", () => {
expect(toServerClock(environmentId, 12_345)).toBe(12_345);
});
});
+
+describe("minuteTickToEpochMs", () => {
+ // Forked test workers (the default pool) apply a changed TZ to later Date calls.
+ it("reads the minute tick as UTC whatever the local timezone", () => {
+ const zone = process.env.TZ;
+ try {
+ for (const tz of ["America/Los_Angeles", "Europe/Berlin", "UTC"]) {
+ process.env.TZ = tz;
+ expect(minuteTickToEpochMs("2026-10-26T02:14")).toBe(Date.UTC(2026, 9, 26, 2, 14));
+ }
+ } finally {
+ if (zone === undefined) delete process.env.TZ;
+ else process.env.TZ = zone;
+ }
+ });
+});
diff --git a/packages/client-runtime/src/clock.ts b/packages/client-runtime/src/clock.ts
index f8f1290730084..439c6d73fe876 100644
--- a/packages/client-runtime/src/clock.ts
+++ b/packages/client-runtime/src/clock.ts
@@ -72,6 +72,14 @@ export const minuteTick: ClockStore = makeTickStore(
60_000,
);
+/**
+ * `minuteTick`'s UTC `YYYY-MM-DDTHH:mm` as epoch ms. The snapshot carries no
+ * offset, and `Date.parse` reads offset-less date-times as local time.
+ */
+export function minuteTickToEpochMs(minute: string): number {
+ return Date.parse(`${minute}:00Z`);
+}
+
// How far each environment's clock runs ahead of this one. Timers read it on
// every tick, so a reconnect's new reading lands without a re-render.
const serverClockOffsets = new Map();
diff --git a/packages/client-runtime/src/pipelineRunPresentation.test.ts b/packages/client-runtime/src/pipelineRunPresentation.test.ts
index bfdf1a1ed6b2c..e04744b511b0b 100644
--- a/packages/client-runtime/src/pipelineRunPresentation.test.ts
+++ b/packages/client-runtime/src/pipelineRunPresentation.test.ts
@@ -20,7 +20,6 @@ import {
pipelineStepPosition,
pipelineRunNeedsAttention,
pipelineRunNeedsYou,
- threadWatchesPullRequest,
} from "./pipelineRunPresentation.ts";
const NAMES = ["Plan", "Implement", "Review"] as const;
@@ -290,28 +289,81 @@ describe("missing handoff", () => {
]);
});
- it("reads a step that watches its pull request as waiting, not as needing attention", () => {
+ it("reads a step waiting on background work, or stuck on it, by its wait", () => {
const run = makeRun({
status: "paused",
pauseReason: "awaiting_handoff",
currentStepIndex: 1,
stepStatuses: ["completed", "running", "pending"],
});
- expect(pipelineRunStatusLabel(run, false, true)).toBe("Implement is waiting on a pull request");
- expect(pipelineRunStateLabel(run, true)).toBe("Waiting on pull request");
- expect(pipelineRunNeedsAttention(run, true)).toBe(false);
- expect(pipelineRunNeedsAttention(run, false)).toBe(true);
- expect(pipelineRunNeedsAttention({ ...run, pauseReason: "step_failed" }, true)).toBe(true);
- const watch = { startedAt: "now" };
- const link = { source: "agent" as const, snapshot: null };
- expect(threadWatchesPullRequest({ pullRequests: [link, { ...link, watch }] })).toBe(true);
- // A merged pull request's watch holds nothing, as the sidebar's busy state reads it.
+ expect(pipelineRunStatusLabel(run, false, "background_work")).toBe(
+ "Implement is waiting on background work",
+ );
+ expect(pipelineRunStateLabel(run, "background_work")).toBe("Background work");
+ expect(pipelineRunStatusLabel(run, false, "possibly_stuck", 2)).toBe(
+ "Implement may be stuck: background work has run for over 2 h",
+ );
+ expect(pipelineRunStateLabel(run, "possibly_stuck")).toBe("Possibly stuck");
+ expect(pipelineRunNeedsAttention(run, "background_work")).toBe(false);
+ expect(pipelineRunNeedsAttention(run, "possibly_stuck")).toBe(true);
expect(
- threadWatchesPullRequest({
- pullRequests: [{ ...link, watch, snapshot: { state: "merged" as const } }],
- }),
- ).toBe(false);
- expect(threadWatchesPullRequest(null)).toBe(false);
+ pipelineRunNeedsAttention({ ...run, pauseReason: "step_failed" }, "background_work"),
+ ).toBe(true);
+ });
+
+ it("leads the overview with the step's wait instead of 'ended without handing off'", () => {
+ const run = makeRun({
+ status: "paused",
+ pauseReason: "awaiting_handoff",
+ currentStepIndex: 1,
+ stepStatuses: ["completed", "running", "pending"],
+ });
+ const steps = [
+ {
+ id: ThreadId.make("child-1"),
+ environmentId: "env" as never,
+ createdAt: "2026-01-01T00:00:00Z",
+ title: "Pipeline · Implement",
+ pipeline: { runId: "r", stepId: "step-1" },
+ },
+ ];
+ const withChild: PipelineRun = {
+ ...run,
+ steps: run.steps.map((entry) =>
+ entry.index === 1 ? { ...entry, childThreadId: steps[0]!.id } : entry,
+ ),
+ };
+ const needsYou = (wait: "background_work" | "possibly_stuck" | null) =>
+ pipelineRunNeedsYou(
+ withChild,
+ steps,
+ () => "ready",
+ () => wait,
+ 2,
+ )?.text ?? null;
+ expect(needsYou(null)).toBe("Implement ended without handing off");
+ expect(needsYou("background_work")).toBeNull();
+ expect(needsYou("possibly_stuck")).toBe(
+ "Implement may be stuck: background work has run for over 2 h",
+ );
+ });
+
+ it("reads a step that watches its pull request as waiting, not as needing attention", () => {
+ const run = makeRun({
+ status: "paused",
+ pauseReason: "awaiting_handoff",
+ currentStepIndex: 1,
+ stepStatuses: ["completed", "running", "pending"],
+ });
+ expect(pipelineRunStatusLabel(run, false, "pull_request")).toBe(
+ "Implement is waiting on a pull request",
+ );
+ expect(pipelineRunStateLabel(run, "pull_request")).toBe("Waiting on pull request");
+ expect(pipelineRunNeedsAttention(run, "pull_request")).toBe(false);
+ expect(pipelineRunNeedsAttention(run, null)).toBe(true);
+ expect(pipelineRunNeedsAttention({ ...run, pauseReason: "step_failed" }, "pull_request")).toBe(
+ true,
+ );
});
});
diff --git a/packages/client-runtime/src/pipelineRunPresentation.ts b/packages/client-runtime/src/pipelineRunPresentation.ts
index a2c0992395ccb..6ace36c3aad6e 100644
--- a/packages/client-runtime/src/pipelineRunPresentation.ts
+++ b/packages/client-runtime/src/pipelineRunPresentation.ts
@@ -1,6 +1,10 @@
import type { PipelineRun, PipelineRunStep, ThreadId } from "@t3tools/contracts";
-import { pullRequestWatchHoldsThread } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
-import { pipelineAttentionTargets, type PipelineNestable } from "./state/pipelineNesting.ts";
+import {
+ pipelineAttentionTargets,
+ type PipelineNestable,
+ type PipelineStepWait,
+ type PipelineStepWaitOf,
+} from "./state/pipelineNesting.ts";
import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
import { compactDynamicToolOutput } from "@t3tools/shared/toolOutput";
@@ -76,29 +80,39 @@ export function pipelineStepAwaitsHandoff(
);
}
-/** Whether a thread waits on a pull request watch, by the rule the sidebar's busy state uses. */
-export function threadWatchesPullRequest(
- shell: {
- readonly pullRequests?: ReadonlyArray[0]>;
- } | null,
-): boolean {
- return shell?.pullRequests?.some(pullRequestWatchHoldsThread) ?? false;
-}
-
/** The thread of the current step when the run waits for its handoff, else null. */
export function pipelineAwaitingHandoffThreadId(run: PipelineRun | null) {
if (run === null || !pipelineStepAwaitsHandoff(run, run.currentStepIndex)) return null;
return run.steps[run.currentStepIndex]?.childThreadId ?? null;
}
+/** A step row's status while its thread waits after ending its turn without a handoff. */
+export function pipelineStepWaitLabel(wait: PipelineStepWait): string {
+ switch (wait) {
+ case "pull_request":
+ return "Waiting on pull request";
+ case "background_work":
+ return "Waiting on background work";
+ case "possibly_stuck":
+ return "Possibly stuck";
+ }
+}
+
+/** How long a step may wait on background work before the label calls it stuck. */
+function stuckAfterText(hours: number | undefined): string {
+ return hours === undefined ? "a long time" : `over ${hours} h`;
+}
+
/**
* `feedingActive`: the step before a still-pending current step is still working.
- * `waitingOnPullRequest`: the current step's thread watches a pull request.
+ * `wait`: what the current step's thread is waiting on after its turn ended without a handoff.
+ * `stuckAfterHours`: the threshold behind a `possibly_stuck` wait.
*/
export function pipelineRunStatusLabel(
run: PipelineRun,
feedingActive = false,
- waitingOnPullRequest = false,
+ wait: PipelineStepWait | null = null,
+ stuckAfterHours?: number,
): string {
const name = stepName(run, run.currentStepIndex);
switch (run.status) {
@@ -112,9 +126,16 @@ export function pipelineRunStatusLabel(
case "awaiting_continue":
return `Paused before ${name}`;
case "awaiting_handoff":
- return waitingOnPullRequest
- ? `${name} is waiting on a pull request`
- : `${name} ended without handing off`;
+ switch (wait) {
+ case "pull_request":
+ return `${name} is waiting on a pull request`;
+ case "background_work":
+ return `${name} is waiting on background work`;
+ case "possibly_stuck":
+ return `${name} may be stuck: background work has run for ${stuckAfterText(stuckAfterHours)}`;
+ default:
+ return `${name} ended without handing off`;
+ }
case "step_failed":
return `Step ${name} failed`;
case "step_stopped":
@@ -134,7 +155,7 @@ export function pipelineRunStatusLabel(
/** The run's state without a step name, for headers that already show the current step. */
export function pipelineRunStateLabel(
run: Pick,
- waitingOnPullRequest = false,
+ wait: PipelineStepWait | null = null,
): string {
switch (run.status) {
case "running":
@@ -142,7 +163,13 @@ export function pipelineRunStateLabel(
case "paused":
switch (run.pauseReason) {
case "awaiting_handoff":
- return waitingOnPullRequest ? "Waiting on pull request" : "No handoff";
+ return wait === "pull_request"
+ ? "Waiting on pull request"
+ : wait === "background_work"
+ ? "Background work"
+ : wait === "possibly_stuck"
+ ? "Possibly stuck"
+ : "No handoff";
case "step_failed":
return "Failed";
case "step_stopped":
@@ -358,13 +385,16 @@ export function createPipelineEscalationWatcher() {
};
}
-/** A paused run's step is not stuck when its thread is watching a pull request. */
+/** A paused run's step waits on its own work, not the user, until that work looks stuck. */
export function pipelineRunNeedsAttention(
run: Pick,
- waitingOnPullRequest: boolean,
+ wait: PipelineStepWait | null,
): boolean {
if (run.status !== "paused") return false;
- return !(run.pauseReason === "awaiting_handoff" && waitingOnPullRequest);
+ return !(
+ run.pauseReason === "awaiting_handoff" &&
+ (wait === "pull_request" || wait === "background_work")
+ );
}
export interface PipelineNeedsYou {
@@ -384,6 +414,8 @@ export function pipelineRunNeedsYou string,
+ waitOf?: PipelineStepWaitOf,
+ stuckAfterHours?: number,
): PipelineNeedsYou | null {
const { target } = pipelineAttentionTargets(
{
@@ -399,6 +431,7 @@ export function pipelineRunNeedsYou {
});
});
+describe("threadBackgroundWait", () => {
+ const HOUR = 3_600_000;
+ const completedAt = "1970-01-01T00:00:00.000Z";
+ const ended = (tasks: ReadonlyArray<{ taskId: string }>, activeRunId: string | null = null) => ({
+ pendingBackgroundTasks: tasks,
+ runtime: { activeRunId },
+ latestRun: { completedAt },
+ });
+ const dev = { taskId: "dev" };
+ const watch = { taskId: "pull-request-watch:github.com/o/r#1" };
+ const clock = (hours: number) => ({ nowMs: hours * HOUR, afterHours: 2 });
+
+ it.each([
+ ["no pending work", ended([]), clock(9), null],
+ ["a dev server", ended([dev]), clock(1), "background_work"],
+ ["a pull request watch alone", ended([watch]), clock(9), "pull_request"],
+ ["a watch beside a dev server", ended([watch, dev]), clock(1), "background_work"],
+ ["a dev server past the threshold", ended([dev]), clock(3), "possibly_stuck"],
+ [
+ "a dev server with the check off",
+ ended([dev]),
+ { nowMs: 9 * HOUR, afterHours: 0 },
+ "background_work",
+ ],
+ ["a dev server with no clock yet", ended([dev]), undefined, "background_work"],
+ ["a dev server in a running turn", ended([dev], "run-1"), clock(9), "background_work"],
+ [
+ "an archived thread past the threshold",
+ { ...ended([dev]), archivedAt: completedAt },
+ clock(9),
+ "background_work",
+ ],
+ [
+ "a thread with no finished run",
+ { ...ended([dev]), latestRun: { completedAt: null } },
+ clock(9),
+ "background_work",
+ ],
+ ["a thread that is not loaded", null, clock(9), null],
+ ] as const)("reads %s as %s", (_case, shell, stuck, expected) => {
+ expect(threadBackgroundWait(shell, stuck)).toBe(expected);
+ });
+});
+
+describe("a paused run waiting on its step's background work", () => {
+ const waitOn =
+ (waits: Record) =>
+ (s: { id: string }): PipelineStepWait | null =>
+ waits[s.id] ?? null;
+ const steps = [{ ...step("s0", "r1", "step-0", "2026-01-01T00:01:00Z"), title: "Run · Build" }];
+ const run = (pauseReason: "awaiting_handoff" | "step_failed") =>
+ ({
+ status: "paused",
+ pauseReason,
+ currentStepIndex: 0,
+ steps: [{ stepId: "step-0", name: "Build", status: "running", childThreadId: "s0" }],
+ }) as unknown as PipelineRunSummary;
+ const ready = () => "ready";
+
+ it.each([
+ { wait: null, status: "input" },
+ { wait: "pull_request", status: null },
+ { wait: "background_work", status: null },
+ { wait: "possibly_stuck", status: "stuck" },
+ ] as const)("with wait $wait, the parent reads $status", ({ wait, status }) => {
+ const waitOf = waitOn(wait === null ? {} : { s0: wait });
+ const awaiting = run("awaiting_handoff");
+ expect(aggregatePipelineStepStatus(steps, ready, awaiting, waitOf)).toBe(status);
+ const [segment] = pipelineProgressSegments(awaiting, steps, ready, waitOf);
+ expect(segment?.status).toBe(status === null ? "running" : "attention");
+ const targets = pipelineAttentionTargets(awaiting, steps, ready, waitOf);
+ expect(targets.target !== null).toBe(status !== null);
+ expect([...targets.attentionThreads.values()][0] ?? null).toBe(status);
+ });
+
+ it.each(["background_work", "possibly_stuck"] as const)(
+ "still needs the user for a failed step whose thread waits on %s",
+ (wait) => {
+ const failed = run("step_failed");
+ const waitOf = waitOn({ s0: wait });
+ expect(aggregatePipelineStepStatus(steps, ready, failed, waitOf)).toBe("input");
+ const targets = pipelineAttentionTargets(failed, steps, ready, waitOf);
+ expect([...targets.attentionThreads.values()]).toEqual(["input"]);
+ },
+ );
+
+ it("rolls a possibly stuck current step up even when the run is not paused", () => {
+ const running = { ...run("awaiting_handoff"), status: "running" } as PipelineRunSummary;
+ expect(
+ aggregatePipelineStepStatus(steps, ready, running, waitOn({ s0: "possibly_stuck" })),
+ ).toBe("stuck");
+ });
+
+ it("rolls up any stuck step once the run is over", () => {
+ expect(
+ aggregatePipelineStepStatus(steps, ready, undefined, waitOn({ s0: "possibly_stuck" })),
+ ).toBe("stuck");
+ });
+
+ it("ignores work an earlier step left running", () => {
+ const earlier = {
+ ...step("old", "r1", "step-old", "2026-01-01T00:00:30Z"),
+ title: "Run · Plan",
+ };
+ const running = { ...run("awaiting_handoff"), status: "running" } as PipelineRunSummary;
+ expect(
+ aggregatePipelineStepStatus(
+ [earlier, ...steps],
+ (s) => (s.id === "s0" ? "working" : "ready"),
+ running,
+ waitOn({ old: "possibly_stuck" }),
+ ),
+ ).toBe("working");
+ });
+});
+
describe("isPipelineGroupActive", () => {
const shells = [
parent("p", "r1"),
diff --git a/packages/client-runtime/src/state/pipelineNesting.ts b/packages/client-runtime/src/state/pipelineNesting.ts
index 7c5e947c5ec9c..42920161d3e4e 100644
--- a/packages/client-runtime/src/state/pipelineNesting.ts
+++ b/packages/client-runtime/src/state/pipelineNesting.ts
@@ -1,5 +1,12 @@
import type { EnvironmentId, PipelineRunSummary, ThreadId } from "@t3tools/contracts";
+import {
+ classifyBackgroundWait,
+ type BackgroundWait,
+ type PendingBackgroundWorkTask,
+ type PossiblyStuckClock,
+} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
+
import { scopedThreadKey, scopeThreadRef } from "../environment/scoped.ts";
/** The shell fields pipeline nesting reads; `EnvironmentThreadShell` satisfies it. */
@@ -96,7 +103,74 @@ export function livePipelineRunOf(
: runs?.get(runKey(shell.environmentId, shell.pipeline.runId));
}
-type PausedRunInput = Pick;
+type PausedRunInput = Pick<
+ PipelineRunSummary,
+ "status" | "currentStepIndex" | "steps" | "pauseReason"
+>;
+
+/**
+ * What a step thread's background work means for a run paused at its handoff: waiting on a pull
+ * request alone, on other background work, or that work has run so long the step may be stuck.
+ */
+export type PipelineStepWait = BackgroundWait;
+
+export type PipelineStepWaitOf = (step: T) => PipelineStepWait | null;
+
+export type { PossiblyStuckClock };
+
+/** An environment's staleness inputs; none until its settings load, so nothing flashes stuck. */
+export function possiblyStuckClock(
+ settings: { readonly possiblyStuckAfterHours: number } | null | undefined,
+ nowMs: number,
+): PossiblyStuckClock | undefined {
+ return settings == null ? undefined : { nowMs, afterHours: settings.possiblyStuckAfterHours };
+}
+
+interface BackgroundWaitShell {
+ readonly pendingBackgroundTasks?: ReadonlyArray>;
+ readonly runtime?: { readonly activeRunId: unknown } | null;
+ readonly latestRun?: { readonly completedAt: string | null } | null;
+ readonly archivedAt?: string | null;
+}
+
+function stuckCheckThread(shell: BackgroundWaitShell) {
+ const completedAtMs = Date.parse(shell.latestRun?.completedAt ?? "");
+ return {
+ activeRunId: shell.runtime?.activeRunId,
+ archived: shell.archivedAt != null,
+ pendingBackgroundTasks: shell.pendingBackgroundTasks,
+ lastRunEndedAtMs: Number.isNaN(completedAtMs) ? null : completedAtMs,
+ };
+}
+
+/** Whether a thread with no active run has background work that has run past the threshold. */
+export function isShellPossiblyStuck(
+ shell: BackgroundWaitShell | null | undefined,
+ stuck: PossiblyStuckClock | undefined,
+): boolean {
+ return threadBackgroundWait(shell, stuck) === "possibly_stuck";
+}
+
+/** The one rule every surface shares for a step thread that ended its turn with work still pending. */
+export function threadBackgroundWait(
+ shell: BackgroundWaitShell | null | undefined,
+ stuck?: PossiblyStuckClock,
+): PipelineStepWait | null {
+ if (shell == null || (shell.pendingBackgroundTasks ?? []).length === 0) return null;
+ return classifyBackgroundWait(stuckCheckThread(shell), stuck);
+}
+
+/** A paused handoff's step that is still waiting on its own work is not waiting on the user. */
+function pausedStepIsBusy(
+ run: Pick,
+ step: T,
+ threadStatus: (step: T) => string,
+ waitOf: PipelineStepWaitOf | undefined,
+): boolean {
+ const wait = run.pauseReason === "awaiting_handoff" ? (waitOf?.(step) ?? null) : null;
+ if (wait === "possibly_stuck") return false;
+ return wait !== null || BUSY_THREAD_STATUSES.has(threadStatus(step));
+}
/**
* The thread of a paused run's current step, if it has one. A run paused
@@ -110,6 +184,23 @@ function pausedRunCurrentStep(
return childThreadId == null ? undefined : steps.find((step) => step.id === childThreadId);
}
+/**
+ * Whether a pipeline holds a step whose background work ran past the user's threshold. A live run
+ * counts only its current step, and not while paused for another reason (a failure, a gate), so
+ * work an earlier step left running does not hold the run. A run that is over counts any step.
+ */
+export function pipelineHasStuckStep(
+ run: PausedRunInput | null | undefined,
+ steps: readonly T[],
+ waitOf: PipelineStepWaitOf | undefined,
+): boolean {
+ if (waitOf === undefined) return false;
+ if (run == null) return steps.some((step) => waitOf(step) === "possibly_stuck");
+ if (run.status === "paused" && run.pauseReason !== "awaiting_handoff") return false;
+ const current = pausedRunCurrentStep(run, steps);
+ return current !== undefined && waitOf(current) === "possibly_stuck";
+}
+
/**
* Whether a paused run waits on the user. It does unless its current step is
* busy again: a step can keep working or monitoring after its turn ended
@@ -220,7 +311,7 @@ export function pipelineStepLabel(
return name === undefined || name === "" ? nestedPipelineStepLabel(step.title) : name;
}
-const URGENT_STEP_STATUSES = ["approval", "input", "request", "working"] as const;
+const URGENT_STEP_STATUSES = ["approval", "input", "request", "stuck", "working"] as const;
export type PipelineStepStatus = (typeof URGENT_STEP_STATUSES)[number];
/** Thread statuses of a step that is still running or monitoring, so nothing waits on the user. */
@@ -229,17 +320,20 @@ const BUSY_THREAD_STATUSES: ReadonlySet = new Set(["working", "waiting"]
/**
* The most urgent status among a pipeline's steps (needs you before running), or null. A paused
* run counts as `input` while it waits on the user: on Continue, a handoff, or a failed or
- * stopped step. Once its current step is busy again, the step's own status shows.
+ * stopped step. Once its current step is busy again, the step's own status shows. Only the
+ * current step reads as `stuck`: work an earlier step left running does not hold the run.
*/
export function aggregatePipelineStepStatus(
steps: readonly T[],
threadStatus: (step: T) => string,
run?: PausedRunInput | null,
+ waitOf?: PipelineStepWaitOf,
): PipelineStepStatus | null {
- const seen = new Set(steps.map(threadStatus));
- if (
+ const seen = new Set(steps.map(threadStatus));
+ if (pipelineHasStuckStep(run, steps, waitOf)) seen.add("stuck");
+ else if (
run?.status === "paused" &&
- pausedRunWaitsOnUser(run, steps, (step) => BUSY_THREAD_STATUSES.has(threadStatus(step)))
+ pausedRunWaitsOnUser(run, steps, (step) => pausedStepIsBusy(run, step, threadStatus, waitOf))
) {
seen.add("input");
}
@@ -291,6 +385,7 @@ export function pipelineProgressSegments string,
+ waitOf?: PipelineStepWaitOf,
): readonly PipelineProgressSegment[] {
// Steps arrive oldest first, so the last thread per step is its latest attempt.
const latestByStepId = new Map();
@@ -315,7 +410,7 @@ export function pipelineProgressSegments;
export function isPipelineAttentionStatus(
status: string | null,
): status is PipelineAttentionStatus {
- return status !== null && ATTENTION_THREAD_STATUSES.has(status);
+ return status !== null && (status === "stuck" || ATTENTION_THREAD_STATUSES.has(status));
}
/** What a step waiting on the user wants, for " needs your …". */
export function pipelineAttentionNoun(status: PipelineAttentionStatus): string {
- return status === "approval" ? "approval" : status === "request" ? "response" : "input";
+ return status === "approval"
+ ? "approval"
+ : status === "request"
+ ? "response"
+ : status === "stuck"
+ ? "attention"
+ : "input";
}
export interface PipelineAttentionTargets {
@@ -372,11 +473,12 @@ export function pipelineAttentionTargets) | undefined,
steps: readonly T[],
threadStatus: (step: T) => string,
+ waitOf?: PipelineStepWaitOf,
): PipelineAttentionTargets {
const attentionThreads = new Map();
let current: T | null = null;
let first: T | null = null;
- pipelineProgressSegments(run, steps, threadStatus).forEach((segment, index) => {
+ pipelineProgressSegments(run, steps, threadStatus, waitOf).forEach((segment, index) => {
const thread = segment.thread;
if (thread === null) return;
const own = threadStatus(thread);
@@ -385,9 +487,16 @@ export function pipelineAttentionTargets {
});
});
+describe("isThreadPossiblyStuck", () => {
+ const HOUR = 3_600_000;
+ const now = 10 * HOUR;
+ const dev = { taskId: "dev" };
+ const watch = { taskId: "pull-request-watch:github.com/o/r#1" };
+ const stuck = { activeRunId: null, pendingBackgroundTasks: [dev], lastRunEndedAtMs: 0 };
+
+ it.each([
+ ["past the threshold", stuck, 2, true],
+ ["exactly at the threshold", { ...stuck, lastRunEndedAtMs: now - 2 * HOUR }, 2, false],
+ ["just past the threshold", { ...stuck, lastRunEndedAtMs: now - 2 * HOUR - 1 }, 2, true],
+ [
+ "a later wake turn restarting the clock",
+ { ...stuck, lastRunEndedAtMs: now - HOUR },
+ 2,
+ false,
+ ],
+ ["only a pull request watch", { ...stuck, pendingBackgroundTasks: [watch] }, 2, false],
+ ["a watch beside other work", { ...stuck, pendingBackgroundTasks: [watch, dev] }, 2, true],
+ ["no background work", { ...stuck, pendingBackgroundTasks: [] }, 2, false],
+ ["an active run", { ...stuck, activeRunId: "run-1" }, 2, false],
+ ["an archived thread", { ...stuck, archived: true }, 2, false],
+ ["no finished run to date it", { ...stuck, lastRunEndedAtMs: null }, 2, false],
+ ["the indicator turned off", stuck, 0, false],
+ ] as const)("with %s: %s", (_case, thread, afterHours, expected) => {
+ expect(isThreadPossiblyStuck(thread, now, afterHours)).toBe(expected);
+ });
+});
+
describe("derivePendingBackgroundWork", () => {
it("takes each subagent item's instance from its joined owner", () => {
const owner = ProviderInstanceId.make("claude-owner");
diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts
index 192142e2665a3..65517d35b2f3e 100644
--- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts
@@ -311,7 +311,7 @@ export function derivePendingBackgroundWork(input: {
}
/** Whether a link's watch still holds its thread open as pending work. */
-export function pullRequestWatchHoldsThread(
+function pullRequestWatchHoldsThread(
link: Pick & {
readonly watch?: unknown;
},
@@ -343,3 +343,60 @@ function pullRequestWatchTasks(
],
);
}
+
+const MS_PER_HOUR = 3_600_000;
+
+/** Pending work other than pull request watches, which wait on people or CI by design. */
+const hasStaleableBackgroundWork = (
+ tasks: ReadonlyArray> | undefined,
+): boolean => (tasks ?? []).some((task) => !isPullRequestWatchTask(task));
+
+interface StuckCheckThread {
+ readonly activeRunId: unknown;
+ readonly archived?: boolean;
+ readonly pendingBackgroundTasks:
+ | ReadonlyArray>
+ | undefined;
+ readonly lastRunEndedAtMs: number | null;
+}
+
+/** The staleness inputs: a shared coarse clock and the user's threshold (0 = off). */
+export interface PossiblyStuckClock {
+ readonly nowMs: number;
+ readonly afterHours: number;
+}
+
+/**
+ * Whether a thread's last turn ended and its background work has run past `afterHours` since.
+ * `afterHours` of 0 turns the check off. A wake turn moves `lastRunEndedAtMs`, so it restarts the clock.
+ */
+export function isThreadPossiblyStuck(
+ thread: StuckCheckThread,
+ nowMs: number,
+ afterHours: number,
+): boolean {
+ if (!(afterHours > 0) || thread.activeRunId != null || thread.archived === true) return false;
+ if (thread.lastRunEndedAtMs === null || !Number.isFinite(thread.lastRunEndedAtMs)) return false;
+ return (
+ hasStaleableBackgroundWork(thread.pendingBackgroundTasks) &&
+ nowMs - thread.lastRunEndedAtMs > afterHours * MS_PER_HOUR
+ );
+}
+
+/**
+ * What a thread whose turn ended still waits on: a pull request watch alone, other background
+ * work, or work that ran so long the thread may be stuck. Without a clock nothing reads as stuck.
+ */
+export type BackgroundWait = "pull_request" | "background_work" | "possibly_stuck";
+
+export function classifyBackgroundWait(
+ thread: StuckCheckThread,
+ clock: PossiblyStuckClock | undefined,
+): BackgroundWait | null {
+ const tasks = thread.pendingBackgroundTasks ?? [];
+ if (tasks.length === 0) return null;
+ if (clock !== undefined && isThreadPossiblyStuck(thread, clock.nowMs, clock.afterHours)) {
+ return "possibly_stuck";
+ }
+ return tasks.every(isPullRequestWatchTask) ? "pull_request" : "background_work";
+}