Open History to see the last commit
1import { threadRuntimeIsActive, type EnvironmentThreadShell } from "./models.ts";
2import { toSortableTimestamp } from "./threadSort.ts";
3
4type WorkingThreadInput = Pick<
5 EnvironmentThreadShell,
6 | "hasActionableProposedPlan"
7 | "hasPendingApprovals"
8 | "hasPendingUserInput"
9 | "pendingSubagentRequest"
10 | "interactionMode"
11 | "latestRun"
12 | "runtime"
13>;
14
15export function isThreadWorking(thread: WorkingThreadInput): boolean {
16 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return false;
17 if (thread.pendingSubagentRequest != null) return false;
18 if (!threadRuntimeIsActive(thread.runtime) && thread.runtime?.status !== "idle") return false;
19 const run = thread.latestRun;
20 const runSettled =
21 run !== null &&
22 run.status !== "preparing" &&
23 run.status !== "queued" &&
24 run.status !== "starting" &&
25 run.status !== "running" &&
26 run.status !== "waiting" &&
27 thread.runtime?.activeRunId !== run.runId;
28 return !(thread.interactionMode === "plan" && thread.hasActionableProposedPlan && runSettled);
29}
30
31type InboxThreadInput = Pick<
32 EnvironmentThreadShell,
33 "id" | "environmentId" | "createdAt" | "unsettledAt" | "latestRun"
34>;
35
36export function sortInboxThreadsByReturn<T extends InboxThreadInput>(
37 threads: readonly T[],
38 observedReturnAt?: (thread: T) => number | undefined,
39): T[] {
40 const timestamps = new Map(
41 threads.map((thread) => [
42 thread,
43 Math.max(
44 toSortableTimestamp(thread.createdAt) ?? 0,
45 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
46 toSortableTimestamp(thread.latestRun?.requestedAt ?? undefined) ?? 0,
47 toSortableTimestamp(thread.latestRun?.completedAt ?? undefined) ?? 0,
48 observedReturnAt?.(thread) ?? 0,
49 ),
50 ]),
51 );
52 return sortNewestFirst(threads, timestamps);
53}
54
55type WorkingSortInput = Pick<
56 EnvironmentThreadShell,
57 "id" | "environmentId" | "createdAt" | "latestRun" | "latestUserAuthoredMessageAt"
58>;
59
60export function sortWorkingThreadsBySend<T extends WorkingSortInput>(threads: readonly T[]): T[] {
61 const timestamps = new Map(
62 threads.map((thread) => [
63 thread,
64 Math.max(
65 toSortableTimestamp(thread.createdAt) ?? 0,
66 toSortableTimestamp(
67 (thread.latestUserAuthoredMessageAt === undefined
68 ? thread.latestRun?.requestedAt
69 : thread.latestUserAuthoredMessageAt) ?? undefined,
70 ) ?? 0,
71 ),
72 ]),
73 );
74 return sortNewestFirst(threads, timestamps);
75}
76
77function sortNewestFirst<T extends Pick<EnvironmentThreadShell, "id" | "environmentId">>(
78 threads: readonly T[],
79 timestamps: ReadonlyMap<T, number>,
80): T[] {
81 return [...threads].sort(
82 (left, right) =>
83 timestamps.get(right)! - timestamps.get(left)! ||
84 left.id.localeCompare(right.id) ||
85 left.environmentId.localeCompare(right.environmentId),
86 );
87}
88
89/**
90 * Keep one at module scope so the inbox order survives routes that unmount the
91 * list. Call `observe` with every thread shell on each list rebuild, or with
92 * null to reset while the beta is off.
93 */
94export function createInboxReturnTracker() {
95 const keyOf = (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
96 `${thread.environmentId}:${thread.id}`;
97 let lastWorkingKeys: ReadonlySet<string> | null = null;
98 const returns = new Map<string, number>();
99 return {
100 observe(threads: ReadonlyArray<WorkingThreadInput & InboxThreadInput> | null): void {
101 if (threads === null) {
102 lastWorkingKeys = null;
103 returns.clear();
104 return;
105 }
106 const working = new Set<string>();
107 const present = new Set<string>();
108 for (const thread of threads) {
109 const key = keyOf(thread);
110 present.add(key);
111 if (isThreadWorking(thread)) working.add(key);
112 }
113 for (const key of returns.keys()) {
114 if (!present.has(key)) returns.delete(key);
115 }
116 // @effect-diagnostics-next-line globalDate:off
117 const at = Date.now();
118 for (const key of lastWorkingKeys ?? []) {
119 if (present.has(key) && !working.has(key)) returns.set(key, at);
120 }
121 lastWorkingKeys = working;
122 },
123 returnedAt: (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
124 returns.get(keyOf(thread)),
125 };
126}