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 * known internal shells and monitors are tracked independently: the owner
52 * can finish while a child remains live and must still block an idle
53 * session stop. Untyped internal rows remain covered by their owner;
54 * nested agents (agentId + agent-flavored taskType) count as working and
55 * can likewise outlive their parent.
56 */
57 readonly recordTaskLiveness: (input: {
58 readonly threadId: string;
59 readonly taskId: string;
60 readonly taskType: string | undefined;
61 readonly status: string | undefined;
62 readonly kind: "started" | "progress" | "updated" | "completed";
63 readonly agentId?: string | undefined;
64 }) => void;
65
66 /** Session death orphans all of a thread's background work. */
67 readonly clearThreadLiveness: (threadId: string) => void;
68
69 /**
70 * Two-state vocabulary by design: any live agent work is "working";
71 * "monitoring" only when watch loops are the ONLY live work.
72 */
73 readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;
74 }
75>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}
76
77export function make(): ThreadBackgroundLivenessService["Service"] {
78 const stateByThreadId = new Map<string, ThreadLivenessState>();
79
80 const stateFor = (threadId: string): ThreadLivenessState => {
81 const existing = stateByThreadId.get(threadId);
82 if (existing) {
83 return existing;
84 }
85 const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };
86 stateByThreadId.set(threadId, created);
87 return created;
88 };
89
90 // Classification is per-transition, not sticky: a task first seen without
91 // a taskType may later reveal itself as a shell, become inert, or turn out
92 // to be agent-owned. Every path drops any prior entry for the taskId so a
93 // stale bucket assignment can't pin the thread's status (review finding).
94 const drop = (threadId: string, taskId: string) => {
95 const state = stateByThreadId.get(threadId);
96 if (!state) {
97 return;
98 }
99 state.agents.delete(taskId);
100 state.monitors.delete(taskId);
101 if (state.agents.size === 0 && state.monitors.size === 0) {
102 stateByThreadId.delete(threadId);
103 }
104 };
105
106 return {
107 recordTaskLiveness: (input) => {
108 const taskType = input.taskType;
109 if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {
110 drop(input.threadId, input.taskId);
111 return;
112 }
113 // Untyped internal work has no reliable bucket of its own; retain the
114 // owner's liveness coverage until a typed lifecycle row arrives.
115 if (input.agentId !== undefined && taskType === undefined) {
116 drop(input.threadId, input.taskId);
117 return;
118 }
119 // Idle counts as not-live: a resting (resumable) Codex child isn't
120 // doing anything, and an all-idle fleet must not pin Working.
121 const terminal =
122 input.kind === "completed" ||
123 input.status === "idle" ||
124 (input.status !== undefined && TERMINAL_STATUSES.has(input.status));
125 if (terminal) {
126 drop(input.threadId, input.taskId);
127 return;
128 }
129
130 // Status-free progress and metadata updates are not restarts. A delayed
131 // row after idle must not put the task back in the live set (#7128).
132 if ((input.kind === "progress" || input.kind === "updated") && input.status === undefined) {
133 const existing = stateByThreadId.get(input.threadId);
134 const stillLive =
135 existing !== undefined &&
136 (existing.agents.has(input.taskId) || existing.monitors.has(input.taskId));
137 if (!stillLive) {
138 return;
139 }
140 }
141
142 drop(input.threadId, input.taskId);
143 const state = stateFor(input.threadId);
144 const bucket =
145 taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;
146 bucket.add(input.taskId);
147 },
148
149 clearThreadLiveness: (threadId) => {
150 stateByThreadId.delete(threadId);
151 },
152
153 getThreadBackgroundLiveness: (threadId) => {
154 const state = stateByThreadId.get(threadId);
155 if (!state) {
156 return null;
157 }
158 if (state.agents.size > 0) {
159 return "working";
160 }
161 if (state.monitors.size > 0) {
162 return "monitoring";
163 }
164 return null;
165 },
166 };
167}
168
169export const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));