Open History to see the last commit
1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import {
3 buildProjectGroups,
4 derivePhysicalProjectKey,
5 deriveProjectGroupLabel,
6} from "@t3tools/client-runtime/state/project-grouping";
7import type {
8 EnvironmentProject,
9 EnvironmentThreadShell,
10} from "@t3tools/client-runtime/state/shell";
11import {
12 getThreadSortTimestamp,
13 sortThreads,
14 toSortableTimestamp,
15} from "@t3tools/client-runtime/state/thread-sort";
16import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
17import type {
18 EnvironmentId,
19 ScopedProjectRef,
20 SidebarProjectGroupingMode,
21 SidebarProjectSortOrder,
22 SidebarThreadSortOrder,
23} from "@t3tools/contracts";
24import * as Arr from "effect/Array";
25import * as Option from "effect/Option";
26import * as Order from "effect/Order";
27
28import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
29import type { PendingNewTask } from "../../state/use-pending-new-tasks";
30
31export type HomeProjectSortOrder = Exclude<SidebarProjectSortOrder, "manual">;
32
33export interface HomeProjectScope {
34 readonly key: string;
35 readonly title: string;
36 readonly representative: EnvironmentProject;
37 readonly projects: ReadonlyArray<EnvironmentProject>;
38 readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
39}
40
41function getProjectSortTimestamp(
42 project: EnvironmentProject,
43 sortOrder: HomeProjectSortOrder,
44): number {
45 return sortOrder === "created_at"
46 ? (toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY)
47 : (toSortableTimestamp(project.updatedAt) ??
48 toSortableTimestamp(project.createdAt) ??
49 Number.NEGATIVE_INFINITY);
50}
51
52export function buildHomeProjectScopes(input: {
53 readonly projects: ReadonlyArray<EnvironmentProject>;
54 readonly environmentId: EnvironmentId | null;
55 readonly projectGroupingMode: SidebarProjectGroupingMode;
56}): ReadonlyArray<HomeProjectScope> {
57 const projects = input.projects.filter(
58 (project) => input.environmentId === null || project.environmentId === input.environmentId,
59 );
60 return buildProjectGroups({
61 projects,
62 settings: {
63 sidebarProjectGroupingMode: input.projectGroupingMode,
64 sidebarProjectGroupingOverrides: {},
65 },
66 }).map((group) => {
67 return {
68 key: group.key,
69 title: group.label,
70 representative: group.representative,
71 projects: group.members.map((member) => member.project),
72 projectRefs: group.memberProjectRefs,
73 };
74 });
75}
76
77export function sortHomeProjectScopes(input: {
78 readonly scopes: ReadonlyArray<HomeProjectScope>;
79 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
80 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
81 readonly projectSortOrder: HomeProjectSortOrder;
82}): ReadonlyArray<HomeProjectScope> {
83 const scopeKeyByProjectRef = new Map(
84 input.scopes.flatMap((scope) =>
85 scope.projectRefs.map(
86 (projectRef) =>
87 [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.key] as const,
88 ),
89 ),
90 );
91 const latestActivityByScope = new Map<string, number>();
92 const recordActivity = (scopeKey: string | undefined, timestamp: number) => {
93 if (!scopeKey || !Number.isFinite(timestamp)) return;
94 latestActivityByScope.set(
95 scopeKey,
96 Math.max(latestActivityByScope.get(scopeKey) ?? Number.NEGATIVE_INFINITY, timestamp),
97 );
98 };
99
100 for (const thread of input.threads) {
101 if (thread.archivedAt !== null) continue;
102 recordActivity(
103 scopeKeyByProjectRef.get(scopedProjectKey(thread.environmentId, thread.projectId)),
104 getThreadSortTimestamp(thread, input.projectSortOrder),
105 );
106 }
107 for (const pendingTask of input.pendingTasks) {
108 recordActivity(
109 scopeKeyByProjectRef.get(scopedProjectKey(pendingTask.environmentId, pendingTask.projectId)),
110 Date.parse(pendingTask.createdAt),
111 );
112 }
113
114 return Arr.sort(
115 input.scopes,
116 Order.mapInput(
117 Order.Struct({
118 timestamp: Order.flip(Order.Number),
119 title: Order.String,
120 key: Order.String,
121 }),
122 (scope: HomeProjectScope) => ({
123 timestamp:
124 latestActivityByScope.get(scope.key) ??
125 Math.max(
126 ...scope.projects.map((project) =>
127 getProjectSortTimestamp(project, input.projectSortOrder),
128 ),
129 ),
130 title: scope.title,
131 key: scope.key,
132 }),
133 ),
134 );
135}
136
137/**
138 * Default home view only surfaces threads active within this window, to keep the
139 * screen compact while keeping recent work visible.
140 */
141const RECENT_THREAD_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
142/** Fallback when a project has no threads inside the recency window. */
143const RECENT_THREAD_FALLBACK_COUNT = 3;
144
145export interface HomeThreadGroup {
146 readonly key: string;
147 readonly title: string;
148 readonly representative: EnvironmentProject;
149 readonly projects: ReadonlyArray<EnvironmentProject>;
150 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
151 /** Full sorted thread history for the group (revealed when expanded / searching). */
152 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
153 /** Subset shown by default: threads from the last few days, or the most recent few. */
154 readonly recentThreads: ReadonlyArray<EnvironmentThreadShell>;
155 /**
156 * Where a quick "new thread in this project" should land. For aggregated
157 * groups (same repo on several machines) this is the member that owns the
158 * group's most recent thread — the machine the user last worked on — rather
159 * than the arbitrary first member; the draft's computer picker covers
160 * switching from there. Null only for synthetic pending-project groups,
161 * whose single "project" is a placeholder built from queued-task metadata.
162 */
163 readonly newThreadTarget: EnvironmentProject | null;
164}
165
166interface MutableHomeThreadGroup {
167 readonly key: string;
168 readonly projects: EnvironmentProject[];
169 readonly pendingTasks: PendingNewTask[];
170 readonly threads: EnvironmentThreadShell[];
171}
172
173function groupSortTimestamp(group: HomeThreadGroup, sortOrder: HomeProjectSortOrder): number {
174 const latestThread = group.threads.reduce(
175 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
176 Number.NEGATIVE_INFINITY,
177 );
178 return group.pendingTasks.reduce((latest, pendingTask) => {
179 const timestamp = Date.parse(pendingTask.createdAt);
180 return Number.isNaN(timestamp) ? latest : Math.max(latest, timestamp);
181 }, latestThread);
182}
183
184/**
185 * Trims a group's threads to recent activity for the default home view.
186 * `sortedThreads` must already be ordered newest-first for `threadSortOrder`.
187 * Keeps threads within {@link RECENT_THREAD_WINDOW_MS}; when none qualify, keeps
188 * the most recent {@link RECENT_THREAD_FALLBACK_COUNT} so a project never vanishes.
189 */
190function selectRecentThreads(
191 sortedThreads: ReadonlyArray<EnvironmentThreadShell>,
192 threadSortOrder: SidebarThreadSortOrder,
193 now: number,
194 queuedThreadKeys: ReadonlySet<string> | undefined,
195): ReadonlyArray<EnvironmentThreadShell> {
196 const cutoff = now - RECENT_THREAD_WINDOW_MS;
197 // A thread with a message waiting in the outbox has work the user is
198 // waiting on, however old its last activity; it never trims away.
199 const recent = sortedThreads.filter(
200 (thread) =>
201 getThreadSortTimestamp(thread, threadSortOrder) >= cutoff ||
202 queuedThreadKeys?.has(scopedThreadKey(thread.environmentId, thread.id)) === true,
203 );
204 return recent.length > 0 ? recent : sortedThreads.slice(0, RECENT_THREAD_FALLBACK_COUNT);
205}
206
207export function buildHomeThreadGroups(input: {
208 readonly projects: ReadonlyArray<EnvironmentProject>;
209 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
210 readonly pendingTasks?: ReadonlyArray<PendingNewTask>;
211 /** Thread keys with a message waiting in the outbox; kept in the default view. */
212 readonly queuedThreadKeys?: ReadonlySet<string>;
213 readonly environmentId: EnvironmentId | null;
214 readonly searchQuery: string;
215 readonly matchedThreadKeys?: ReadonlySet<string>;
216 readonly projectSortOrder: HomeProjectSortOrder;
217 readonly threadSortOrder: SidebarThreadSortOrder;
218 readonly projectGroupingMode: SidebarProjectGroupingMode;
219 /** Current time used for the recency window; defaults to now. Injectable for tests. */
220 readonly now?: number;
221}): ReadonlyArray<HomeThreadGroup> {
222 const now = input.now ?? Date.now();
223 const groups = new Map<string, MutableHomeThreadGroup>();
224 const groupTitleByKey = new Map<string, string>();
225 const groupKeyByProjectKey = new Map<string, string>();
226
227 for (const scope of buildHomeProjectScopes(input)) {
228 groupTitleByKey.set(scope.key, scope.title);
229 groups.set(scope.key, {
230 key: scope.key,
231 projects: [...scope.projects],
232 pendingTasks: [],
233 threads: [],
234 });
235 for (const projectRef of scope.projectRefs) {
236 groupKeyByProjectKey.set(
237 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
238 scope.key,
239 );
240 }
241 }
242
243 for (const pendingTask of input.pendingTasks ?? []) {
244 if (input.environmentId !== null && pendingTask.environmentId !== input.environmentId) {
245 continue;
246 }
247
248 const physicalKey = scopedProjectKey(pendingTask.environmentId, pendingTask.projectId);
249 let groupKey = groupKeyByProjectKey.get(physicalKey);
250 if (!groupKey) {
251 // The project shell is not loaded (environment offline / project gone).
252 // A queued task must stay visible and deletable regardless, so build a
253 // standalone group from the metadata snapshotted at enqueue time.
254 groupKey = `pending-project:${physicalKey}`;
255 groupKeyByProjectKey.set(physicalKey, groupKey);
256 groups.set(groupKey, {
257 key: groupKey,
258 projects: [
259 {
260 environmentId: pendingTask.environmentId,
261 id: pendingTask.projectId,
262 title: pendingTask.projectTitle ?? "Unknown project",
263 workspaceRoot: pendingTask.projectCwd ?? String(pendingTask.projectId),
264 repositoryIdentity: null,
265 defaultModelSelection: null,
266 scripts: [],
267 createdAt: pendingTask.createdAt,
268 updatedAt: pendingTask.createdAt,
269 },
270 ],
271 pendingTasks: [],
272 threads: [],
273 });
274 }
275 groups.get(groupKey)?.pendingTasks.push(pendingTask);
276 }
277
278 for (const thread of input.threads) {
279 if (thread.archivedAt !== null) {
280 continue;
281 }
282 if (input.environmentId !== null && thread.environmentId !== input.environmentId) {
283 continue;
284 }
285
286 const physicalKey = scopedProjectKey(thread.environmentId, thread.projectId);
287 const groupKey = groupKeyByProjectKey.get(physicalKey);
288 if (!groupKey) {
289 continue;
290 }
291 groups.get(groupKey)?.threads.push(thread);
292 }
293
294 const query = input.searchQuery.trim().toLocaleLowerCase();
295 const result: HomeThreadGroup[] = [];
296
297 for (const group of groups.values()) {
298 const representative = group.projects[0];
299 if (!representative || (group.threads.length === 0 && group.pendingTasks.length === 0)) {
300 continue;
301 }
302
303 const title =
304 groupTitleByKey.get(group.key) ??
305 deriveProjectGroupLabel({ representative, members: group.projects });
306 const groupMatches =
307 query.length === 0 ||
308 title.toLocaleLowerCase().includes(query) ||
309 group.projects.some((project) => project.title.toLocaleLowerCase().includes(query));
310 const matchingThreads = groupMatches
311 ? group.threads
312 : group.threads.filter(
313 (thread) =>
314 thread.title.toLocaleLowerCase().includes(query) ||
315 threadPullRequestSearchTerms(thread).some((term) =>
316 term.toLocaleLowerCase().includes(query),
317 ) ||
318 input.matchedThreadKeys?.has(
319 threadSearchMatchKey({
320 environmentId: thread.environmentId,
321 threadId: thread.id,
322 }),
323 ) === true,
324 );
325 const matchingPendingTasks = groupMatches
326 ? group.pendingTasks
327 : group.pendingTasks.filter((pendingTask) =>
328 pendingTask.title.toLocaleLowerCase().includes(query),
329 );
330
331 if (matchingThreads.length === 0 && matchingPendingTasks.length === 0) {
332 continue;
333 }
334
335 const sortedThreads = sortThreads(matchingThreads, input.threadSortOrder);
336 // An active search should reach the full history, so the recency window
337 // only trims the default (no-query) view.
338 const recentThreads =
339 query.length === 0
340 ? selectRecentThreads(sortedThreads, input.threadSortOrder, now, input.queuedThreadKeys)
341 : sortedThreads;
342
343 // A stale project id still resolves to the canonical member with the same
344 // environment/path, so quick creation follows the machine with the newest activity.
345 const lastActiveProject = Arr.head(sortedThreads).pipe(
346 Option.flatMap((thread) =>
347 Arr.findFirst(
348 input.projects,
349 (project) =>
350 project.environmentId === thread.environmentId && project.id === thread.projectId,
351 ),
352 ),
353 Option.flatMap((threadProject) =>
354 Arr.findFirst(
355 group.projects,
356 (project) =>
357 derivePhysicalProjectKey(project) === derivePhysicalProjectKey(threadProject),
358 ),
359 ),
360 Option.getOrNull,
361 );
362
363 result.push({
364 key: group.key,
365 title,
366 representative,
367 projects: group.projects,
368 pendingTasks: matchingPendingTasks,
369 threads: sortedThreads,
370 recentThreads,
371 newThreadTarget: group.key.startsWith("pending-project:")
372 ? null
373 : (lastActiveProject ?? representative),
374 });
375 }
376
377 return Arr.sort(
378 result,
379 Order.mapInput(
380 Order.Struct({
381 timestamp: Order.flip(Order.Number),
382 title: Order.String,
383 key: Order.String,
384 }),
385 (group: HomeThreadGroup) => ({
386 timestamp: groupSortTimestamp(group, input.projectSortOrder),
387 title: group.title,
388 key: group.key,
389 }),
390 ),
391 );
392}