Open History to see the last commit
1// @effect-diagnostics globalTimers:off - Shelf placement timers run in web and native clients, outside an Effect runtime.
2import { threadRuntimeIsActive, type EnvironmentThreadShell } from "./models.ts";
3import { toSortableTimestamp } from "./threadSort.ts";
4import { effectiveSnoozed } from "./threadSettled.ts";
5
6type WorkingThreadInput = Pick<
7 EnvironmentThreadShell,
8 | "hasActionableProposedPlan"
9 | "hasPendingApprovals"
10 | "hasPendingUserInput"
11 | "pendingSubagentRequest"
12 | "interactionMode"
13 | "latestRun"
14 | "runtime"
15>;
16
17export function isThreadWorking(thread: WorkingThreadInput): boolean {
18 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return false;
19 if (thread.pendingSubagentRequest != null) return false;
20 if (!threadRuntimeIsActive(thread.runtime) && thread.runtime?.status !== "idle") return false;
21 const run = thread.latestRun;
22 const runSettled =
23 run !== null &&
24 run.status !== "preparing" &&
25 run.status !== "queued" &&
26 run.status !== "starting" &&
27 run.status !== "running" &&
28 run.status !== "waiting" &&
29 thread.runtime?.activeRunId !== run.runId;
30 return !(thread.interactionMode === "plan" && thread.hasActionableProposedPlan && runSettled);
31}
32
33type InboxThreadInput = Pick<
34 EnvironmentThreadShell,
35 "id" | "environmentId" | "createdAt" | "unsettledAt" | "latestRun"
36>;
37
38export function sortInboxThreadsByReturn<T extends InboxThreadInput>(
39 threads: readonly T[],
40 observedReturnAt?: (thread: T) => number | undefined,
41): T[] {
42 const timestamps = new Map(
43 threads.map((thread) => [
44 thread,
45 Math.max(
46 toSortableTimestamp(thread.createdAt) ?? 0,
47 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
48 toSortableTimestamp(thread.latestRun?.requestedAt ?? undefined) ?? 0,
49 toSortableTimestamp(thread.latestRun?.completedAt ?? undefined) ?? 0,
50 observedReturnAt?.(thread) ?? 0,
51 ),
52 ]),
53 );
54 return sortNewestFirst(threads, timestamps);
55}
56
57type WorkingSortInput = Pick<
58 EnvironmentThreadShell,
59 "id" | "environmentId" | "createdAt" | "latestRun" | "latestUserAuthoredMessageAt"
60>;
61
62export function sortWorkingThreadsBySend<T extends WorkingSortInput>(threads: readonly T[]): T[] {
63 const timestamps = new Map(
64 threads.map((thread) => [
65 thread,
66 Math.max(
67 toSortableTimestamp(thread.createdAt) ?? 0,
68 toSortableTimestamp(
69 (thread.latestUserAuthoredMessageAt === undefined
70 ? thread.latestRun?.requestedAt
71 : thread.latestUserAuthoredMessageAt) ?? undefined,
72 ) ?? 0,
73 ),
74 ]),
75 );
76 return sortNewestFirst(threads, timestamps);
77}
78
79function sortNewestFirst<T extends Pick<EnvironmentThreadShell, "id" | "environmentId">>(
80 threads: readonly T[],
81 timestamps: ReadonlyMap<T, number>,
82): T[] {
83 return [...threads].sort(
84 (left, right) =>
85 timestamps.get(right)! - timestamps.get(left)! ||
86 left.id.localeCompare(right.id) ||
87 left.environmentId.localeCompare(right.environmentId),
88 );
89}
90
91type TrackedInboxThread = WorkingThreadInput &
92 InboxThreadInput &
93 Partial<
94 Pick<
95 EnvironmentThreadShell,
96 | "archivedAt"
97 | "deletedAt"
98 | "pinnedAt"
99 | "settledOverride"
100 | "settledAt"
101 | "snoozedAt"
102 | "snoozedUntil"
103 | "activeOrderKey"
104 | "pendingGuestMessageCount"
105 >
106 >;
107
108type ThreadKeyInput = Pick<EnvironmentThreadShell, "environmentId" | "id">;
109
110/**
111 * How long a thread that stopped working keeps reading as working. An orchestrator
112 * run can end moments before its continuation starts, so clients wait this long
113 * before treating the thread as done.
114 */
115const WORKING_EXIT_GRACE_MS = 2_000;
116
117/**
118 * Keep one at module scope so placement survives routes that unmount the list. Call
119 * `observe` when the shells or the snapshot version change, or with null while the beta
120 * is off. Its result stays fixed, so a list built from it can be cached.
121 */
122export function createInboxReturnTracker() {
123 const keyOf = (thread: ThreadKeyInput) => `${thread.environmentId}:${thread.id}`;
124 const states = new Map<
125 string,
126 { working: boolean; deadline: number | null; placement: string | null }
127 >();
128 const returns = new Map<string, number>();
129 const listeners = new Set<() => void>();
130 let timer: ReturnType<typeof setTimeout> | undefined;
131 let version = 0;
132 const now = () => {
133 // @effect-diagnostics-next-line globalDate:off - The grace deadline is wall-clock time shared by web and native clients.
134 return Date.now();
135 };
136 const schedule = () => {
137 clearTimeout(timer);
138 timer = undefined;
139 let next = Infinity;
140 for (const state of states.values()) {
141 if (state.deadline !== null) next = Math.min(next, state.deadline);
142 }
143 if (next === Infinity) return;
144 timer = setTimeout(
145 () => {
146 const at = now();
147 for (const [key, state] of states) {
148 if (state.deadline !== null && state.deadline <= at) {
149 state.working = false;
150 state.deadline = null;
151 returns.set(key, at);
152 }
153 }
154 schedule();
155 version++;
156 for (const listener of listeners) listener();
157 },
158 Math.max(0, next - now()),
159 );
160 };
161 return {
162 subscribe(listener: () => void) {
163 listeners.add(listener);
164 return () => {
165 listeners.delete(listener);
166 };
167 },
168 getSnapshot: () => version,
169 observe(threads: readonly TrackedInboxThread[] | null): {
170 readonly isWorking: (thread: WorkingThreadInput & ThreadKeyInput) => boolean;
171 readonly returnedAt: (thread: ThreadKeyInput) => number | undefined;
172 } {
173 if (threads === null) {
174 clearTimeout(timer);
175 timer = undefined;
176 states.clear();
177 returns.clear();
178 return { isWorking: isThreadWorking, returnedAt: () => undefined };
179 }
180 const present = new Set<string>();
181 const at = now();
182 // @effect-diagnostics-next-line globalDate:off - Snooze checks compare wall-clock ISO times.
183 const observedAt = new Date(at).toISOString();
184 for (const thread of threads) {
185 const key = keyOf(thread);
186 present.add(key);
187 const previous = states.get(key);
188 const actual = isThreadWorking(thread);
189 const placement =
190 actual || previous?.working
191 ? JSON.stringify([
192 thread.archivedAt,
193 thread.deletedAt,
194 thread.pinnedAt,
195 thread.settledOverride,
196 thread.settledAt,
197 thread.snoozedAt,
198 thread.snoozedUntil,
199 thread.activeOrderKey,
200 ])
201 : null;
202 const actionable =
203 thread.hasPendingApprovals ||
204 thread.hasPendingUserInput ||
205 thread.pendingSubagentRequest != null ||
206 (thread.pendingGuestMessageCount ?? 0) > 0 ||
207 (thread.interactionMode === "plan" && thread.hasActionableProposedPlan) ||
208 thread.runtime?.lastError != null ||
209 thread.latestRun?.status === "failed";
210 const moved = previous !== undefined && previous.placement !== placement;
211 const excluded =
212 thread.archivedAt != null ||
213 thread.deletedAt != null ||
214 thread.pinnedAt != null ||
215 thread.settledOverride === "settled" ||
216 effectiveSnoozed(thread, { now: observedAt });
217 // Only shelf placement is held: execution state and attention requests stay authoritative.
218 const deadline =
219 !actual && previous?.working && !actionable && !moved && !excluded
220 ? (previous.deadline ?? at + WORKING_EXIT_GRACE_MS)
221 : null;
222 const working = actual || (deadline !== null && deadline > at);
223 if (previous?.working && !working) returns.set(key, at);
224 states.set(key, { working, deadline: working ? deadline : null, placement });
225 }
226 for (const key of states.keys()) {
227 if (!present.has(key)) {
228 states.delete(key);
229 returns.delete(key);
230 }
231 }
232 schedule();
233 const observedWorking = new Map<string, boolean>();
234 states.forEach((state, key) => observedWorking.set(key, state.working));
235 const observedReturns = new Map(returns);
236 return {
237 isWorking: (thread) => observedWorking.get(keyOf(thread)) ?? isThreadWorking(thread),
238 returnedAt: (thread) => observedReturns.get(keyOf(thread)),
239 };
240 },
241 isWorking: (thread: WorkingThreadInput & ThreadKeyInput) =>
242 states.get(keyOf(thread))?.working ?? isThreadWorking(thread),
243 returnedAt: (thread: ThreadKeyInput) => returns.get(keyOf(thread)),
244 };
245}