Open History to see the last commit
1import { threadRuntimeIsActive, type EnvironmentThreadShell } from "./models.ts";
2import { toSortableTimestamp } from "./threadSort.ts";
3
4// Working section beta, shared so web and mobile fold and order the inbox the
5// same way. Off by default; each client owns its own toggle.
6
7type WorkingThreadInput = Pick<
8 EnvironmentThreadShell,
9 | "hasActionableProposedPlan"
10 | "hasPendingApprovals"
11 | "hasPendingUserInput"
12 | "pendingSubagentRequest"
13 | "interactionMode"
14 | "latestRun"
15 | "runtime"
16>;
17
18/** Threads busy with work that does not need the user fold into the Working
19 section: a running run, or one stopped with background work that will wake
20 it. Approvals, questions (its own or a subagent's), plan prompts, and
21 failures stay in the inbox. */
22export function isThreadWorking(thread: WorkingThreadInput): boolean {
23 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return false;
24 if (thread.pendingSubagentRequest != null) return false;
25 if (!threadRuntimeIsActive(thread.runtime) && thread.runtime?.status !== "idle") return false;
26 // A plan prompt outranks lingering background work: the user has to act on it.
27 const run = thread.latestRun;
28 const runSettled =
29 run !== null &&
30 run.status !== "preparing" &&
31 run.status !== "queued" &&
32 run.status !== "starting" &&
33 run.status !== "running" &&
34 run.status !== "waiting" &&
35 thread.runtime?.activeRunId !== run.runId;
36 return !(thread.interactionMode === "plan" && thread.hasActionableProposedPlan && runSettled);
37}
38
39type InboxThreadInput = Pick<
40 EnvironmentThreadShell,
41 "id" | "environmentId" | "createdAt" | "unsettledAt" | "latestRun"
42>;
43
44/** The inbox lists threads newest first by when each last came back to the
45 user, so a thread that leaves the Working section lands on top.
46 `observedReturnAt` adds returns the server does not stamp, such as an
47 approval request mid-turn or background work ending. */
48export function sortInboxThreadsByReturn<T extends InboxThreadInput>(
49 threads: readonly T[],
50 observedReturnAt?: (thread: T) => number | undefined,
51): T[] {
52 const timestamps = new Map(
53 threads.map((thread) => [
54 thread,
55 Math.max(
56 toSortableTimestamp(thread.createdAt) ?? 0,
57 toSortableTimestamp(thread.unsettledAt ?? undefined) ?? 0,
58 toSortableTimestamp(thread.latestRun?.requestedAt ?? undefined) ?? 0,
59 toSortableTimestamp(thread.latestRun?.completedAt ?? undefined) ?? 0,
60 observedReturnAt?.(thread) ?? 0,
61 ),
62 ]),
63 );
64 return sortNewestFirst(threads, timestamps);
65}
66
67type WorkingSortInput = Pick<
68 EnvironmentThreadShell,
69 "id" | "environmentId" | "createdAt" | "latestRun" | "latestUserAuthoredMessageAt"
70>;
71
72/** The Working section lists threads newest first by the last message the
73 user sent. Runs ending and wakes (background results, delegated results,
74 PR watches) do not move a row, so the order stays put while agents finish
75 and resume. Servers without the authored stamp fall back to the latest
76 run's request time. */
77export function sortWorkingThreadsBySend<T extends WorkingSortInput>(threads: readonly T[]): T[] {
78 const timestamps = new Map(
79 threads.map((thread) => [
80 thread,
81 Math.max(
82 toSortableTimestamp(thread.createdAt) ?? 0,
83 toSortableTimestamp(
84 (thread.latestUserAuthoredMessageAt === undefined
85 ? thread.latestRun?.requestedAt
86 : thread.latestUserAuthoredMessageAt) ?? undefined,
87 ) ?? 0,
88 ),
89 ]),
90 );
91 return sortNewestFirst(threads, timestamps);
92}
93
94function sortNewestFirst<T extends Pick<EnvironmentThreadShell, "id" | "environmentId">>(
95 threads: readonly T[],
96 timestamps: ReadonlyMap<T, number>,
97): T[] {
98 return [...threads].sort(
99 (left, right) =>
100 timestamps.get(right)! - timestamps.get(left)! ||
101 left.id.localeCompare(right.id) ||
102 left.environmentId.localeCompare(right.environmentId),
103 );
104}
105
106/**
107 * Remembers when this client saw each thread leave the Working section. Keep
108 * one at module scope so the inbox order survives routes that unmount the
109 * list. Call `observe` with every thread shell on each list rebuild, or with
110 * null to reset while the beta is off. The first call only takes a baseline,
111 * so mounting never reshuffles the inbox.
112 */
113export function createInboxReturnTracker() {
114 const keyOf = (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
115 `${thread.environmentId}:${thread.id}`;
116 let lastWorkingKeys: ReadonlySet<string> | null = null;
117 const returns = new Map<string, number>();
118 return {
119 observe(threads: ReadonlyArray<WorkingThreadInput & InboxThreadInput> | null): void {
120 if (threads === null) {
121 lastWorkingKeys = null;
122 returns.clear();
123 return;
124 }
125 const working = new Set<string>();
126 const present = new Set<string>();
127 for (const thread of threads) {
128 const key = keyOf(thread);
129 present.add(key);
130 if (isThreadWorking(thread)) working.add(key);
131 }
132 // Drop deleted threads so the map stays bounded by the live thread list.
133 for (const key of returns.keys()) {
134 if (!present.has(key)) returns.delete(key);
135 }
136 // The moment this client saw the change is the data; there is no
137 // server stamp to read instead.
138 // @effect-diagnostics-next-line globalDate:off
139 const at = Date.now();
140 for (const key of lastWorkingKeys ?? []) {
141 if (present.has(key) && !working.has(key)) returns.set(key, at);
142 }
143 lastWorkingKeys = working;
144 },
145 returnedAt: (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
146 returns.get(keyOf(thread)),
147 };
148}