The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; |
| 2 | import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; |
| 3 | import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models"; |
| 4 | import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; |
| 5 | import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; |
| 6 | import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests"; |
| 7 | import * as React from "react"; |
| 8 | import { msg } from "gt-react"; |
| 9 | import { m, type MessageResolver } from "../i18n/messages"; |
| 10 | import { |
| 11 | isAtomCommandInterrupted, |
| 12 | type AtomCommandResult, |
| 13 | } from "@t3tools/client-runtime/state/runtime"; |
| 14 | import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable"; |
| 15 | import { |
| 16 | threadSearchMatchKey, |
| 17 | threadSearchSubject, |
| 18 | type ThreadSearchShell, |
| 19 | } from "@t3tools/client-runtime/state/thread-search"; |
| 20 | import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; |
| 21 | import { |
| 22 | type ContextMenuItem, |
| 23 | type EnvironmentId, |
| 24 | type ResolvedKeybindingsConfig, |
| 25 | type ScopedThreadRef, |
| 26 | type ThreadId, |
| 27 | } from "@t3tools/contracts"; |
| 28 | import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; |
| 29 | import type { AsyncResult } from "effect/reactivity"; |
| 30 | import { |
| 31 | effectiveSnoozed, |
| 32 | hasUnseenRunFailure, |
| 33 | type ThreadSnoozeShell, |
| 34 | } from "@t3tools/client-runtime/state/thread-settled"; |
| 35 | import { |
| 36 | getThreadSortTimestamp, |
| 37 | planPinnedReorder, |
| 38 | sortThreads, |
| 39 | toSortableTimestamp, |
| 40 | type ThreadSortInput, |
| 41 | } from "@t3tools/client-runtime/state/thread-sort"; |
| 42 | import type { SidebarThreadSummary, Thread } from "../types"; |
| 43 | import { normalizeSearchText } from "../lib/utils"; |
| 44 | import { isLatestRunSettled } from "../session-logic"; |
| 45 | import { THREAD_STATUS_TEXT } from "@t3tools/client-runtime/state/thread-activity-announcement"; |
| 46 | import { observeIntersection } from "../lib/observeIntersection"; |
| 47 | import { deadlineAfter, deadlineStore, type ClockStore } from "@t3tools/client-runtime/clock"; |
| 48 | import { useDeadlinePassed } from "../hooks/useDeadline"; |
| 49 | import { legacyProjectCwdPreferenceKey } from "../uiStateStore"; |
| 50 | import { isElectron } from "../env"; |
| 51 | import { shouldShowThreadJumpHintsForModifiers } from "../keybindings"; |
| 52 | import { isTerminalFocused, subscribeToTerminalFocusChanges } from "../lib/terminalFocus"; |
| 53 | import { isPreviewFocused } from "../lib/previewFocus"; |
| 54 | import { isModelPickerOpen, subscribeToModelPickerVisibility } from "../modelPickerVisibility"; |
| 55 | import { shortcutModifierStore } from "../shortcutModifierState"; |
| 56 | import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; |
| 57 | import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; |
| 58 | |
| 59 | export 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 | ); |
| 73 | } |
| 74 | |
| 75 | export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200; |
| 76 | |
| 77 | export 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 | }; |
| 87 | } |
| 88 | |
| 89 | // Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load. |
| 90 | const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160; |
| 91 | |
| 92 | export 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 | }; |
| 112 | } |
| 113 | |
| 114 | const fileDragClears = new Set<(active: false) => void>(); |
| 115 | function clearFileDrags() { |
| 116 | const clears = [...fileDragClears]; |
| 117 | fileDragClears.clear(); |
| 118 | for (const clear of clears) clear(false); |
| 119 | } |
| 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 | */ |
| 125 | export 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); |
| 136 | } |
| 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 | */ |
| 142 | export 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; |
| 167 | } |
| 168 | |
| 169 | // Live status that says the cwd is not a repository means the checkout was removed. |
| 170 | export 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; |
| 174 | } |
| 175 | |
| 176 | export 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; |
| 186 | } |
| 187 | |
| 188 | // Sortable owns drag transforms; replaying committed order would animate drops twice. |
| 189 | export 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 | |
| 194 | export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled"; |
| 195 | |
| 196 | export 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"; |
| 205 | } |
| 206 | |
| 207 | const SIDEBAR_MARKER_PREFIX = "sidebar-marker-"; |
| 208 | |
| 209 | export type SidebarListMarker = |
| 210 | | "pinned-header" |
| 211 | | "active-placeholder" |
| 212 | | "settled-placeholder" |
| 213 | | "pinned-divider" |
| 214 | | "working-header" |
| 215 | | "snoozed-header" |
| 216 | | "settled-header"; |
| 217 | |
| 218 | export function sidebarMarkerId(marker: SidebarListMarker): string { |
| 219 | return `${SIDEBAR_MARKER_PREFIX}${marker}`; |
| 220 | } |
| 221 | |
| 222 | export type SidebarListItem = |
| 223 | | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection } |
| 224 | | { readonly kind: "marker"; readonly marker: SidebarListMarker }; |
| 225 | |
| 226 | export function sidebarListItemId(item: SidebarListItem): string { |
| 227 | return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker); |
| 228 | } |
| 229 | |
| 230 | function 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; |
| 241 | } |
| 242 | |
| 243 | type SidebarDropTarget = { |
| 244 | readonly section: "pinned" | "active" | "settled"; |
| 245 | readonly pinnedOrder: readonly string[]; |
| 246 | readonly activeOrder: readonly string[]; |
| 247 | }; |
| 248 | |
| 249 | export 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 }; |
| 277 | } |
| 278 | |
| 279 | type 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 | |
| 302 | export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake"; |
| 303 | |
| 304 | export 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"; |
| 314 | } |
| 315 | |
| 316 | export 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); |
| 326 | } |
| 327 | |
| 328 | export 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; |
| 337 | } |
| 338 | |
| 339 | export 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 }; |
| 363 | } |
| 364 | |
| 365 | export 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 | } |
| 493 | } |
| 494 | |
| 495 | export 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 | }; |
| 530 | } |
| 531 | |
| 532 | type SidebarProject = { |
| 533 | id: string; |
| 534 | title: string; |
| 535 | createdAt?: string | undefined; |
| 536 | updatedAt?: string | undefined; |
| 537 | }; |
| 538 | |
| 539 | type ScopedSidebarProject = SidebarProject & { |
| 540 | environmentId: string; |
| 541 | }; |
| 542 | |
| 543 | type ScopedSidebarThread = ThreadSortInput & { |
| 544 | environmentId: string; |
| 545 | projectId: string; |
| 546 | archivedAt: string | null; |
| 547 | }; |
| 548 | |
| 549 | type LogicalSidebarProject = SidebarProject & { |
| 550 | projectKey: string; |
| 551 | memberProjectRefs: readonly { |
| 552 | environmentId: string; |
| 553 | projectId: string; |
| 554 | }[]; |
| 555 | }; |
| 556 | |
| 557 | type ThreadTraversalDirection = "previous" | "next"; |
| 558 | |
| 559 | /** Exclude only successful deletions from shared-worktree checks. */ |
| 560 | export 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 }; |
| 584 | } |
| 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 | */ |
| 590 | export 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 | ); |
| 610 | } |
| 611 | |
| 612 | export 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 | }; |
| 628 | } |
| 629 | |
| 630 | export 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 })) }; |
| 635 | } |
| 636 | |
| 637 | export interface ThreadStatusPill { |
| 638 | /** A `msg()` string; render it through `useMessages()`. */ |
| 639 | label: string; |
| 640 | colorClass: string; |
| 641 | dotClass: string; |
| 642 | pulse: boolean; |
| 643 | } |
| 644 | |
| 645 | type 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. |
| 662 | export 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 | }; |
| 679 | } |
| 680 | |
| 681 | /** Whether the current modifier combination, including none, has been held unchanged for `delayMs`. */ |
| 682 | function 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 | }; |
| 720 | } |
| 721 | |
| 722 | const threadJumpModifierHold = createModifierHoldStore(THREAD_JUMP_HINT_SHOW_DELAY_MS); |
| 723 | |
| 724 | function 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 | }; |
| 740 | } |
| 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 | */ |
| 747 | export 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 | ); |
| 760 | } |
| 761 | |
| 762 | export 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; |
| 770 | } |
| 771 | |
| 772 | export 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; |
| 784 | } |
| 785 | |
| 786 | // Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0. |
| 787 | export function isTrailingDoubleClick(detail: number): boolean { |
| 788 | return detail > 1; |
| 789 | } |
| 790 | |
| 791 | function 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); |
| 794 | } |
| 795 | |
| 796 | export 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; |
| 806 | } |
| 807 | |
| 808 | /** The "New thread in" picker opens unless there is one open project or none; then the current context decides. */ |
| 809 | export function shouldCreateNewThreadInCurrentProject( |
| 810 | shiftKey: boolean, |
| 811 | openProjectGroupCount: number, |
| 812 | projectGroupCount: number, |
| 813 | ): boolean { |
| 814 | return shiftKey || openProjectGroupCount === 1 || projectGroupCount === 0; |
| 815 | } |
| 816 | |
| 817 | export function orderItemsByPreferredIds<TItem, TId>(input: { |
| 818 | items: readonly TItem[]; |
| 819 | preferredIds: readonly TId[]; |
| 820 | getId: (item: TItem) => TId; |
| 821 | getPreferenceIds?: (item: TItem) => readonly TId[]; |
| 822 | }): TItem[] { |
| 823 | const { getId, getPreferenceIds, items, preferredIds } = input; |
| 824 | if (preferredIds.length === 0) { |
| 825 | return [...items]; |
| 826 | } |
| 827 | |
| 828 | const indexesByPreferenceId = new Map<TId, number[]>(); |
| 829 | for (const [index, item] of items.entries()) { |
| 830 | const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)]; |
| 831 | for (const preferenceId of new Set(preferenceIds)) { |
| 832 | const indexes = indexesByPreferenceId.get(preferenceId); |
| 833 | if (indexes) { |
| 834 | indexes.push(index); |
| 835 | } else { |
| 836 | indexesByPreferenceId.set(preferenceId, [index]); |
| 837 | } |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | const emittedIndexes = new Set<number>(); |
| 842 | const ordered = preferredIds.flatMap((id) => { |
| 843 | const index = indexesByPreferenceId |
| 844 | .get(id) |
| 845 | ?.find((candidate) => !emittedIndexes.has(candidate)); |
| 846 | if (index === undefined) { |
| 847 | return []; |
| 848 | } |
| 849 | emittedIndexes.add(index); |
| 850 | return [items[index]!]; |
| 851 | }); |
| 852 | const remaining = items.filter((_, index) => !emittedIndexes.has(index)); |
| 853 | return [...ordered, ...remaining]; |
| 854 | } |
| 855 | |
| 856 | export function resolveAdjacentThreadId<T>(input: { |
| 857 | threadIds: readonly T[]; |
| 858 | currentThreadId: T | null; |
| 859 | direction: ThreadTraversalDirection; |
| 860 | }): T | null { |
| 861 | const { currentThreadId, direction, threadIds } = input; |
| 862 | |
| 863 | if (threadIds.length === 0) { |
| 864 | return null; |
| 865 | } |
| 866 | |
| 867 | if (currentThreadId === null) { |
| 868 | return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null); |
| 869 | } |
| 870 | |
| 871 | const currentIndex = threadIds.indexOf(currentThreadId); |
| 872 | if (currentIndex === -1) { |
| 873 | return null; |
| 874 | } |
| 875 | |
| 876 | if (direction === "previous") { |
| 877 | return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null; |
| 878 | } |
| 879 | |
| 880 | return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null; |
| 881 | } |
| 882 | |
| 883 | export type SidebarThreadStatus = |
| 884 | | "approval" |
| 885 | | "input" |
| 886 | | "request" |
| 887 | | "preparing" |
| 888 | | "working" |
| 889 | | "waiting" |
| 890 | | "failed" |
| 891 | | "limited" |
| 892 | | "ready"; |
| 893 | |
| 894 | export function shouldRecedeSidebarThread(input: { |
| 895 | status: SidebarThreadStatus; |
| 896 | isUnread: boolean; |
| 897 | isWoke: boolean; |
| 898 | isActive: boolean; |
| 899 | isSelected: boolean; |
| 900 | }): boolean { |
| 901 | if ( |
| 902 | input.isActive || |
| 903 | input.isSelected || |
| 904 | input.status === "input" || |
| 905 | input.status === "request" |
| 906 | ) { |
| 907 | return false; |
| 908 | } |
| 909 | if (input.status === "preparing" || input.status === "working" || input.status === "waiting") { |
| 910 | return true; |
| 911 | } |
| 912 | if (input.status === "ready" || input.status === "approval") { |
| 913 | return !input.isUnread && !input.isWoke; |
| 914 | } |
| 915 | return false; |
| 916 | } |
| 917 | |
| 918 | type SidebarThreadStatusInput = Pick< |
| 919 | SidebarThreadSummary, |
| 920 | | "hasPendingApprovals" |
| 921 | | "hasPendingUserInput" |
| 922 | | "pendingSubagentRequest" |
| 923 | | "pendingGuestMessageCount" |
| 924 | | "runtime" |
| 925 | | "blockedOnThreadWait" |
| 926 | >; |
| 927 | |
| 928 | export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus { |
| 929 | if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") { |
| 930 | return "approval"; |
| 931 | } |
| 932 | if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") { |
| 933 | return "input"; |
| 934 | } |
| 935 | // A guest is waiting on the owner; the agent's own requests come first. |
| 936 | if ((thread.pendingGuestMessageCount ?? 0) > 0) { |
| 937 | return "request"; |
| 938 | } |
| 939 | if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) { |
| 940 | return "waiting"; |
| 941 | } |
| 942 | if (thread.runtime?.status === "preparing") { |
| 943 | return "preparing"; |
| 944 | } |
| 945 | if ( |
| 946 | thread.runtime !== null && |
| 947 | ["queued", "starting", "running", "waiting"].includes(thread.runtime.status) |
| 948 | ) { |
| 949 | return "working"; |
| 950 | } |
| 951 | if (thread.runtime?.status === "idle") { |
| 952 | return "waiting"; |
| 953 | } |
| 954 | if (thread.runtime?.status === "failed") { |
| 955 | return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed"; |
| 956 | } |
| 957 | return "ready"; |
| 958 | } |
| 959 | |
| 960 | /** Sidebar row status: a failure the user has already opened settles to ready, like Done. */ |
| 961 | export function resolveSidebarRowStatus( |
| 962 | thread: ThreadStatusInput & SidebarThreadStatusInput, |
| 963 | ): SidebarThreadStatus { |
| 964 | const status = resolveSidebarThreadStatus(thread); |
| 965 | // A runtime failure without a failed run has nothing to date it, so it stays. |
| 966 | if (status !== "failed" || thread.latestRun?.status !== "failed") return status; |
| 967 | return hasUnseenRunFailure(thread) ? status : "ready"; |
| 968 | } |
| 969 | |
| 970 | /** What the window title says the open thread is doing, in the words its announcer uses. */ |
| 971 | export function resolveWindowTitleThreadStatus( |
| 972 | thread: SidebarThreadStatusInput, |
| 973 | resolve: MessageResolver = m, |
| 974 | ): string | null { |
| 975 | // A guest waiting doesn't hide that the agent is still working. |
| 976 | switch (resolveSidebarThreadStatus({ ...thread, pendingGuestMessageCount: 0 })) { |
| 977 | case "approval": |
| 978 | return resolve(THREAD_STATUS_TEXT.approval); |
| 979 | case "input": |
| 980 | return resolve(THREAD_STATUS_TEXT.input); |
| 981 | case "preparing": |
| 982 | case "working": |
| 983 | return resolve(THREAD_STATUS_TEXT.working); |
| 984 | case "waiting": |
| 985 | // Waiting on a child thread is still this turn, so it must not read as finished. |
| 986 | return thread.runtime?.status === "running" ? resolve(THREAD_STATUS_TEXT.working) : null; |
| 987 | default: |
| 988 | return null; |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | /** |
| 993 | * The dot on a closed boring-sidebar folder: the most urgent state among its |
| 994 | * hidden threads. Waiting threads stay quiet, like their rows. |
| 995 | */ |
| 996 | export function resolveSidebarFolderDot( |
| 997 | threads: ReadonlyArray<ThreadStatusInput & SidebarThreadStatusInput>, |
| 998 | ): "attention" | "failed" | "unread" | "working" | null { |
| 999 | const statuses = new Set(threads.map(resolveSidebarRowStatus)); |
| 1000 | if ( |
| 1001 | statuses.has("input") || |
| 1002 | statuses.has("approval") || |
| 1003 | statuses.has("request") || |
| 1004 | statuses.has("limited") |
| 1005 | ) { |
| 1006 | return "attention"; |
| 1007 | } |
| 1008 | if (statuses.has("failed")) return "failed"; |
| 1009 | // Rows show Done only for ready threads, so the dot follows the same rule. |
| 1010 | const hasUnread = threads.some( |
| 1011 | (thread) => resolveSidebarRowStatus(thread) === "ready" && hasUnseenCompletion(thread), |
| 1012 | ); |
| 1013 | if (hasUnread) return "unread"; |
| 1014 | if (statuses.has("working") || statuses.has("preparing")) return "working"; |
| 1015 | return null; |
| 1016 | } |
| 1017 | |
| 1018 | /** |
| 1019 | * Keys the old per-project sidebar saved folder open state under, most |
| 1020 | * specific first, for `resolveProjectExpanded`. Boring folders read and write |
| 1021 | * the same keys, so a legacy user's closed folders stay closed after regrouping. |
| 1022 | */ |
| 1023 | export function sidebarFolderExpansionKeys(group: { |
| 1024 | readonly projectKey: string; |
| 1025 | readonly memberProjects: ReadonlyArray<{ |
| 1026 | readonly physicalProjectKey: string; |
| 1027 | readonly workspaceRoot: string; |
| 1028 | }>; |
| 1029 | }): string[] { |
| 1030 | return [ |
| 1031 | group.projectKey, |
| 1032 | ...group.memberProjects.map((member) => member.physicalProjectKey), |
| 1033 | ...group.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)), |
| 1034 | ]; |
| 1035 | } |
| 1036 | |
| 1037 | /** |
| 1038 | * Boring sidebar folders. Folders follow `groups` order and threads keep their |
| 1039 | * input order. A project with no threads gets a folder only when `keepEmpty` says so. |
| 1040 | * A thread whose project is in no group has no folder and is left out. |
| 1041 | */ |
| 1042 | export function groupSidebarThreadsByProject< |
| 1043 | TGroup extends { |
| 1044 | readonly memberProjectRefs: ReadonlyArray<{ |
| 1045 | readonly environmentId: EnvironmentId; |
| 1046 | readonly projectId: string; |
| 1047 | }>; |
| 1048 | }, |
| 1049 | TThread extends Pick<SidebarThreadSummary, "environmentId" | "projectId">, |
| 1050 | >( |
| 1051 | groups: readonly TGroup[], |
| 1052 | threads: readonly TThread[], |
| 1053 | keepEmpty: (group: TGroup) => boolean, |
| 1054 | ): Array<{ group: TGroup; threads: TThread[] }> { |
| 1055 | const folders = groups.map((group) => ({ group, threads: [] as TThread[] })); |
| 1056 | const folderByProject = new Map<string, (typeof folders)[number]>(); |
| 1057 | for (const folder of folders) { |
| 1058 | for (const ref of folder.group.memberProjectRefs) { |
| 1059 | folderByProject.set(`${ref.environmentId}:${ref.projectId}`, folder); |
| 1060 | } |
| 1061 | } |
| 1062 | for (const thread of threads) { |
| 1063 | folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread); |
| 1064 | } |
| 1065 | return folders.filter((folder) => folder.threads.length > 0 || keepEmpty(folder.group)); |
| 1066 | } |
| 1067 | |
| 1068 | export type SidebarV2TopStatusKind = |
| 1069 | | "approval" |
| 1070 | | "done" |
| 1071 | | "failed" |
| 1072 | | "limited" |
| 1073 | | "input" |
| 1074 | | "request" |
| 1075 | | "waiting" |
| 1076 | | "woke" |
| 1077 | | "working"; |
| 1078 | |
| 1079 | export function firstValidTimestampMs( |
| 1080 | ...candidates: ReadonlyArray<string | null | undefined> |
| 1081 | ): number { |
| 1082 | for (const candidate of candidates) { |
| 1083 | if (candidate == null) continue; |
| 1084 | const parsed = Date.parse(candidate); |
| 1085 | if (!Number.isNaN(parsed)) return parsed; |
| 1086 | } |
| 1087 | return 0; |
| 1088 | } |
| 1089 | |
| 1090 | export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort"; |
| 1091 | export { |
| 1092 | sortInboxThreadsByReturn, |
| 1093 | sortWorkingThreadsBySend, |
| 1094 | } from "@t3tools/client-runtime/state/thread-inbox"; |
| 1095 | |
| 1096 | export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort"; |
| 1097 | export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort"; |
| 1098 | |
| 1099 | const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>(); |
| 1100 | |
| 1101 | /** |
| 1102 | * Sidebar search results: title, branch, and pull request matches ranked as |
| 1103 | * the command palette ranks them, then threads listed only because their |
| 1104 | * messages match, in `contentMatchKeys` order. |
| 1105 | */ |
| 1106 | export function searchSidebarThreads< |
| 1107 | T extends ThreadSearchShell & { |
| 1108 | readonly environmentId: EnvironmentId; |
| 1109 | readonly id: ThreadId; |
| 1110 | }, |
| 1111 | >( |
| 1112 | threads: readonly T[], |
| 1113 | query: string, |
| 1114 | contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS, |
| 1115 | now = Date.now(), |
| 1116 | ): { readonly titleMatches: T[]; readonly contentMatches: T[] } { |
| 1117 | const normalizedQuery = foldSearchQuery(query); |
| 1118 | if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] }; |
| 1119 | const titleMatches = rankSearchItems(threads, (thread, options) => |
| 1120 | scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, { |
| 1121 | ...options, |
| 1122 | picks: false, |
| 1123 | }), |
| 1124 | ).map(({ item }) => item); |
| 1125 | const listed = new Set(titleMatches); |
| 1126 | // In the order the server ranked their messages, as the palette lists them. |
| 1127 | const threadByKey = new Map( |
| 1128 | threads.map((thread) => [ |
| 1129 | threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }), |
| 1130 | thread, |
| 1131 | ]), |
| 1132 | ); |
| 1133 | const contentMatches = [...contentMatchKeys].flatMap((key) => { |
| 1134 | const thread = threadByKey.get(key); |
| 1135 | return thread && !listed.has(thread) ? [thread] : []; |
| 1136 | }); |
| 1137 | return { titleMatches, contentMatches }; |
| 1138 | } |
| 1139 | |
| 1140 | export function pullRequestMatchesSearchQuery( |
| 1141 | pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0], |
| 1142 | query: string, |
| 1143 | ): boolean { |
| 1144 | const normalizedQuery = normalizeSearchText(query); |
| 1145 | if (normalizedQuery.length === 0) return false; |
| 1146 | const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" ")); |
| 1147 | return normalizedQuery.split(" ").every((token) => haystack.includes(token)); |
| 1148 | } |
| 1149 | |
| 1150 | export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: { |
| 1151 | items: readonly TItem[]; |
| 1152 | query: string; |
| 1153 | matches: (item: TItem, query: string) => boolean; |
| 1154 | }): readonly TItem[] { |
| 1155 | const query = input.query.trim(); |
| 1156 | if (query.length === 0) return input.items; |
| 1157 | return input.items.filter((item) => item.value !== "all" && input.matches(item, query)); |
| 1158 | } |
| 1159 | |
| 1160 | interface SidebarProjectScopeMenuState { |
| 1161 | readonly open: boolean; |
| 1162 | readonly query: string; |
| 1163 | } |
| 1164 | |
| 1165 | type SidebarProjectScopeMenuAction = |
| 1166 | | { readonly type: "query-changed"; readonly query: string } |
| 1167 | | { readonly type: "open-changed"; readonly open: boolean } |
| 1168 | | { readonly type: "project-settings-opened" }; |
| 1169 | |
| 1170 | export function reduceSidebarProjectScopeMenuState( |
| 1171 | state: SidebarProjectScopeMenuState, |
| 1172 | action: SidebarProjectScopeMenuAction, |
| 1173 | ): SidebarProjectScopeMenuState { |
| 1174 | switch (action.type) { |
| 1175 | case "query-changed": |
| 1176 | return { ...state, query: action.query }; |
| 1177 | case "open-changed": |
| 1178 | return { open: action.open, query: "" }; |
| 1179 | case "project-settings-opened": |
| 1180 | return { open: false, query: "" }; |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | export function resolveWorkingStartedAt( |
| 1185 | thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">, |
| 1186 | ): string | null { |
| 1187 | return resolveThreadWorkingStartedAt(thread); |
| 1188 | } |
| 1189 | |
| 1190 | export function resolveThreadStatusPill(input: { |
| 1191 | thread: ThreadStatusInput; |
| 1192 | }): ThreadStatusPill | null { |
| 1193 | const { thread } = input; |
| 1194 | |
| 1195 | if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") { |
| 1196 | return { |
| 1197 | label: msg("Pending Approval"), |
| 1198 | colorClass: "text-amber-600 dark:text-amber-300/90", |
| 1199 | dotClass: "bg-amber-500 dark:bg-amber-300/90", |
| 1200 | pulse: false, |
| 1201 | }; |
| 1202 | } |
| 1203 | |
| 1204 | if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") { |
| 1205 | return { |
| 1206 | label: msg("Awaiting Input"), |
| 1207 | colorClass: "text-indigo-600 dark:text-indigo-300/90", |
| 1208 | dotClass: "bg-indigo-500 dark:bg-indigo-300/90", |
| 1209 | pulse: false, |
| 1210 | }; |
| 1211 | } |
| 1212 | |
| 1213 | if ((thread.pendingGuestMessageCount ?? 0) > 0) { |
| 1214 | return { |
| 1215 | label: msg("Guest Request"), |
| 1216 | colorClass: "text-guest-foreground", |
| 1217 | dotClass: "bg-guest", |
| 1218 | pulse: false, |
| 1219 | }; |
| 1220 | } |
| 1221 | |
| 1222 | if ( |
| 1223 | (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) || |
| 1224 | thread.runtime?.status === "waiting" |
| 1225 | ) { |
| 1226 | return { |
| 1227 | label: msg("Working"), |
| 1228 | colorClass: "text-sky-600 dark:text-sky-300/80", |
| 1229 | dotClass: "bg-sky-500 dark:bg-sky-300/80", |
| 1230 | pulse: true, |
| 1231 | }; |
| 1232 | } |
| 1233 | |
| 1234 | if ( |
| 1235 | thread.runtime?.status === "preparing" || |
| 1236 | thread.runtime?.status === "starting" || |
| 1237 | thread.runtime?.status === "queued" |
| 1238 | ) { |
| 1239 | return { |
| 1240 | label: msg("Connecting"), |
| 1241 | colorClass: "text-sky-600 dark:text-sky-300/80", |
| 1242 | dotClass: "bg-sky-500 dark:bg-sky-300/80", |
| 1243 | pulse: true, |
| 1244 | }; |
| 1245 | } |
| 1246 | |
| 1247 | const waiting = { |
| 1248 | label: msg("Waiting"), |
| 1249 | colorClass: "text-sidebar-muted-foreground", |
| 1250 | dotClass: "bg-sidebar-muted-foreground", |
| 1251 | pulse: false, |
| 1252 | }; |
| 1253 | if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) return waiting; |
| 1254 | |
| 1255 | // A failed run goes to the inbox even while background work holds the thread. |
| 1256 | if (hasUnseenRunFailure(thread)) { |
| 1257 | return { |
| 1258 | label: msg("Failed"), |
| 1259 | colorClass: "text-red-600 dark:text-red-300/90", |
| 1260 | dotClass: "bg-red-500 dark:bg-red-300/90", |
| 1261 | pulse: false, |
| 1262 | }; |
| 1263 | } |
| 1264 | |
| 1265 | if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return waiting; |
| 1266 | |
| 1267 | const hasPlanReadyPrompt = |
| 1268 | !thread.hasPendingUserInput && |
| 1269 | thread.interactionMode === "plan" && |
| 1270 | isLatestRunSettled(thread.latestRun, thread.runtime) && |
| 1271 | thread.hasActionableProposedPlan; |
| 1272 | if (hasPlanReadyPrompt) { |
| 1273 | return { |
| 1274 | label: msg("Plan Ready"), |
| 1275 | colorClass: "text-violet-600 dark:text-violet-300/90", |
| 1276 | dotClass: "bg-violet-500 dark:bg-violet-300/90", |
| 1277 | pulse: false, |
| 1278 | }; |
| 1279 | } |
| 1280 | |
| 1281 | if (hasUnseenCompletion(thread)) { |
| 1282 | return { |
| 1283 | label: msg("Completed"), |
| 1284 | colorClass: "text-emerald-600 dark:text-emerald-300/90", |
| 1285 | dotClass: "bg-emerald-500 dark:bg-emerald-300/90", |
| 1286 | pulse: false, |
| 1287 | }; |
| 1288 | } |
| 1289 | |
| 1290 | return null; |
| 1291 | } |
| 1292 | |
| 1293 | export function getFallbackThreadIdAfterDelete< |
| 1294 | T extends Pick< |
| 1295 | Thread, |
| 1296 | "id" | "projectId" | "createdAt" | "updatedAt" | "settledOverride" | "lineage" |
| 1297 | > & |
| 1298 | ThreadSortInput & |
| 1299 | ThreadSnoozeShell & |
| 1300 | Pick<Thread, "environmentId">, |
| 1301 | >(input: { |
| 1302 | threads: readonly T[]; |
| 1303 | deletedThreadId: T["id"]; |
| 1304 | sortOrder: SidebarThreadSortOrder; |
| 1305 | now: string; |
| 1306 | deletedThreadIds?: ReadonlySet<T["id"]>; |
| 1307 | delegatedUnderParent: ReadonlySet<string>; |
| 1308 | }): T["id"] | null { |
| 1309 | const { deletedThreadId, deletedThreadIds, sortOrder, now, threads, delegatedUnderParent } = |
| 1310 | input; |
| 1311 | const deletedThread = threads.find((thread) => thread.id === deletedThreadId); |
| 1312 | if (!deletedThread) { |
| 1313 | return null; |
| 1314 | } |
| 1315 | |
| 1316 | return ( |
| 1317 | sortThreads( |
| 1318 | threads.filter( |
| 1319 | (thread) => |
| 1320 | thread.projectId === deletedThread.projectId && |
| 1321 | thread.id !== deletedThreadId && |
| 1322 | !deletedThreadIds?.has(thread.id) && |
| 1323 | thread.settledOverride !== "settled" && |
| 1324 | !effectiveSnoozed(thread, { now }) && |
| 1325 | !isShownUnderParent( |
| 1326 | { environmentId: thread.environmentId, threadId: thread.id }, |
| 1327 | thread.lineage, |
| 1328 | delegatedUnderParent, |
| 1329 | ), |
| 1330 | ), |
| 1331 | sortOrder, |
| 1332 | )[0]?.id ?? null |
| 1333 | ); |
| 1334 | } |
| 1335 | function getProjectSortTimestamp( |
| 1336 | project: SidebarProject, |
| 1337 | projectThreads: readonly ThreadSortInput[], |
| 1338 | sortOrder: Exclude<SidebarProjectSortOrder, "manual">, |
| 1339 | ): number { |
| 1340 | if (projectThreads.length > 0) { |
| 1341 | return projectThreads.reduce( |
| 1342 | (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)), |
| 1343 | Number.NEGATIVE_INFINITY, |
| 1344 | ); |
| 1345 | } |
| 1346 | |
| 1347 | if (sortOrder === "created_at") { |
| 1348 | return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY; |
| 1349 | } |
| 1350 | return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY; |
| 1351 | } |
| 1352 | |
| 1353 | function sortProjectsByActivity<TProject extends SidebarProject>( |
| 1354 | projects: readonly TProject[], |
| 1355 | sortOrder: SidebarProjectSortOrder, |
| 1356 | getProjectThreads: (project: TProject) => readonly ThreadSortInput[], |
| 1357 | compareTies: (left: TProject, right: TProject) => number, |
| 1358 | ): TProject[] { |
| 1359 | if (sortOrder === "manual") { |
| 1360 | return [...projects]; |
| 1361 | } |
| 1362 | |
| 1363 | // Project timestamps scan all threads; compute once per project instead of per comparison. |
| 1364 | return projects |
| 1365 | .map((project) => ({ |
| 1366 | project, |
| 1367 | timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder), |
| 1368 | })) |
| 1369 | .sort((left, right) => { |
| 1370 | const byTimestamp = |
| 1371 | right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1; |
| 1372 | return byTimestamp || compareTies(left.project, right.project); |
| 1373 | }) |
| 1374 | .map(({ project }) => project); |
| 1375 | } |
| 1376 | |
| 1377 | export function sortLogicalProjectsForSidebar< |
| 1378 | TProject extends LogicalSidebarProject, |
| 1379 | TThread extends ScopedSidebarThread, |
| 1380 | >( |
| 1381 | projects: readonly TProject[], |
| 1382 | threads: readonly TThread[], |
| 1383 | sortOrder: SidebarProjectSortOrder, |
| 1384 | ): TProject[] { |
| 1385 | const groupKeyByProjectRef = new Map( |
| 1386 | projects.flatMap((project) => |
| 1387 | project.memberProjectRefs.map( |
| 1388 | (projectRef) => |
| 1389 | [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const, |
| 1390 | ), |
| 1391 | ), |
| 1392 | ); |
| 1393 | const threadsByProjectKey = new Map<string, TThread[]>(); |
| 1394 | for (const thread of threads) { |
| 1395 | if (thread.archivedAt !== null) continue; |
| 1396 | const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`); |
| 1397 | if (!projectKey) continue; |
| 1398 | const existing = threadsByProjectKey.get(projectKey); |
| 1399 | if (existing) { |
| 1400 | existing.push(thread); |
| 1401 | } else { |
| 1402 | threadsByProjectKey.set(projectKey, [thread]); |
| 1403 | } |
| 1404 | } |
| 1405 | |
| 1406 | return sortProjectsByActivity( |
| 1407 | projects, |
| 1408 | sortOrder, |
| 1409 | (project) => threadsByProjectKey.get(project.projectKey) ?? [], |
| 1410 | (left, right) => |
| 1411 | left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey), |
| 1412 | ); |
| 1413 | } |
| 1414 | |
| 1415 | export function sortSidebarV2ProjectGroups< |
| 1416 | TProject extends LogicalSidebarProject, |
| 1417 | TThread extends ScopedSidebarThread & |
| 1418 | Pick<SidebarThreadSummary, "environmentId" | "id" | "lineage">, |
| 1419 | >( |
| 1420 | projects: readonly TProject[], |
| 1421 | threads: readonly TThread[], |
| 1422 | sortOrder: SidebarProjectSortOrder, |
| 1423 | delegatedUnderParent: ReadonlySet<string>, |
| 1424 | ): TProject[] { |
| 1425 | return sortLogicalProjectsForSidebar( |
| 1426 | projects, |
| 1427 | filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent), |
| 1428 | sortOrder, |
| 1429 | ); |
| 1430 | } |
| 1431 | |
| 1432 | export function sortScopedProjectsForSidebar< |
| 1433 | TProject extends ScopedSidebarProject, |
| 1434 | TThread extends ScopedSidebarThread, |
| 1435 | >( |
| 1436 | projects: readonly TProject[], |
| 1437 | threads: readonly TThread[], |
| 1438 | sortOrder: SidebarProjectSortOrder, |
| 1439 | ): TProject[] { |
| 1440 | const scopedKey = (environmentId: string, projectId: string) => |
| 1441 | `${environmentId}\u0000${projectId}`; |
| 1442 | const threadsByProject = new Map<string, TThread[]>(); |
| 1443 | for (const thread of threads) { |
| 1444 | if (thread.archivedAt !== null) { |
| 1445 | continue; |
| 1446 | } |
| 1447 | const key = scopedKey(thread.environmentId, thread.projectId); |
| 1448 | const existing = threadsByProject.get(key) ?? []; |
| 1449 | existing.push(thread); |
| 1450 | threadsByProject.set(key, existing); |
| 1451 | } |
| 1452 | |
| 1453 | return sortProjectsByActivity( |
| 1454 | projects, |
| 1455 | sortOrder, |
| 1456 | (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [], |
| 1457 | (left, right) => |
| 1458 | left.title.localeCompare(right.title) || |
| 1459 | left.environmentId.localeCompare(right.environmentId) || |
| 1460 | left.id.localeCompare(right.id), |
| 1461 | ); |
| 1462 | } |