Open History to see the last commit
1/**
2 * ThreadBackgroundLivenessService - in-memory per-thread background liveness
3 * for the sidebar status pill.
4 *
5 * The turn can settle while native background work runs on (subagent fleets,
6 * workflow runs, Monitor watch loops); the shell previously showed nothing.
7 * Ingestion records task lifecycle transitions and the shell query reads the
8 * derived state at mapping time — no persistence, no migration. After a
9 * server restart the registry is empty until new task events arrive, which
10 * matches reality: orphaned background work is not live.
11 *
12 * "monitoring" is reserved for watch loops (monitor tasks and background
13 * shells) when they are the ONLY live work; any agent work presents as
14 * "working".
15 *
16 * @module ThreadBackgroundLivenessService
17 */
18import { INERT_TASK_TYPES, MONITOR_TASK_TYPES } from "@t3tools/contracts";
19import * as Context from "effect/Context";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22
23export type ThreadBackgroundLiveness = "working" | "monitoring" | null;
24
25interface ThreadLivenessState {
26 readonly agents: Set<string>;
27 readonly monitors: Set<string>;
28}
29
30// Classification sets are the shared contracts copies (MONITOR_TASK_TYPES:
31// watch loops — monitor tasks plus background shells, which in practice are
32// PR babysitting/log tails since pacing sleeps complete inside the turn;
33// INERT_TASK_TYPES: plan-mode bookkeeping) so this registry, ingestion's
34// agentKind stamp, and the client fold can never drift apart.
35
36const TERMINAL_STATUSES: ReadonlySet<string> = new Set([
37 "completed",
38 "failed",
39 "stopped",
40 "cancelled",
41 "interrupted",
42]);
43
44export class ThreadBackgroundLivenessService extends Context.Service<
45 ThreadBackgroundLivenessService,
46 {
47 /**
48 * Feed one task lifecycle transition. taskType may be absent on
49 * synthesized rows (workflow members, Codex children) — those count as
50 * agents. agentId marks a task launched from inside a subagent: its
51 * internal shells are covered by the owning agent's liveness, but a
52 * NESTED AGENT (agentId + agent-flavored taskType) still counts — it
53 * can outlive its parent and must keep the thread Working.
54 */
55 readonly recordTaskLiveness: (input: {
56 readonly threadId: string;
57 readonly taskId: string;
58 readonly taskType: string | undefined;
59 readonly status: string | undefined;
60 readonly kind: "started" | "progress" | "updated" | "completed";
61 readonly agentId?: string | undefined;
62 }) => void;
63
64 /** Session death orphans all of a thread's background work. */
65 readonly clearThreadLiveness: (threadId: string) => void;
66
67 /**
68 * Two-state vocabulary by design: any live agent work is "working";
69 * "monitoring" only when watch loops are the ONLY live work.
70 */
71 readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;
72 }
73>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}
74
75export function make(): ThreadBackgroundLivenessService["Service"] {
76 const stateByThreadId = new Map<string, ThreadLivenessState>();
77
78 const stateFor = (threadId: string): ThreadLivenessState => {
79 const existing = stateByThreadId.get(threadId);
80 if (existing) {
81 return existing;
82 }
83 const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };
84 stateByThreadId.set(threadId, created);
85 return created;
86 };
87
88 // Classification is per-transition, not sticky: a task first seen without
89 // a taskType may later reveal itself as a shell, become inert, or turn out
90 // to be agent-owned. Every path drops any prior entry for the taskId so a
91 // stale bucket assignment can't pin the thread's status (review finding).
92 const drop = (threadId: string, taskId: string) => {
93 const state = stateByThreadId.get(threadId);
94 if (!state) {
95 return;
96 }
97 state.agents.delete(taskId);
98 state.monitors.delete(taskId);
99 if (state.agents.size === 0 && state.monitors.size === 0) {
100 stateByThreadId.delete(threadId);
101 }
102 };
103
104 return {
105 recordTaskLiveness: (input) => {
106 const taskType = input.taskType;
107 if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {
108 drop(input.threadId, input.taskId);
109 return;
110 }
111 // A subagent's internal non-agent work (its own shells/monitors) is
112 // covered by the owning agent's liveness. Nested agents fall through:
113 // they can outlive their parent (review finding).
114 if (
115 input.agentId !== undefined &&
116 (taskType === undefined || MONITOR_TASK_TYPES.has(taskType))
117 ) {
118 drop(input.threadId, input.taskId);
119 return;
120 }
121
122 // Idle counts as not-live: a resting (resumable) Codex child isn't
123 // doing anything, and an all-idle fleet must not pin Working.
124 const terminal =
125 input.kind === "completed" ||
126 input.status === "idle" ||
127 (input.status !== undefined && TERMINAL_STATUSES.has(input.status));
128 if (terminal) {
129 drop(input.threadId, input.taskId);
130 return;
131 }
132
133 // Status-free progress is a description tick, not a restart. A delayed
134 // progress event after idle must not put the task back in the live set
135 // (#7128).
136 if (input.kind === "progress" && input.status === undefined) {
137 const existing = stateByThreadId.get(input.threadId);
138 const stillLive =
139 existing !== undefined &&
140 (existing.agents.has(input.taskId) || existing.monitors.has(input.taskId));
141 if (!stillLive) {
142 return;
143 }
144 }
145
146 drop(input.threadId, input.taskId);
147 const state = stateFor(input.threadId);
148 const bucket =
149 taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;
150 bucket.add(input.taskId);
151 },
152
153 clearThreadLiveness: (threadId) => {
154 stateByThreadId.delete(threadId);
155 },
156
157 getThreadBackgroundLiveness: (threadId) => {
158 const state = stateByThreadId.get(threadId);
159 if (!state) {
160 return null;
161 }
162 if (state.agents.size > 0) {
163 return "working";
164 }
165 if (state.monitors.size > 0) {
166 return "monitoring";
167 }
168 return null;
169 },
170 };
171}
172
173export const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));