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

Sidebar.logic.ts

1,491 lines50.0 KB

1import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
2import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
4import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
5import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
6import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
7import * as React from "react";
8import { msg } from "gt-react";
9import { m, type MessageResolver } from "../i18n/messages";
10import {
11 isAtomCommandInterrupted,
12 type AtomCommandResult,
13} from "@t3tools/client-runtime/state/runtime";
14import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
15import {
16 threadSearchMatchKey,
17 threadSearchSubject,
18 type ThreadSearchShell,
19} from "@t3tools/client-runtime/state/thread-search";
20import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
21import {
22 type ContextMenuItem,
23 type EnvironmentId,
24 type ResolvedKeybindingsConfig,
25 type ScopedThreadRef,
26 type ThreadId,
27} from "@t3tools/contracts";
28import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
29import type { AsyncResult } from "effect/reactivity";
30import {
31 effectiveSnoozed,
32 hasUnseenRunFailure,
33 type ThreadSnoozeShell,
34} from "@t3tools/client-runtime/state/thread-settled";
35import {
36 getThreadSortTimestamp,
37 planPinnedReorder,
38 sortThreads,
39 toSortableTimestamp,
40 type ThreadSortInput,
41} from "@t3tools/client-runtime/state/thread-sort";
42import type { SidebarThreadSummary, Thread } from "../types";
43import { normalizeSearchText } from "../lib/utils";
44import { isLatestRunSettled } from "../session-logic";
45import { THREAD_STATUS_TEXT } from "@t3tools/client-runtime/state/thread-activity-announcement";
46import { observeIntersection } from "../lib/observeIntersection";
47import { deadlineAfter, deadlineStore, type ClockStore } from "@t3tools/client-runtime/clock";
48import { useDeadlinePassed } from "../hooks/useDeadline";
49import { legacyProjectCwdPreferenceKey } from "../uiStateStore";
50import { isElectron } from "../env";
51import { shouldShowThreadJumpHintsForModifiers } from "../keybindings";
52import { isTerminalFocused, subscribeToTerminalFocusChanges } from "../lib/terminalFocus";
53import { isPreviewFocused } from "../lib/previewFocus";
54import { isModelPickerOpen, subscribeToModelPickerVisibility } from "../modelPickerVisibility";
55import { shortcutModifierStore } from "../shortcutModifierState";
56import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
57import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
58​
59export function shouldNavigateAfterThreadPark(input: {
60 readonly threadKey: string;
61 readonly currentThreadKey: string | null;
62 readonly action: "settle" | "snooze";
63 readonly now: string;
64 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
65}): boolean {
66 return (
67 input.threadKey === input.currentThreadKey &&
68 input.thread !== null &&
69 (input.action === "settle"
70 ? input.thread.settledOverride === "settled"
71 : effectiveSnoozed(input.thread, { now: input.now }))
72 );
74​
75export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
76​
77export function resolveSidebarRowAccessibility(input: {
78 readonly title: string;
79 readonly statusLabel: string | null;
80 readonly projectDisplayName: string | null;
81 readonly isActive: boolean;
82}): { readonly label: string; readonly current: "page" | undefined } {
83 return {
84 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
85 current: input.isActive ? "page" : undefined,
86 };
88​
89// Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load.
90const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
91​
92export function useSidebarRowSubscriptionLease(isActive: boolean): {
93 readonly leaseLiveStatus: boolean;
94 readonly rowRef: (row: HTMLElement | null) => (() => void) | undefined;
95} {
96 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
97 if (isActive && !isNearViewport) setIsNearViewport(true);
98 const canObserve = typeof IntersectionObserver !== "undefined";
99​
100 return {
101 leaseLiveStatus: isActive || isNearViewport || !canObserve,
102 rowRef: (row) => {
103 if (row === null || isActive || !canObserve) return undefined;
104 // The overscan has to apply to the sidebar's own scroller; a viewport-rooted
105 // margin is still clipped by it.
106 return observeIntersection(row, (entry) => setIsNearViewport(entry.isIntersecting), {
107 root: row.closest('[data-slot="scroll-area-viewport"]'),
108 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
109 });
110 },
111 };
113​
114const fileDragClears = new Set<(active: false) => void>();
115function clearFileDrags() {
116 const clears = [...fileDragClears];
117 fileDragClears.clear();
118 for (const clear of clears) clear(false);
120​
121/**
122 * A file drag that ends outside every drop target (Escape, or a drop elsewhere)
123 * sends no dragleave to the row it last entered, so the window's dragend clears it.
124 */
125export function setFileDragActive(setActive: (active: boolean) => void, active: boolean) {
126 setActive(active);
127 if (typeof window === "undefined") return;
128 if (!active) {
129 if (fileDragClears.delete(setActive) && fileDragClears.size === 0) {
130 window.removeEventListener("dragend", clearFileDrags);
131 }
132 return;
133 }
134 if (fileDragClears.size === 0) window.addEventListener("dragend", clearFileDrags, { once: true });
135 fileDragClears.add(setActive);
137​
138/**
139 * A clock that advances exactly when a snooze wake time passes, so a woken
140 * thread leaves the shelf on time without a per-second clock.
141 */
142export function useSnoozeWakeClock(
143 threads: ReadonlyArray<{ readonly snoozedUntil?: string | null | undefined }>,
144): number {
145 const [clockMs, setClockMs] = React.useState(() => Date.now());
146 const wakeTimes: number[] = [];
147 let nextWakeAt: number | null = null;
148 for (const thread of threads) {
149 const wakeAt = thread.snoozedUntil == null ? Number.NaN : Date.parse(thread.snoozedUntil);
150 if (!(wakeAt > clockMs)) continue;
151 wakeTimes.push(wakeAt);
152 if (nextWakeAt === null || wakeAt < nextWakeAt) nextWakeAt = wakeAt;
153 }
154 const woke = useDeadlinePassed(nextWakeAt);
155 // Advancing to the latest wake that has passed skips every wake that elapsed
156 // meanwhile, e.g. across a laptop sleep. Stepping one wake at a time would
157 // re-render once per elapsed wake and hit React's limit.
158 if (woke && nextWakeAt !== null) {
159 let nextClockMs = nextWakeAt;
160 for (const wakeAt of wakeTimes) {
161 if (wakeAt > nextClockMs && deadlineStore(wakeAt).getSnapshot()) nextClockMs = wakeAt;
162 }
163 setClockMs(nextClockMs);
164 return nextClockMs;
165 }
166 return clockMs;
168​
169// Live status that says the cwd is not a repository means the checkout was removed.
170export function withoutRemovedCheckout<
171 T extends { readonly branch: string | null; readonly worktreePath: string | null },
172>(thread: T, gitStatus: { readonly isRepo?: boolean | undefined } | null): T {
173 return gitStatus?.isRepo === false ? { ...thread, branch: null, worktreePath: null } : thread;
175​
176export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
177 const [retained, setRetained] = React.useState<{
178 readonly key: string;
179 readonly value: T;
180 } | null>(null);
181 if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) {
182 setRetained({ key, value });
183 }
184 if (value !== null) return value;
185 return key !== null && retained?.key === key ? retained.value : null;
187​
188// Sortable owns drag transforms; replaying committed order would animate drops twice.
189export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
190 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
191​
192// Snoozed rows cannot accept drops without a wake time. Working rows only drag out as chat context.
193​
194export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
195​
196export function resolveSidebarThreadSection(input: {
197 readonly snoozed: boolean;
198 readonly settled: boolean;
199 readonly pinned: boolean;
200}): SidebarSection {
201 if (input.snoozed) return "snoozed";
202 if (input.settled) return "settled";
203 if (input.pinned) return "pinned";
204 return "active";
206​
207const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
208​
209export type SidebarListMarker =
210 | "pinned-header"
211 | "active-placeholder"
212 | "settled-placeholder"
213 | "pinned-divider"
214 | "working-header"
215 | "snoozed-header"
216 | "settled-header";
217​
218export function sidebarMarkerId(marker: SidebarListMarker): string {
219 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
221​
222export type SidebarListItem =
223 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
224 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
225​
226export function sidebarListItemId(item: SidebarListItem): string {
227 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
229​
230function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
231 let section: SidebarSection = "pinned";
232 for (let i = 0; i < index && i < items.length; i += 1) {
233 const item = items[i]!;
234 if (item.kind !== "marker") continue;
235 if (item.marker === "pinned-divider") section = "active";
236 else if (item.marker === "working-header") section = "working";
237 else if (item.marker === "snoozed-header") section = "snoozed";
238 else if (item.marker === "settled-header") section = "settled";
239 }
240 return section;
242​
243type SidebarDropTarget = {
244 readonly section: "pinned" | "active" | "settled";
245 readonly pinnedOrder: readonly string[];
246 readonly activeOrder: readonly string[];
247};
248​
249export function resolveSidebarDropTarget(
250 items: readonly SidebarListItem[],
251 activeKey: string,
252 overId: string,
253): SidebarDropTarget | null {
254 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
255 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
256 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
257 const moved = items.filter((_, index) => index !== activeIndex);
258 moved.splice(overIndex, 0, items[activeIndex]!);
259 const section = sectionAtSidebarSlot(moved, overIndex);
260 if (section === "working" || section === "snoozed") return null;
261 const pinnedOrder: string[] = [];
262 const activeOrder: string[] = [];
263 let currentSection: SidebarSection = "pinned";
264 for (const item of moved) {
265 if (item.kind === "marker") {
266 if (item.marker === "pinned-divider") currentSection = "active";
267 else if (
268 item.marker === "working-header" ||
269 item.marker === "snoozed-header" ||
270 item.marker === "settled-header"
271 )
272 break;
273 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
274 else activeOrder.push(item.key);
275 }
276 return { section, pinnedOrder, activeOrder };
278​
279type SidebarThreadDropPlan =
280 | { readonly kind: "none" }
281 | {
282 readonly kind: "reorder-pinned";
283 readonly order: readonly string[];
284 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
285 }
286 | {
287 readonly kind: "pin";
288 readonly order: readonly string[];
289 readonly orderKey: string | undefined;
290 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
291 }
292 | {
293 readonly kind: "move-active";
294 readonly order: readonly string[] | null;
295 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
296 readonly unpin: boolean;
297 readonly unsettle: boolean;
298 readonly unsnooze: boolean;
299 }
300 | { readonly kind: "settle" };
301​
302export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
303​
304export function resolveSidebarDropVerb(
305 from: SidebarSection,
306 to: SidebarSection | null,
307): SidebarDropVerb | null {
308 if (to === null || to === from || to === "working" || to === "snoozed") return null;
309 if (to === "pinned") return "pin";
310 if (to === "settled") return "settle";
311 if (from === "pinned") return "unpin";
312 if (from === "settled") return "unsettle";
313 return "wake";
315​
316export function resolveSidebarSweepKeys(
317 orderedKeys: readonly string[],
318 originKey: string,
319 targetKey: string,
320 canApply: (key: string) => boolean,
321): string[] {
322 const origin = orderedKeys.indexOf(originKey);
323 const target = orderedKeys.indexOf(targetKey);
324 if (origin === -1 || target === -1) return [];
325 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
327​
328export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
329 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
330 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
331 let key: string | null = null;
332 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
333 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
334 key = row.dataset.threadItem ?? null;
335 }
336 return key;
338​
339export function resolveSidebarReorderableThreadKeys(input: {
340 readonly threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId" | "id">>;
341 readonly serverConfigs: ReadonlyMap<EnvironmentId, Pick<EnvironmentServerConfig, "environment">>;
342 readonly connectedEnvironmentIds: readonly EnvironmentId[];
343}) {
344 const connectedEnvironmentIds = new Set(input.connectedEnvironmentIds);
345 const draggableThreadKeys = new Set<string>();
346 const activeReorderableThreadKeys = new Set<string>();
347​
348 for (const thread of input.threads) {
349 // Config is cached for offline rendering, so its presence does not make a row writable.
350 if (
351 !connectedEnvironmentIds.has(thread.environmentId) ||
352 !input.serverConfigs.has(thread.environmentId)
353 ) {
354 continue;
355 }
356​
357 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
358 activeReorderableThreadKeys.add(threadKey);
359 draggableThreadKeys.add(threadKey);
360 }
361​
362 return { draggableThreadKeys, activeReorderableThreadKeys };
364​
365export function planSidebarThreadDrop(input: {
366 readonly activeKey: string;
367 readonly activeSection: SidebarSection;
368 readonly activePinned?: boolean;
369 readonly activeSettled?: boolean;
370 readonly supportsSettlement?: boolean;
371 readonly target: SidebarDropTarget;
372 readonly pinnedOrder: readonly string[];
373 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
374 readonly reorderableKeys?: ReadonlySet<string>;
375 readonly activeOrder: readonly string[];
376 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
377 readonly activeReorderableKeys?: ReadonlySet<string>;
378 readonly activeTimeOrdered?: boolean;
379}): SidebarThreadDropPlan {
380 const {
381 activeKey,
382 activeSection,
383 activePinned = activeSection === "pinned",
384 activeSettled = activeSection === "settled",
385 target,
386 pinnedOrder,
387 pinnedKeysById,
388 reorderableKeys,
389 activeOrder,
390 activeKeysById,
391 activeReorderableKeys,
392 } = input;
393 if (activeSection === "working") return { kind: "none" };
394 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
395 return { kind: "none" };
396 }
397 const arrange = (
398 order: readonly string[],
399 keysById: ReadonlyMap<string, string | null | undefined>,
400 writable: ReadonlySet<string> | undefined,
401 ) => {
402 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
403 if (!writable.has(activeKey)) return null;
404 const assignments = planPinnedReorder({
405 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
406 keysById,
407 movedId: activeKey,
408 });
409 if (assignments.some(({ id }) => !writable.has(id))) return null;
410​
411 // Keyless Active rows sort before keyed rows; keyless Pinned rows sort after them.
412 // Materializing any row across a frozen keyless boundary cannot persist that position.
413 const assignedIds = new Set(assignments.map(({ id }) => id));
414 let hasFrozenKeylessBefore = false;
415 let hasAssignedBefore = false;
416 for (const id of order) {
417 const isFrozenKeyless = !writable.has(id) && keysById.get(id) == null;
418 const isAssigned = assignedIds.has(id);
419 if (
420 (target.section === "active" && isFrozenKeyless && hasAssignedBefore) ||
421 (target.section === "pinned" && isAssigned && hasFrozenKeylessBefore)
422 ) {
423 return null;
424 }
425​
426 hasFrozenKeylessBefore ||= isFrozenKeyless;
427 hasAssignedBefore ||= isAssigned;
428 }
429​
430 return assignments;
431 };
432 switch (target.section) {
433 case "active": {
434 if (input.activeTimeOrdered) {
435 return activeSection === "active"
436 ? { kind: "none" }
437 : {
438 kind: "move-active",
439 order: null,
440 assignments: [],
441 unpin: activePinned,
442 unsettle: activeSettled,
443 unsnooze: activeSection === "snoozed",
444 };
445 }
446 const order = target.activeOrder;
447 if (
448 activeSection === "active" &&
449 order.length === activeOrder.length &&
450 order.every((key, index) => key === activeOrder[index])
451 ) {
452 return { kind: "none" };
453 }
454 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
455 if (assignments === null) return { kind: "none" };
456 return {
457 kind: "move-active",
458 order,
459 assignments,
460 unpin: activePinned,
461 unsettle: activeSettled,
462 unsnooze: activeSection === "snoozed",
463 };
464 }
465 case "settled":
466 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
467 case "pinned": {
468 const order = target.pinnedOrder;
469 if (
470 activeSection === "pinned" &&
471 order.length === pinnedOrder.length &&
472 order.every((key, index) => key === pinnedOrder[index])
473 ) {
474 return { kind: "none" };
475 }
476 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
477 if (assignments === null) return { kind: "none" };
478 if (activeSection === "pinned") {
479 return assignments.length === 0
480 ? { kind: "none" }
481 : { kind: "reorder-pinned", order, assignments };
482 }
483 return {
484 kind: "pin",
485 order,
486 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
487 extraAssignments: activePinned
488 ? assignments
489 : assignments.filter((assignment) => assignment.id !== activeKey),
490 };
491 }
492 }
494​
495export function applySidebarThreadDrop<
496 T extends Pick<
497 SidebarThreadSummary,
498 | "pinnedAt"
499 | "pinOrderKey"
500 | "activeOrderKey"
501 | "snoozedAt"
502 | "snoozedUntil"
503 | "settledAt"
504 | "settledOverride"
505 | "unsettledAt"
506 >,
507>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
508 const wasSettled = thread.settledOverride === "settled";
509 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
510 if (section === "settled") {
511 return {
512 ...awake,
513 pinnedAt: null,
514 pinOrderKey: null,
515 activeOrderKey: null,
516 settledOverride: "settled",
517 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
518 unsettledAt: null,
519 };
520 }
521 const resumed = wasSettled
522 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
523 : awake;
524 return {
525 ...resumed,
526 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
527 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
528 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
529 };
531​
532type SidebarProject = {
533 id: string;
534 title: string;
535 createdAt?: string | undefined;
536 updatedAt?: string | undefined;
537};
538​
539type ScopedSidebarProject = SidebarProject & {
540 environmentId: string;
541};
542​
543type ScopedSidebarThread = ThreadSortInput & {
544 environmentId: string;
545 projectId: string;
546 archivedAt: string | null;
547};
548​
549type LogicalSidebarProject = SidebarProject & {
550 projectKey: string;
551 memberProjectRefs: readonly {
552 environmentId: string;
553 projectId: string;
554 }[];
555};
556​
557type ThreadTraversalDirection = "previous" | "next";
558​
559/** Exclude only successful deletions from shared-worktree checks. */
560export async function deleteSelectedThreadEntries<
561 TEntry extends { readonly threadKey: string },
562>(input: {
563 entries: readonly TEntry[];
564 delete: (
565 entry: TEntry,
566 deletedThreadKeys: ReadonlySet<string>,
567 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
568}) {
569 const deletedThreadKeys = new Set<string>();
570 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
571​
572 for (const entry of input.entries) {
573 const result = await input.delete(entry, deletedThreadKeys);
574 if (result === null) continue;
575 if (result._tag === "Failure") {
576 if (isAtomCommandInterrupted(result)) break;
577 firstFailure ??= result;
578 continue;
579 }
580 deletedThreadKeys.add(entry.threadKey);
581 }
582​
583 return { deletedThreadKeys, firstFailure };
585​
586/**
587 * `delegatedUnderParent` holds the tasks linked environments run for a thread
588 * the sidebar lists, by thread key; they show under that thread, as subagents do.
589 */
590export function filterSidebarV2VisibleThreads<
591 T extends Pick<SidebarThreadSummary, "archivedAt" | "environmentId" | "id" | "lineage"> & {
592 projectId: string;
593 },
594>(
595 threads: readonly T[],
596 scopedProjectKeys: ReadonlySet<string> | null,
597 delegatedUnderParent: ReadonlySet<string>,
598): T[] {
599 return threads.filter(
600 (thread) =>
601 thread.archivedAt === null &&
602 !isShownUnderParent(
603 { environmentId: thread.environmentId, threadId: thread.id },
604 thread.lineage,
605 delegatedUnderParent,
606 ) &&
607 (scopedProjectKeys === null ||
608 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
609 );
611​
612export function buildBulkTitleRegenerationContextMenuItem(input: {
613 supportedCount: number;
614 actionableCount: number;
615}): ContextMenuItem<"regenerate-title"> | null {
616 if (input.supportedCount === 0) return null;
617 if (input.actionableCount === 0) {
618 return {
619 id: "regenerate-title",
620 label: m(msg("Regenerating… ({count})", { count: input.supportedCount })),
621 disabled: true,
622 };
623 }
624 return {
625 id: "regenerate-title",
626 label: m(msg("Regenerate titles ({count})", { count: input.actionableCount })),
627 };
629​
630export function buildBulkUnpinContextMenuItem(input: {
631 pinnedCount: number;
632}): ContextMenuItem<"unpin"> | null {
633 if (input.pinnedCount === 0) return null;
634 return { id: "unpin", label: m(msg("Unpin ({count})", { count: input.pinnedCount })) };
636​
637export interface ThreadStatusPill {
638 /** A `msg()` string; render it through `useMessages()`. */
639 label: string;
640 colorClass: string;
641 dotClass: string;
642 pulse: boolean;
644​
645type ThreadStatusInput = Pick<
646 SidebarThreadSummary,
647 | "hasActionableProposedPlan"
648 | "hasPendingApprovals"
649 | "hasPendingUserInput"
650 | "pendingSubagentRequest"
651 | "pendingGuestMessageCount"
652 | "interactionMode"
653 | "latestRun"
654 | "runtime"
655> & {
656 lastVisitedAt?: string | null | undefined;
657 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
658 blockedOnThreadWait?: boolean | undefined;
659};
660​
661// Read at event time: subscribing Sidebar to terminal or modifier state re-renders every row.
662export function threadShortcutContext(routeThreadRef: ScopedThreadRef | null) {
663 return {
664 terminalFocus: isTerminalFocused(),
665 terminalOpen:
666 routeThreadRef !== null &&
667 selectThreadTerminalUiState(
668 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
669 routeThreadRef,
670 ).terminalOpen,
671 previewFocus: isPreviewFocused(),
672 previewOpen:
673 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
674 "preview",
675 modelPickerOpen: isModelPickerOpen(),
676 isWeb: !isElectron,
677 isDesktop: isElectron,
678 };
680​
681/** Whether the current modifier combination, including none, has been held unchanged for `delayMs`. */
682function createModifierHoldStore(delayMs: number): ClockStore<boolean> {
683 const listeners = new Set<() => void>();
684 let held = false;
685 let stopDeadline = () => {};
686 let stopModifiers: (() => void) | null = null;
687​
688 const setHeld = (next: boolean) => {
689 if (held === next) return;
690 held = next;
691 for (const listener of listeners) listener();
692 };
693 const onModifiersChange = () => {
694 stopDeadline();
695 const deadline = deadlineStore(deadlineAfter(delayMs));
696 stopDeadline = deadline.subscribe(() => setHeld(true));
697 // A deadline another subscriber already passed never notifies a late joiner.
698 setHeld(deadline.getSnapshot());
699 };
700​
701 return {
702 subscribe: (listener) => {
703 listeners.add(listener);
704 if (stopModifiers === null) {
705 stopModifiers = shortcutModifierStore.subscribe(onModifiersChange);
706 onModifiersChange();
707 }
708 return () => {
709 listeners.delete(listener);
710 if (listeners.size > 0) return;
711 stopModifiers?.();
712 stopModifiers = null;
713 stopDeadline();
714 stopDeadline = () => {};
715 held = false;
716 };
717 },
718 getSnapshot: () => held,
719 };
721​
722const threadJumpModifierHold = createModifierHoldStore(THREAD_JUMP_HINT_SHOW_DELAY_MS);
723​
724function subscribeToThreadJumpHintInputs(listener: () => void): () => void {
725 const unsubscribeHold = threadJumpModifierHold.subscribe(listener);
726 // The snapshot reads the modifiers; the hold stays silent when it is true across a change.
727 const unsubscribeModifiers = shortcutModifierStore.subscribe(listener);
728 const unsubscribeFocus = subscribeToTerminalFocusChanges(listener);
729 const unsubscribeTerminals = useTerminalUiStateStore.subscribe(listener);
730 const unsubscribeRightPanels = useRightPanelStore.subscribe(listener);
731 const unsubscribeModelPicker = subscribeToModelPickerVisibility(listener);
732 return () => {
733 unsubscribeHold();
734 unsubscribeModifiers();
735 unsubscribeFocus();
736 unsubscribeTerminals();
737 unsubscribeRightPanels();
738 unsubscribeModelPicker();
739 };
741​
742/**
743 * Thread jump hints appear once the jump modifier has been held for a moment,
744 * so a quick shortcut never flashes them, and hide as soon as it is released.
745 * The snapshot is the visibility itself, so a quick shortcut never re-renders the caller.
746 */
747export function useThreadJumpHintsVisible(
748 keybindings: ResolvedKeybindingsConfig,
749 routeThreadRef: ScopedThreadRef | null,
750): boolean {
751 return React.useSyncExternalStore(
752 subscribeToThreadJumpHintInputs,
753 () =>
754 threadJumpModifierHold.getSnapshot() &&
755 shouldShowThreadJumpHintsForModifiers(shortcutModifierStore.getSnapshot(), keybindings, {
756 platform: navigator.platform,
757 context: threadShortcutContext(routeThreadRef),
758 }),
759 );
761​
762export function resolveThreadLastVisitedAt(
763 serverLastVisitedAt: string | null | undefined,
764 localLastVisitedAt: string | undefined,
765): string | undefined {
766 // Server visits override local watermarks, including mark-unread rewinds; use local values only on older
767 // servers.
768 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
769 return serverLastVisitedAt ?? undefined;
771​
772export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
773 if (!thread.latestRun?.completedAt) return false;
774 if (thread.latestRun.status === "interrupted" || thread.latestRun.status === "cancelled") {
775 return false;
776 }
777 const completedAt = Date.parse(thread.latestRun.completedAt);
778 if (Number.isNaN(completedAt)) return false;
779 if (!thread.lastVisitedAt) return false;
780​
781 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
782 if (Number.isNaN(lastVisitedAt)) return true;
783 return completedAt > lastVisitedAt;
785​
786// Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0.
787export function isTrailingDoubleClick(detail: number): boolean {
788 return detail > 1;
790​
791function nodeClosest(node: object | null, selector: string): unknown {
792 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
793 return node.closest(selector);
795​
796export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
797 if (target == null || typeof target !== "object") return false;
798 if (nodeClosest(target, "a[href]") !== null) return true;
799 const parent =
800 "parentElement" in target &&
801 target.parentElement !== null &&
802 typeof target.parentElement === "object"
803 ? target.parentElement
804 : null;
805 return nodeClosest(parent, "a[href]") !== null;
807​
808/** The "New thread in" picker opens unless there is one open project or none; then the current context decides. */
809export function shouldCreateNewThreadInCurrentProject(
810 shiftKey: boolean,
811 openProjectGroupCount: number,
812 projectGroupCount: number,
813): boolean {
814 return shiftKey || openProjectGroupCount === 1 || projectGroupCount === 0;
816​
817/**
818 * A sidebar filtered to one project already says where the next thread belongs,
819 * so New skips the picker there. A project grouped across environments keeps the
820 * viewed thread's environment when that thread belongs to the group.
821 */
822export function resolveScopedNewThreadProjectRef<
823 TRef extends { readonly environmentId: string; readonly projectId: string },
824>(input: {
825 shiftKey: boolean;
826 scopedProjectGroups: readonly {
827 readonly environmentId: string;
828 readonly id: string;
829 readonly memberProjectRefs: readonly TRef[];
830 }[];
831 viewed: { readonly environmentId: string; readonly projectId: string } | null | undefined;
832}): TRef | null {
833 const [group, ...otherGroups] = input.scopedProjectGroups;
834 if (input.shiftKey || !group || otherGroups.length > 0) return null;
835 const memberAt = (environmentId: string, projectId: string) =>
836 group.memberProjectRefs.find(
837 (ref) => ref.environmentId === environmentId && ref.projectId === projectId,
838 );
839 return (
840 (input.viewed && memberAt(input.viewed.environmentId, input.viewed.projectId)) ??
841 memberAt(group.environmentId, group.id) ??
842 null
843 );
845​
846export function orderItemsByPreferredIds<TItem, TId>(input: {
847 items: readonly TItem[];
848 preferredIds: readonly TId[];
849 getId: (item: TItem) => TId;
850 getPreferenceIds?: (item: TItem) => readonly TId[];
851}): TItem[] {
852 const { getId, getPreferenceIds, items, preferredIds } = input;
853 if (preferredIds.length === 0) {
854 return [...items];
855 }
856​
857 const indexesByPreferenceId = new Map<TId, number[]>();
858 for (const [index, item] of items.entries()) {
859 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
860 for (const preferenceId of new Set(preferenceIds)) {
861 const indexes = indexesByPreferenceId.get(preferenceId);
862 if (indexes) {
863 indexes.push(index);
864 } else {
865 indexesByPreferenceId.set(preferenceId, [index]);
866 }
867 }
868 }
869​
870 const emittedIndexes = new Set<number>();
871 const ordered = preferredIds.flatMap((id) => {
872 const index = indexesByPreferenceId
873 .get(id)
874 ?.find((candidate) => !emittedIndexes.has(candidate));
875 if (index === undefined) {
876 return [];
877 }
878 emittedIndexes.add(index);
879 return [items[index]!];
880 });
881 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
882 return [...ordered, ...remaining];
884​
885export function resolveAdjacentThreadId<T>(input: {
886 threadIds: readonly T[];
887 currentThreadId: T | null;
888 direction: ThreadTraversalDirection;
889}): T | null {
890 const { currentThreadId, direction, threadIds } = input;
891​
892 if (threadIds.length === 0) {
893 return null;
894 }
895​
896 if (currentThreadId === null) {
897 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
898 }
899​
900 const currentIndex = threadIds.indexOf(currentThreadId);
901 if (currentIndex === -1) {
902 return null;
903 }
904​
905 if (direction === "previous") {
906 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
907 }
908​
909 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
911​
912export type SidebarThreadStatus =
913 | "approval"
914 | "input"
915 | "request"
916 | "preparing"
917 | "working"
918 | "waiting"
919 | "failed"
920 | "limited"
921 | "ready";
922​
923export function shouldRecedeSidebarThread(input: {
924 status: SidebarThreadStatus;
925 isUnread: boolean;
926 isWoke: boolean;
927 isActive: boolean;
928 isSelected: boolean;
929}): boolean {
930 if (
931 input.isActive ||
932 input.isSelected ||
933 input.status === "input" ||
934 input.status === "request"
935 ) {
936 return false;
937 }
938 if (input.status === "preparing" || input.status === "working" || input.status === "waiting") {
939 return true;
940 }
941 if (input.status === "ready" || input.status === "approval") {
942 return !input.isUnread && !input.isWoke;
943 }
944 return false;
946​
947type SidebarThreadStatusInput = Pick<
948 SidebarThreadSummary,
949 | "hasPendingApprovals"
950 | "hasPendingUserInput"
951 | "pendingSubagentRequest"
952 | "pendingGuestMessageCount"
953 | "runtime"
954 | "blockedOnThreadWait"
955>;
956​
957export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
958 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
959 return "approval";
960 }
961 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
962 return "input";
963 }
964 // A guest is waiting on the owner; the agent's own requests come first.
965 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
966 return "request";
967 }
968 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
969 return "waiting";
970 }
971 if (thread.runtime?.status === "preparing") {
972 return "preparing";
973 }
974 if (
975 thread.runtime !== null &&
976 ["queued", "starting", "running", "waiting"].includes(thread.runtime.status)
977 ) {
978 return "working";
979 }
980 if (thread.runtime?.status === "idle") {
981 return "waiting";
982 }
983 if (thread.runtime?.status === "failed") {
984 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
985 }
986 return "ready";
988​
989/** Sidebar row status: a failure the user has already opened settles to ready, like Done. */
990export function resolveSidebarRowStatus(
991 thread: ThreadStatusInput & SidebarThreadStatusInput,
992): SidebarThreadStatus {
993 const status = resolveSidebarThreadStatus(thread);
994 // A runtime failure without a failed run has nothing to date it, so it stays.
995 if (status !== "failed" || thread.latestRun?.status !== "failed") return status;
996 return hasUnseenRunFailure(thread) ? status : "ready";
998​
999/** What the window title says the open thread is doing, in the words its announcer uses. */
1000export function resolveWindowTitleThreadStatus(
1001 thread: SidebarThreadStatusInput,
1002 resolve: MessageResolver = m,
1003): string | null {
1004 // A guest waiting doesn't hide that the agent is still working.
1005 switch (resolveSidebarThreadStatus({ ...thread, pendingGuestMessageCount: 0 })) {
1006 case "approval":
1007 return resolve(THREAD_STATUS_TEXT.approval);
1008 case "input":
1009 return resolve(THREAD_STATUS_TEXT.input);
1010 case "preparing":
1011 case "working":
1012 return resolve(THREAD_STATUS_TEXT.working);
1013 case "waiting":
1014 // Waiting on a child thread is still this turn, so it must not read as finished.
1015 return thread.runtime?.status === "running" ? resolve(THREAD_STATUS_TEXT.working) : null;
1016 default:
1017 return null;
1020​
1021/**
1022 * The dot on a closed boring-sidebar folder: the most urgent state among its
1023 * hidden threads. Waiting threads stay quiet, like their rows.
1024 */
1025export function resolveSidebarFolderDot(
1026 threads: ReadonlyArray<ThreadStatusInput & SidebarThreadStatusInput>,
1027): "attention" | "failed" | "unread" | "working" | null {
1028 const statuses = new Set(threads.map(resolveSidebarRowStatus));
1029 if (
1030 statuses.has("input") ||
1031 statuses.has("approval") ||
1032 statuses.has("request") ||
1033 statuses.has("limited")
1034 ) {
1035 return "attention";
1037 if (statuses.has("failed")) return "failed";
1038 // Rows show Done only for ready threads, so the dot follows the same rule.
1039 const hasUnread = threads.some(
1040 (thread) => resolveSidebarRowStatus(thread) === "ready" && hasUnseenCompletion(thread),
1041 );
1042 if (hasUnread) return "unread";
1043 if (statuses.has("working") || statuses.has("preparing")) return "working";
1044 return null;
1046​
1047/**
1048 * Keys the old per-project sidebar saved folder open state under, most
1049 * specific first, for `resolveProjectExpanded`. Boring folders read and write
1050 * the same keys, so a legacy user's closed folders stay closed after regrouping.
1051 */
1052export function sidebarFolderExpansionKeys(group: {
1053 readonly projectKey: string;
1054 readonly memberProjects: ReadonlyArray<{
1055 readonly physicalProjectKey: string;
1056 readonly workspaceRoot: string;
1057 }>;
1058}): string[] {
1059 return [
1060 group.projectKey,
1061 ...group.memberProjects.map((member) => member.physicalProjectKey),
1062 ...group.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)),
1063 ];
1065​
1066/**
1067 * Boring sidebar folders. Folders follow `groups` order and threads keep their
1068 * input order. A project with no threads gets a folder only when `keepEmpty` says so.
1069 * A thread whose project is in no group has no folder and is left out.
1070 */
1071export function groupSidebarThreadsByProject<
1072 TGroup extends {
1073 readonly memberProjectRefs: ReadonlyArray<{
1074 readonly environmentId: EnvironmentId;
1075 readonly projectId: string;
1076 }>;
1077 },
1078 TThread extends Pick<SidebarThreadSummary, "environmentId" | "projectId">,
1080 groups: readonly TGroup[],
1081 threads: readonly TThread[],
1082 keepEmpty: (group: TGroup) => boolean,
1083): Array<{ group: TGroup; threads: TThread[] }> {
1084 const folders = groups.map((group) => ({ group, threads: [] as TThread[] }));
1085 const folderByProject = new Map<string, (typeof folders)[number]>();
1086 for (const folder of folders) {
1087 for (const ref of folder.group.memberProjectRefs) {
1088 folderByProject.set(`${ref.environmentId}:${ref.projectId}`, folder);
1091 for (const thread of threads) {
1092 folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread);
1094 return folders.filter((folder) => folder.threads.length > 0 || keepEmpty(folder.group));
1096​
1097export type SidebarV2TopStatusKind =
1098 | "approval"
1099 | "done"
1100 | "failed"
1101 | "limited"
1102 | "input"
1103 | "request"
1104 | "waiting"
1105 | "woke"
1106 | "working";
1107​
1108export function firstValidTimestampMs(
1109 ...candidates: ReadonlyArray<string | null | undefined>
1110): number {
1111 for (const candidate of candidates) {
1112 if (candidate == null) continue;
1113 const parsed = Date.parse(candidate);
1114 if (!Number.isNaN(parsed)) return parsed;
1116 return 0;
1118​
1119export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1120export {
1121 sortInboxThreadsByReturn,
1122 sortWorkingThreadsBySend,
1123} from "@t3tools/client-runtime/state/thread-inbox";
1124​
1125export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
1126export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1127​
1128const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
1129​
1130/**
1131 * Sidebar search results: title, branch, and pull request matches ranked as
1132 * the command palette ranks them, then threads listed only because their
1133 * messages match, in `contentMatchKeys` order.
1134 */
1135export function searchSidebarThreads<
1136 T extends ThreadSearchShell & {
1137 readonly environmentId: EnvironmentId;
1138 readonly id: ThreadId;
1139 },
1141 threads: readonly T[],
1142 query: string,
1143 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1144 now = Date.now(),
1145): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
1146 const normalizedQuery = foldSearchQuery(query);
1147 if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
1148 const titleMatches = rankSearchItems(threads, (thread, options) =>
1149 scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
1150 ...options,
1151 picks: false,
1152 }),
1153 ).map(({ item }) => item);
1154 const listed = new Set(titleMatches);
1155 // In the order the server ranked their messages, as the palette lists them.
1156 const threadByKey = new Map(
1157 threads.map((thread) => [
1158 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1159 thread,
1160 ]),
1161 );
1162 const contentMatches = [...contentMatchKeys].flatMap((key) => {
1163 const thread = threadByKey.get(key);
1164 return thread && !listed.has(thread) ? [thread] : [];
1165 });
1166 return { titleMatches, contentMatches };
1168​
1169export function pullRequestMatchesSearchQuery(
1170 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1171 query: string,
1172): boolean {
1173 const normalizedQuery = normalizeSearchText(query);
1174 if (normalizedQuery.length === 0) return false;
1175 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1176 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1178​
1179export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1180 items: readonly TItem[];
1181 query: string;
1182 matches: (item: TItem, query: string) => boolean;
1183}): readonly TItem[] {
1184 const query = input.query.trim();
1185 if (query.length === 0) return input.items;
1186 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1188​
1189interface SidebarProjectScopeMenuState {
1190 readonly open: boolean;
1191 readonly query: string;
1193​
1194type SidebarProjectScopeMenuAction =
1195 | { readonly type: "query-changed"; readonly query: string }
1196 | { readonly type: "open-changed"; readonly open: boolean }
1197 | { readonly type: "project-settings-opened" };
1198​
1199export function reduceSidebarProjectScopeMenuState(
1200 state: SidebarProjectScopeMenuState,
1201 action: SidebarProjectScopeMenuAction,
1202): SidebarProjectScopeMenuState {
1203 switch (action.type) {
1204 case "query-changed":
1205 return { ...state, query: action.query };
1206 case "open-changed":
1207 return { open: action.open, query: "" };
1208 case "project-settings-opened":
1209 return { open: false, query: "" };
1212​
1213export function resolveWorkingStartedAt(
1214 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1215): string | null {
1216 return resolveThreadWorkingStartedAt(thread);
1218​
1219export function resolveThreadStatusPill(input: {
1220 thread: ThreadStatusInput;
1221}): ThreadStatusPill | null {
1222 const { thread } = input;
1223​
1224 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1225 return {
1226 label: msg("Pending Approval"),
1227 colorClass: "text-amber-600 dark:text-amber-300/90",
1228 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1229 pulse: false,
1230 };
1232​
1233 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1234 return {
1235 label: msg("Awaiting Input"),
1236 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1237 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1238 pulse: false,
1239 };
1241​
1242 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1243 return {
1244 label: msg("Guest Request"),
1245 colorClass: "text-guest-foreground",
1246 dotClass: "bg-guest",
1247 pulse: false,
1248 };
1250​
1251 if (
1252 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1253 thread.runtime?.status === "waiting"
1254 ) {
1255 return {
1256 label: msg("Working"),
1257 colorClass: "text-sky-600 dark:text-sky-300/80",
1258 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1259 pulse: true,
1260 };
1262​
1263 if (
1264 thread.runtime?.status === "preparing" ||
1265 thread.runtime?.status === "starting" ||
1266 thread.runtime?.status === "queued"
1267 ) {
1268 return {
1269 label: msg("Connecting"),
1270 colorClass: "text-sky-600 dark:text-sky-300/80",
1271 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1272 pulse: true,
1273 };
1275​
1276 const waiting = {
1277 label: msg("Waiting"),
1278 colorClass: "text-sidebar-muted-foreground",
1279 dotClass: "bg-sidebar-muted-foreground",
1280 pulse: false,
1281 };
1282 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) return waiting;
1283​
1284 // A failed run goes to the inbox even while background work holds the thread.
1285 if (hasUnseenRunFailure(thread)) {
1286 return {
1287 label: msg("Failed"),
1288 colorClass: "text-red-600 dark:text-red-300/90",
1289 dotClass: "bg-red-500 dark:bg-red-300/90",
1290 pulse: false,
1291 };
1293​
1294 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return waiting;
1295​
1296 const hasPlanReadyPrompt =
1297 !thread.hasPendingUserInput &&
1298 thread.interactionMode === "plan" &&
1299 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1300 thread.hasActionableProposedPlan;
1301 if (hasPlanReadyPrompt) {
1302 return {
1303 label: msg("Plan Ready"),
1304 colorClass: "text-violet-600 dark:text-violet-300/90",
1305 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1306 pulse: false,
1307 };
1309​
1310 if (hasUnseenCompletion(thread)) {
1311 return {
1312 label: msg("Completed"),
1313 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1314 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1315 pulse: false,
1316 };
1318​
1319 return null;
1321​
1322export function getFallbackThreadIdAfterDelete<
1323 T extends Pick<
1324 Thread,
1325 "id" | "projectId" | "createdAt" | "updatedAt" | "settledOverride" | "lineage"
1326 > &
1327 ThreadSortInput &
1328 ThreadSnoozeShell &
1329 Pick<Thread, "environmentId">,
1330>(input: {
1331 threads: readonly T[];
1332 deletedThreadId: T["id"];
1333 sortOrder: SidebarThreadSortOrder;
1334 now: string;
1335 deletedThreadIds?: ReadonlySet<T["id"]>;
1336 delegatedUnderParent: ReadonlySet<string>;
1337}): T["id"] | null {
1338 const { deletedThreadId, deletedThreadIds, sortOrder, now, threads, delegatedUnderParent } =
1339 input;
1340 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1341 if (!deletedThread) {
1342 return null;
1344​
1345 return (
1346 sortThreads(
1347 threads.filter(
1348 (thread) =>
1349 thread.projectId === deletedThread.projectId &&
1350 thread.id !== deletedThreadId &&
1351 !deletedThreadIds?.has(thread.id) &&
1352 thread.settledOverride !== "settled" &&
1353 !effectiveSnoozed(thread, { now }) &&
1354 !isShownUnderParent(
1355 { environmentId: thread.environmentId, threadId: thread.id },
1356 thread.lineage,
1357 delegatedUnderParent,
1358 ),
1359 ),
1360 sortOrder,
1361 )[0]?.id ?? null
1362 );
1364function getProjectSortTimestamp(
1365 project: SidebarProject,
1366 projectThreads: readonly ThreadSortInput[],
1367 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1368): number {
1369 if (projectThreads.length > 0) {
1370 return projectThreads.reduce(
1371 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1372 Number.NEGATIVE_INFINITY,
1373 );
1375​
1376 if (sortOrder === "created_at") {
1377 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1379 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1381​
1382function sortProjectsByActivity<TProject extends SidebarProject>(
1383 projects: readonly TProject[],
1384 sortOrder: SidebarProjectSortOrder,
1385 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1386 compareTies: (left: TProject, right: TProject) => number,
1387): TProject[] {
1388 if (sortOrder === "manual") {
1389 return [...projects];
1391​
1392 // Project timestamps scan all threads; compute once per project instead of per comparison.
1393 return projects
1394 .map((project) => ({
1395 project,
1396 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1397 }))
1398 .sort((left, right) => {
1399 const byTimestamp =
1400 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1401 return byTimestamp || compareTies(left.project, right.project);
1402 })
1403 .map(({ project }) => project);
1405​
1406export function sortLogicalProjectsForSidebar<
1407 TProject extends LogicalSidebarProject,
1408 TThread extends ScopedSidebarThread,
1410 projects: readonly TProject[],
1411 threads: readonly TThread[],
1412 sortOrder: SidebarProjectSortOrder,
1413): TProject[] {
1414 const groupKeyByProjectRef = new Map(
1415 projects.flatMap((project) =>
1416 project.memberProjectRefs.map(
1417 (projectRef) =>
1418 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1419 ),
1420 ),
1421 );
1422 const threadsByProjectKey = new Map<string, TThread[]>();
1423 for (const thread of threads) {
1424 if (thread.archivedAt !== null) continue;
1425 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1426 if (!projectKey) continue;
1427 const existing = threadsByProjectKey.get(projectKey);
1428 if (existing) {
1429 existing.push(thread);
1430 } else {
1431 threadsByProjectKey.set(projectKey, [thread]);
1434​
1435 return sortProjectsByActivity(
1436 projects,
1437 sortOrder,
1438 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1439 (left, right) =>
1440 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1441 );
1443​
1444export function sortSidebarV2ProjectGroups<
1445 TProject extends LogicalSidebarProject,
1446 TThread extends ScopedSidebarThread &
1447 Pick<SidebarThreadSummary, "environmentId" | "id" | "lineage">,
1449 projects: readonly TProject[],
1450 threads: readonly TThread[],
1451 sortOrder: SidebarProjectSortOrder,
1452 delegatedUnderParent: ReadonlySet<string>,
1453): TProject[] {
1454 return sortLogicalProjectsForSidebar(
1455 projects,
1456 filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent),
1457 sortOrder,
1458 );
1460​
1461export function sortScopedProjectsForSidebar<
1462 TProject extends ScopedSidebarProject,
1463 TThread extends ScopedSidebarThread,
1465 projects: readonly TProject[],
1466 threads: readonly TThread[],
1467 sortOrder: SidebarProjectSortOrder,
1468): TProject[] {
1469 const scopedKey = (environmentId: string, projectId: string) =>
1470 `${environmentId}\u0000${projectId}`;
1471 const threadsByProject = new Map<string, TThread[]>();
1472 for (const thread of threads) {
1473 if (thread.archivedAt !== null) {
1474 continue;
1476 const key = scopedKey(thread.environmentId, thread.projectId);
1477 const existing = threadsByProject.get(key) ?? [];
1478 existing.push(thread);
1479 threadsByProject.set(key, existing);
1481​
1482 return sortProjectsByActivity(
1483 projects,
1484 sortOrder,
1485 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1486 (left, right) =>
1487 left.title.localeCompare(right.title) ||
1488 left.environmentId.localeCompare(right.environmentId) ||
1489 left.id.localeCompare(right.id),
1490 );