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