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