Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadInbox.ts

111 lines4.3 KB

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);
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 [...threads].sort(
62 (left, right) =>
63 timestamps.get(right)! - timestamps.get(left)! ||
64 left.id.localeCompare(right.id) ||
65 left.environmentId.localeCompare(right.environmentId),
66 );
68​
69/**
70 * Remembers when this client saw each thread leave the Working section. Keep
71 * one at module scope so the inbox order survives routes that unmount the
72 * list. Call `observe` with every thread shell on each list rebuild, or with
73 * null to reset while the beta is off. The first call only takes a baseline,
74 * so mounting never reshuffles the inbox.
75 */
76export function createInboxReturnTracker() {
77 const keyOf = (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
78 `${thread.environmentId}:${thread.id}`;
79 let lastWorkingKeys: ReadonlySet<string> | null = null;
80 const returns = new Map<string, number>();
81 return {
82 observe(threads: ReadonlyArray<WorkingThreadInput & InboxThreadInput> | null): void {
83 if (threads === null) {
84 lastWorkingKeys = null;
85 returns.clear();
86 return;
87 }
88 const working = new Set<string>();
89 const present = new Set<string>();
90 for (const thread of threads) {
91 const key = keyOf(thread);
92 present.add(key);
93 if (isThreadWorking(thread)) working.add(key);
94 }
95 // Drop deleted threads so the map stays bounded by the live thread list.
96 for (const key of returns.keys()) {
97 if (!present.has(key)) returns.delete(key);
98 }
99 // The moment this client saw the change is the data; there is no
100 // server stamp to read instead.
101 // @effect-diagnostics-next-line globalDate:off
102 const at = Date.now();
103 for (const key of lastWorkingKeys ?? []) {
104 if (present.has(key) && !working.has(key)) returns.set(key, at);
105 }
106 lastWorkingKeys = working;
107 },
108 returnedAt: (thread: Pick<EnvironmentThreadShell, "environmentId" | "id">) =>
109 returns.get(keyOf(thread)),
110 };