Unified · Split
| @@ -78,6 +78,7 @@ describe("DesktopLifecycle", () => { · 77 unmodified lines | ||
| 78 | 78 | handleBackendNotReady: Effect.void, |
| 79 | 79 | flushMainWindowBounds: Effect.void, |
| 80 | 80 | dispatchMenuAction: () => Effect.void, |
| 81 | + zoomMain: () => Effect.void, | |
| 81 | 82 | syncAppearance: Effect.void, |
| 82 | 83 | }); |
| 83 | 84 | |
| @@ -91,6 +91,7 @@ function makePoolLayer( · 90 unmodified lines | ||
| 91 | 91 | handleBackendNotReady: Effect.void, |
| 92 | 92 | flushMainWindowBounds: Effect.void, |
| 93 | 93 | dispatchMenuAction: () => Effect.die("unexpected menu action"), |
| 94 | + zoomMain: () => Effect.die("unexpected zoom"), | |
| 94 | 95 | syncAppearance: Effect.void, |
| 95 | 96 | } satisfies DesktopWindow.DesktopWindow["Service"]), |
| 96 | 97 | ), |
| @@ -39,8 +39,7 @@ const clientSettings: ClientSettings = { · 38 unmodified lines | ||
| 39 | 39 | sidebarProjectSortOrder: "manual", |
| 40 | 40 | sidebarThreadSortOrder: "created_at", |
| 41 | 41 | sidebarThreadPreviewCount: 6, |
| 42 | − sidebarV2Enabled: false, | |
| 43 | − sidebarV2ConfiguredByUser: false, | |
| 42 | + legacySidebarEnabled: false, | |
| 44 | 43 | timestampFormat: "24-hour", |
| 45 | 44 | wordWrap: true, |
| 46 | 45 | }; |
| @@ -81,6 +81,8 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) => · 80 unmodified lines | ||
| 81 | 81 | handleBackendNotReady: Effect.void, |
| 82 | 82 | flushMainWindowBounds: Effect.void, |
| 83 | 83 | dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid), |
| 84 | + zoomMain: (direction) => | |
| 85 | + Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid), | |
| 84 | 86 | syncAppearance: Effect.void, |
| 85 | 87 | } satisfies DesktopWindow.DesktopWindow["Service"]); |
| 86 | 88 | |
| @@ -94,6 +96,30 @@ const makeElectronMenuLayer = ( · 7 unmodified lines | ||
| 94 | 96 | showContextMenu: () => Effect.succeed(Option.none()), |
| 95 | 97 | } satisfies ElectronMenu.ElectronMenu["Service"]); |
| 96 | 98 | |
| 99 | +const configureMenu = ( | |
| 100 | + selectedAction: Deferred.Deferred<string>, | |
| 101 | + applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>, | |
| 102 | +) => | |
| 103 | + Effect.gen(function* () { | |
| 104 | + const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu; | |
| 105 | + yield* menu.configure; | |
| 106 | + }).pipe( | |
| 107 | + Effect.provide( | |
| 108 | + DesktopApplicationMenu.layer.pipe( | |
| 109 | + Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)), | |
| 110 | + Layer.provideMerge(makeDesktopWindowLayer(selectedAction)), | |
| 111 | + Layer.provideMerge(desktopUpdatesLayer), | |
| 112 | + Layer.provideMerge(electronDialogLayer), | |
| 113 | + Layer.provideMerge(electronAppLayer), | |
| 114 | + Layer.provideMerge( | |
| 115 | + DesktopEnvironment.layer(environmentInput).pipe( | |
| 116 | + Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))), | |
| 117 | + ), | |
| 118 | + ), | |
| 119 | + ), | |
| 120 | + ), | |
| 121 | + ); | |
| 122 | + | |
| 97 | 123 | describe("DesktopApplicationMenu", () => { |
| 98 | 124 | it.effect("installs the native menu and routes Settings through DesktopWindow", () => |
| 99 | 125 | Effect.gen(function* () { |
| @@ -101,25 +127,7 @@ describe("DesktopApplicationMenu", () => { · 1 unmodified line | ||
| 101 | 127 | const applicationMenuTemplate = |
| 102 | 128 | yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>(); |
| 103 | 129 | |
| 104 | − yield* Effect.gen(function* () { | |
| 105 | − const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu; | |
| 106 | − yield* menu.configure; | |
| 107 | − }).pipe( | |
| 108 | − Effect.provide( | |
| 109 | − DesktopApplicationMenu.layer.pipe( | |
| 110 | − Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)), | |
| 111 | − Layer.provideMerge(makeDesktopWindowLayer(selectedAction)), | |
| 112 | − Layer.provideMerge(desktopUpdatesLayer), | |
| 113 | − Layer.provideMerge(electronDialogLayer), | |
| 114 | − Layer.provideMerge(electronAppLayer), | |
| 115 | − Layer.provideMerge( | |
| 116 | − DesktopEnvironment.layer(environmentInput).pipe( | |
| 117 | − Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))), | |
| 118 | − ), | |
| 119 | − ), | |
| 120 | − ), | |
| 121 | − ), | |
| 122 | − ); | |
| 130 | + yield* configureMenu(selectedAction, applicationMenuTemplate); | |
| 123 | 131 | |
| 124 | 132 | const template = yield* Deferred.await(applicationMenuTemplate); |
| 125 | 133 | const fileMenu = template.find((item) => item.label === "File"); |
| @@ -138,4 +146,38 @@ describe("DesktopApplicationMenu", () => { · 12 unmodified lines | ||
| 138 | 146 | assert.equal(yield* Deferred.await(selectedAction), "open-settings"); |
| 139 | 147 | }), |
| 140 | 148 | ); |
| 149 | + | |
| 150 | + // Zoom must route through DesktopWindow.zoomMain instead of the Electron | |
| 151 | + // zoom roles: the roles zoom whichever webContents has focus, which breaks | |
| 152 | + // app zoom while an embedded preview WebContentsView holds focus. | |
| 153 | + it.effect("routes View menu zoom to the main window instead of zoom roles", () => | |
| 154 | + Effect.gen(function* () { | |
| 155 | + const selectedAction = yield* Deferred.make<string>(); | |
| 156 | + const applicationMenuTemplate = | |
| 157 | + yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>(); | |
| 158 | + | |
| 159 | + yield* configureMenu(selectedAction, applicationMenuTemplate); | |
| 160 | + | |
| 161 | + const template = yield* Deferred.await(applicationMenuTemplate); | |
| 162 | + const viewMenu = template.find((item) => item.label === "View"); | |
| 163 | + assert.isDefined(viewMenu); | |
| 164 | + if (!Array.isArray(viewMenu.submenu)) { | |
| 165 | + throw new Error("Expected View menu submenu to be an array."); | |
| 166 | + } | |
| 167 | + | |
| 168 | + assert.isUndefined( | |
| 169 | + viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")), | |
| 170 | + ); | |
| 171 | + | |
| 172 | + const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In"); | |
| 173 | + assert.isDefined(zoomIn); | |
| 174 | + assert.equal(zoomIn.accelerator, "CmdOrCtrl+="); | |
| 175 | + if (typeof zoomIn.click !== "function") { | |
| 176 | + throw new Error("Expected Zoom In menu item to have a click handler."); | |
| 177 | + } | |
| 178 | + | |
| 179 | + zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent); | |
| 180 | + assert.equal(yield* Deferred.await(selectedAction), "zoom-in"); | |
| 181 | + }), | |
| 182 | + ); | |
| 141 | 183 | }); |
| @@ -49,6 +49,13 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function · 48 unmodified lines | ||
| 49 | 49 | yield* desktopWindow.dispatchMenuAction(action); |
| 50 | 50 | }); |
| 51 | 51 | |
| 52 | +const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* ( | |
| 53 | + direction: DesktopWindow.MainWindowZoomDirection, | |
| 54 | +): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> { | |
| 55 | + const desktopWindow = yield* DesktopWindow.DesktopWindow; | |
| 56 | + yield* desktopWindow.zoomMain(direction); | |
| 57 | +}); | |
| 58 | + | |
| 52 | 59 | const checkForUpdatesFromMenu = Effect.gen(function* () { |
| 53 | 60 | const updates = yield* DesktopUpdates.DesktopUpdates; |
| 54 | 61 | const electronDialog = yield* ElectronDialog.ElectronDialog; |
| @@ -127,6 +134,9 @@ export const make = Effect.gen(function* () { · 72 unmodified lines | ||
| 127 | 134 | const settingsClick = () => { |
| 128 | 135 | runMenuEffect("open-settings", dispatchMenuAction("open-settings")); |
| 129 | 136 | }; |
| 137 | + const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => { | |
| 138 | + runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction)); | |
| 139 | + }; | |
| 130 | 140 | const template: Electron.MenuItemConstructorOptions[] = []; |
| 131 | 141 | |
| 132 | 142 | if (environment.platform === "darwin") { |
| @@ -181,10 +191,21 @@ export const make = Effect.gen(function* () { · 48 unmodified lines | ||
| 181 | 191 | { role: "forceReload" }, |
| 182 | 192 | { role: "toggleDevTools" }, |
| 183 | 193 | { type: "separator" }, |
| 184 | − { role: "resetZoom" }, | |
| 185 | − { role: "zoomIn", accelerator: "CmdOrCtrl+=" }, | |
| 186 | − { role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false }, | |
| 187 | − { role: "zoomOut" }, | |
| 194 | + /* | |
| 195 | + Not the zoom roles: those act on the focused webContents, so with | |
| 196 | + an embedded preview WebContentsView focused they zoom the guest | |
| 197 | + page and the app UI appears stuck. These always zoom the main | |
| 198 | + window (see DesktopWindow.zoomMain). | |
| 199 | + */ | |
| 200 | + { label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") }, | |
| 201 | + { label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") }, | |
| 202 | + { | |
| 203 | + label: "Zoom In", | |
| 204 | + accelerator: "CmdOrCtrl+Plus", | |
| 205 | + visible: false, | |
| 206 | + click: zoomClick("in"), | |
| 207 | + }, | |
| 208 | + { label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") }, | |
| 188 | 209 | { type: "separator" }, |
| 189 | 210 | { role: "togglefullscreen" }, |
| 190 | 211 | ], |
| @@ -61,6 +61,8 @@ export type DesktopWindowError = · 60 unmodified lines | ||
| 61 | 61 | | ElectronWindow.ElectronWindowCreateError |
| 62 | 62 | | PreviewManager.PreviewManagerError; |
| 63 | 63 | |
| 64 | +export type MainWindowZoomDirection = "in" | "out" | "reset"; | |
| 65 | + | |
| 64 | 66 | export class DesktopWindow extends Context.Service< |
| 65 | 67 | DesktopWindow, |
| 66 | 68 | { |
| @@ -87,6 +89,12 @@ export class DesktopWindow extends Context.Service< · 20 unmodified lines | ||
| 87 | 89 | readonly handleBackendNotReady: Effect.Effect<void>; |
| 88 | 90 | readonly flushMainWindowBounds: Effect.Effect<void>; |
| 89 | 91 | readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>; |
| 92 | + // Zooms the main window's own webContents. The Electron `zoomIn`/`zoomOut` | |
| 93 | + // menu roles act on whichever webContents has keyboard focus, so with an | |
| 94 | + // embedded preview WebContentsView (or DevTools) focused they zoom the | |
| 95 | + // guest page instead of the app UI. The menu routes here to always target | |
| 96 | + // the main window. | |
| 97 | + readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>; | |
| 90 | 98 | readonly syncAppearance: Effect.Effect<void>; |
| 91 | 99 | } |
| 92 | 100 | >()("@t3tools/desktop/window/DesktopWindow") {} |
| @@ -836,6 +844,18 @@ export const make = Effect.gen(function* () { · 743 unmodified lines | ||
| 836 | 844 | |
| 837 | 845 | send(); |
| 838 | 846 | }), |
| 847 | + zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) { | |
| 848 | + yield* Effect.annotateCurrentSpan({ direction }); | |
| 849 | + const window = yield* focusedMainWindow; | |
| 850 | + if (Option.isNone(window) || window.value.isDestroyed()) { | |
| 851 | + return; | |
| 852 | + } | |
| 853 | + const webContents = window.value.webContents; | |
| 854 | + // Same step size as the Electron zoomIn/zoomOut menu roles. | |
| 855 | + webContents.setZoomLevel( | |
| 856 | + direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5), | |
| 857 | + ); | |
| 858 | + }), | |
| 839 | 859 | syncAppearance: Effect.gen(function* () { |
| 840 | 860 | const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; |
| 841 | 861 | yield* electronWindow.syncAllAppearance((window) => |
| @@ -131,7 +131,7 @@ function LocalSettingsRouteScreen() { · 130 unmodified lines | ||
| 131 | 131 | <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" /> |
| 132 | 132 | </SettingsSection> |
| 133 | 133 | |
| 134 | − <BetaSettingsSection /> | |
| 134 | + <LegacySettingsSection /> | |
| 135 | 135 | |
| 136 | 136 | <ArchivedThreadsSettingsSection /> |
| 137 | 137 | |
| @@ -519,7 +519,7 @@ function ConfiguredSettingsRouteScreen() { · 381 unmodified lines | ||
| 519 | 519 | <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" /> |
| 520 | 520 | </SettingsSection> |
| 521 | 521 | |
| 522 | − <BetaSettingsSection /> | |
| 522 | + <LegacySettingsSection /> | |
| 523 | 523 | |
| 524 | 524 | <ArchivedThreadsSettingsSection /> |
| 525 | 525 | |
| @@ -538,26 +538,27 @@ function GeneralSettingsSection() { · 12 unmodified lines | ||
| 538 | 538 | } |
| 539 | 539 | |
| 540 | 540 | /** |
| 541 | − * Device-local beta toggles. Mobile has no client-settings sync, so this is | |
| 542 | − * the counterpart of web's Settings → Beta backed by mobile preferences. | |
| 541 | + * Device-local legacy toggles. Mobile has no client-settings sync, so this is | |
| 542 | + * the counterpart of web's Settings → General → Legacy features backed by | |
| 543 | + * mobile preferences. | |
| 543 | 544 | */ |
| 544 | −function BetaSettingsSection() { | |
| 545 | +function LegacySettingsSection() { | |
| 545 | 546 | const savePreferences = useAtomSet(updateMobilePreferencesAtom); |
| 546 | 547 | const threadListV2Enabled = useThreadListV2Enabled(); |
| 547 | 548 | |
| 548 | 549 | return ( |
| 549 | 550 | <View className="gap-3"> |
| 550 | − <SettingsSection title="Beta"> | |
| 551 | + <SettingsSection title="Legacy"> | |
| 551 | 552 | <SettingsSwitchRow |
| 552 | 553 | icon="sidebar.left" |
| 553 | − label="Thread List v2" | |
| 554 | − value={threadListV2Enabled} | |
| 555 | − onValueChange={(value) => savePreferences({ threadListV2Enabled: value })} | |
| 554 | + label="Legacy Thread List" | |
| 555 | + value={!threadListV2Enabled} | |
| 556 | + onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })} | |
| 556 | 557 | /> |
| 557 | 558 | </SettingsSection> |
| 558 | 559 | <Text className="px-2 text-sm text-foreground-muted"> |
| 559 | − One flat thread list in creation order. Active work renders as cards; settled threads | |
| 560 | − collapse to compact rows. Switch back any time. | |
| 560 | + Brings back the original grouped thread list. The default list is flat, in creation order: | |
| 561 | + active work renders as cards; settled threads collapse to compact rows. | |
| 561 | 562 | </Text> |
| 562 | 563 | </View> |
| 563 | 564 | ); |
| @@ -25,15 +25,12 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri · 24 unmodified lines | ||
| 25 | 25 | import { ControlPill, ControlPillMenu } from "../../components/ControlPill"; |
| 26 | 26 | import { ProviderIcon } from "../../components/ProviderIcon"; |
| 27 | 27 | import { ComposerSurface } from "./ThreadComposer"; |
| 28 | +import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet"; | |
| 29 | +import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation"; | |
| 28 | 30 | |
| 29 | 31 | import { makeTurnCommandMetadata } from "../../lib/commandMetadata"; |
| 30 | 32 | import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; |
| 31 | −import { | |
| 32 | − applyProviderOptionMenuEvent, | |
| 33 | − buildProviderOptionMenuActions, | |
| 34 | − providerOptionsConfigurationLabel, | |
| 35 | − resolveProviderOptionDescriptors, | |
| 36 | −} from "../../lib/providerOptions"; | |
| 33 | +import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; | |
| 37 | 34 | import { useScaledTextRole } from "../settings/appearance/useScaledTextRole"; |
| 38 | 35 | import { |
| 39 | 36 | clearComposerDraftContent, |
| @@ -43,7 +40,7 @@ import { · 3 unmodified lines | ||
| 43 | 40 | type ComposerDraft, |
| 44 | 41 | } from "../../state/use-composer-drafts"; |
| 45 | 42 | import { useEnvironmentServerConfig, useProjects } from "../../state/entities"; |
| 46 | −import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions"; | |
| 43 | +import { resolveSelectableModelSelection } from "../../lib/modelOptions"; | |
| 47 | 44 | import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn"; |
| 48 | 45 | import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration"; |
| 49 | 46 | import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox"; |
| @@ -103,6 +100,10 @@ export function NewTaskDraftScreen(props: { · 53 unmodified lines | ||
| 103 | 100 | const promptInputRef = useRef<ComposerEditorHandle>(null); |
| 104 | 101 | const loadedBranchesProjectKeyRef = useRef<string | null>(null); |
| 105 | 102 | const [isComposerFocused, setIsComposerFocused] = useState(false); |
| 103 | + const settingsSheetPresentation = useThreadSettingsSheetPresentation({ | |
| 104 | + editorRef: promptInputRef, | |
| 105 | + isEditorFocused: isComposerFocused, | |
| 106 | + }); | |
| 106 | 107 | const [importingShareKey, setImportingShareKey] = useState<string | null>(null); |
| 107 | 108 | const [isCancellingShareImport, setIsCancellingShareImport] = useState(false); |
| 108 | 109 | const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null); |
| @@ -521,7 +522,15 @@ export function NewTaskDraftScreen(props: { · 412 unmodified lines | ||
| 521 | 522 | |
| 522 | 523 | let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null; |
| 523 | 524 | const interaction = InteractionManager.runAfterInteractions(() => { |
| 524 | − focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus()); | |
| 525 | + focusFrame = requestAnimationFrame(() => { | |
| 526 | + // The delayed focus can land after the settings sheet opened, which | |
| 527 | + // would pop the keyboard underneath its modal. | |
| 528 | + if (!settingsSheetPresentation.isActiveRef.current) { | |
| 529 | + promptInputRef.current?.focus(); | |
| 530 | + } else { | |
| 531 | + settingsSheetPresentation.restoreFocusAfterSave(); | |
| 532 | + } | |
| 533 | + }); | |
| 525 | 534 | }); |
| 526 | 535 | |
| 527 | 536 | return () => { |
| @@ -530,7 +539,11 @@ export function NewTaskDraftScreen(props: { · 2 unmodified lines | ||
| 530 | 539 | cancelAnimationFrame(focusFrame); |
| 531 | 540 | } |
| 532 | 541 | }; |
| 533 | − }, [selectedProject]); | |
| 542 | + }, [ | |
| 543 | + selectedProject, | |
| 544 | + settingsSheetPresentation.isActiveRef, | |
| 545 | + settingsSheetPresentation.restoreFocusAfterSave, | |
| 546 | + ]); | |
| 534 | 547 | |
| 535 | 548 | const environmentMenuActions = useMemo( |
| 536 | 549 | () => |
| @@ -544,10 +557,6 @@ export function NewTaskDraftScreen(props: { · 7 unmodified lines | ||
| 544 | 557 | [flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending], |
| 545 | 558 | ); |
| 546 | 559 | |
| 547 | − const modelMenuActions = useMemo( | |
| 548 | − () => buildModelMenuActions(flow.providerGroups, flow.selectedModel), | |
| 549 | − [flow.providerGroups, flow.selectedModel], | |
| 550 | − ); | |
| 551 | 560 | const providerOptionDescriptors = useMemo( |
| 552 | 561 | () => |
| 553 | 562 | resolveProviderOptionDescriptors({ |
| @@ -557,54 +566,6 @@ export function NewTaskDraftScreen(props: { · 3 unmodified lines | ||
| 557 | 566 | [flow.selectedModel?.options, flow.selectedModelOption?.capabilities], |
| 558 | 567 | ); |
| 559 | 568 | |
| 560 | − const optionsMenuActions = useMemo( | |
| 561 | − () => [ | |
| 562 | − ...buildProviderOptionMenuActions(providerOptionDescriptors), | |
| 563 | − { | |
| 564 | − id: "options-runtime", | |
| 565 | − title: "Runtime", | |
| 566 | − subtitle: | |
| 567 | − flow.runtimeMode === "approval-required" | |
| 568 | − ? "Approve actions" | |
| 569 | − : flow.runtimeMode === "auto-accept-edits" | |
| 570 | − ? "Auto-accept edits" | |
| 571 | − : flow.runtimeMode === "auto" | |
| 572 | − ? "Auto" | |
| 573 | − : "Full access", | |
| 574 | − subactions: [ | |
| 575 | − { id: "options:runtime:approval-required", title: "Approve actions" }, | |
| 576 | − { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" }, | |
| 577 | − { id: "options:runtime:auto", title: "Auto" }, | |
| 578 | − { id: "options:runtime:full-access", title: "Full access" }, | |
| 579 | − ].map((option) => { | |
| 580 | − const value = option.id.replace("options:runtime:", ""); | |
| 581 | − return { | |
| 582 | − id: option.id, | |
| 583 | − title: option.title, | |
| 584 | − state: flow.runtimeMode === value ? ("on" as const) : undefined, | |
| 585 | − }; | |
| 586 | − }), | |
| 587 | − }, | |
| 588 | − { | |
| 589 | − id: "options-interaction", | |
| 590 | − title: "Interaction", | |
| 591 | − subtitle: flow.interactionMode === "plan" ? "Plan" : "Default", | |
| 592 | − subactions: [ | |
| 593 | − { id: "options:interaction:default", title: "Default" }, | |
| 594 | − { id: "options:interaction:plan", title: "Plan" }, | |
| 595 | − ].map((option) => { | |
| 596 | − const value = option.id.replace("options:interaction:", ""); | |
| 597 | − return { | |
| 598 | − id: option.id, | |
| 599 | − title: option.title, | |
| 600 | − state: flow.interactionMode === value ? ("on" as const) : undefined, | |
| 601 | − }; | |
| 602 | − }), | |
| 603 | − }, | |
| 604 | − ], | |
| 605 | − [flow.interactionMode, flow.runtimeMode, providerOptionDescriptors], | |
| 606 | − ); | |
| 607 | − | |
| 608 | 569 | const workspaceMenuActions = useMemo(() => { |
| 609 | 570 | const branchActions = |
| 610 | 571 | flow.availableBranches.length === 0 |
| @@ -675,10 +636,12 @@ export function NewTaskDraftScreen(props: { · 64 unmodified lines | ||
| 675 | 636 | flow.availableBranches.find((branch) => branch.current)?.name ?? |
| 676 | 637 | flow.availableBranches.find((branch) => branch.isDefault)?.name ?? |
| 677 | 638 | null; |
| 678 | − const configurationLabel = useMemo( | |
| 679 | − () => providerOptionsConfigurationLabel(providerOptionDescriptors), | |
| 680 | − [providerOptionDescriptors], | |
| 681 | − ); | |
| 639 | + const settingsSummaryLabel = threadSettingsSummaryLabel({ | |
| 640 | + modelLabel: flow.selectedModelOption?.label ?? "Model", | |
| 641 | + optionDescriptors: providerOptionDescriptors, | |
| 642 | + runtimeMode: flow.runtimeMode, | |
| 643 | + interactionMode: flow.interactionMode, | |
| 644 | + }); | |
| 682 | 645 | const workspaceLabel = useMemo( |
| 683 | 646 | () => |
| 684 | 647 | formatWorkspaceLabel({ |
| @@ -688,13 +651,6 @@ export function NewTaskDraftScreen(props: { · 3 unmodified lines | ||
| 688 | 651 | }), |
| 689 | 652 | [currentBranchName, flow.selectedBranchName, flow.workspaceMode], |
| 690 | 653 | ); |
| 691 | − function handleModelMenuAction(event: string) { | |
| 692 | − if (isIncomingShareTransferPending || !event.startsWith("model:")) { | |
| 693 | − return; | |
| 694 | − } | |
| 695 | − flow.setSelectedModelKey(event.slice("model:".length)); | |
| 696 | − } | |
| 697 | − | |
| 698 | 654 | function handleEnvironmentMenuAction(event: string) { |
| 699 | 655 | if (isIncomingShareTransferPending || !event.startsWith("environment:")) { |
| 700 | 656 | return; |
| @@ -702,28 +658,6 @@ export function NewTaskDraftScreen(props: { · 1 unmodified line | ||
| 702 | 658 | flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length))); |
| 703 | 659 | } |
| 704 | 660 | |
| 705 | − function handleOptionsMenuAction(event: string) { | |
| 706 | − if (isIncomingShareTransferPending) { | |
| 707 | − return; | |
| 708 | − } | |
| 709 | − const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event); | |
| 710 | − if (providerOptions) { | |
| 711 | − flow.setSelectedModelOptions(providerOptions); | |
| 712 | − return; | |
| 713 | − } | |
| 714 | − if (event.startsWith("options:runtime:")) { | |
| 715 | − flow.setRuntimeMode( | |
| 716 | − event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0], | |
| 717 | − ); | |
| 718 | − return; | |
| 719 | − } | |
| 720 | − if (event.startsWith("options:interaction:")) { | |
| 721 | − flow.setInteractionMode( | |
| 722 | − event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0], | |
| 723 | − ); | |
| 724 | − } | |
| 725 | − } | |
| 726 | − | |
| 727 | 661 | function handleWorkspaceMenuAction(event: string) { |
| 728 | 662 | if (isIncomingShareTransferPending) { |
| 729 | 663 | return; |
| @@ -930,7 +864,9 @@ export function NewTaskDraftScreen(props: { · 200 unmodified lines | ||
| 930 | 864 | const isDarkMode = colorScheme === "dark"; |
| 931 | 865 | // Android expansion follows native editor focus so relayout cannot race |
| 932 | 866 | // the touch gesture that opens the keyboard. |
| 933 | − const isExpanded = !isAndroid || isComposerFocused; | |
| 867 | + // The settings sheet dismisses the keyboard, so its flag keeps the Android | |
| 868 | + // draft composer expanded through the blur (mirrors ThreadComposer). | |
| 869 | + const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive; | |
| 934 | 870 | const canStart = |
| 935 | 871 | Boolean(flow.selectedProject) && |
| 936 | 872 | Boolean(flow.selectedModel) && |
| @@ -984,28 +920,14 @@ export function NewTaskDraftScreen(props: { · 47 unmodified lines | ||
| 984 | 920 | showChevron={false} |
| 985 | 921 | disabled={isIncomingShareTransferPending} |
| 986 | 922 | /> |
| 987 | − <ControlPillMenu | |
| 988 | − actions={modelMenuActions} | |
| 989 | − onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)} | |
| 990 | − > | |
| 991 | − <ComposerToolbarTrigger | |
| 992 | − accessibilityLabel="Model" | |
| 993 | − disabled={isIncomingShareTransferPending} | |
| 994 | − iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />} | |
| 995 | − label={flow.selectedModelOption?.label ?? "Model"} | |
| 996 | − /> | |
| 997 | − </ControlPillMenu> | |
| 998 | − <ControlPillMenu | |
| 999 | − actions={optionsMenuActions} | |
| 1000 | − onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)} | |
| 1001 | − > | |
| 1002 | − <ComposerToolbarTrigger | |
| 1003 | − accessibilityLabel="Configuration" | |
| 1004 | − disabled={isIncomingShareTransferPending} | |
| 1005 | − icon="slider.horizontal.3" | |
| 1006 | − label={configurationLabel} | |
| 1007 | − /> | |
| 1008 | − </ControlPillMenu> | |
| 923 | + <ComposerToolbarTrigger | |
| 924 | + accessibilityLabel="Thread settings" | |
| 925 | + disabled={isIncomingShareTransferPending} | |
| 926 | + iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />} | |
| 927 | + label={settingsSummaryLabel} | |
| 928 | + maxWidth={320} | |
| 929 | + onPress={settingsSheetPresentation.open} | |
| 930 | + /> | |
| 1009 | 931 | <ControlPillMenu |
| 1010 | 932 | actions={environmentMenuActions} |
| 1011 | 933 | onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)} |
| @@ -1031,6 +953,21 @@ export function NewTaskDraftScreen(props: { · 19 unmodified lines | ||
| 1031 | 953 | </> |
| 1032 | 954 | ); |
| 1033 | 955 | |
| 956 | + const settingsSheet = ( | |
| 957 | + <ThreadSettingsSheet | |
| 958 | + visible={settingsSheetPresentation.isVisible} | |
| 959 | + onClose={settingsSheetPresentation.close} | |
| 960 | + onDismissed={settingsSheetPresentation.onDismissed} | |
| 961 | + providerGroups={flow.providerGroups} | |
| 962 | + selectedModel={flow.selectedModel} | |
| 963 | + onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)} | |
| 964 | + optionDescriptors={providerOptionDescriptors} | |
| 965 | + onUpdateOptionSelections={flow.setSelectedModelOptions} | |
| 966 | + runtimeMode={flow.runtimeMode} | |
| 967 | + onUpdateRuntimeMode={flow.setRuntimeMode} | |
| 968 | + /> | |
| 969 | + ); | |
| 970 | + | |
| 1034 | 971 | const startButton = ( |
| 1035 | 972 | <ComposerToolbarButton |
| 1036 | 973 | accessibilityLabel={ |
| @@ -1120,6 +1057,7 @@ export function NewTaskDraftScreen(props: { · 83 unmodified lines | ||
| 1120 | 1057 | ) : null} |
| 1121 | 1058 | </View> |
| 1122 | 1059 | </KeyboardAvoidingView> |
| 1060 | + {settingsSheet} | |
| 1123 | 1061 | </View> |
| 1124 | 1062 | ); |
| 1125 | 1063 | } |
| @@ -1153,6 +1091,7 @@ export function NewTaskDraftScreen(props: { · 27 unmodified lines | ||
| 1153 | 1091 | </ComposerToolbarRow> |
| 1154 | 1092 | </View> |
| 1155 | 1093 | </KeyboardAvoidingView> |
| 1094 | + {settingsSheet} | |
| 1156 | 1095 | </View> |
| 1157 | 1096 | ); |
| 1158 | 1097 | } |
| @@ -51,10 +51,10 @@ import { · 50 unmodified lines | ||
| 51 | 51 | ComposerToolbarScroller, |
| 52 | 52 | ComposerToolbarTrigger, |
| 53 | 53 | } from "../../components/ComposerToolbarTrigger"; |
| 54 | −import { ControlPill, ControlPillMenu } from "../../components/ControlPill"; | |
| 54 | +import { ControlPill } from "../../components/ControlPill"; | |
| 55 | 55 | import { ProviderIcon } from "../../components/ProviderIcon"; |
| 56 | 56 | import type { DraftComposerImageAttachment } from "../../lib/composerImages"; |
| 57 | −import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions"; | |
| 57 | +import { buildModelOptions, groupByProvider } from "../../lib/modelOptions"; | |
| 58 | 58 | import { useScaledTextRole } from "../settings/appearance/useScaledTextRole"; |
| 59 | 59 | import type { RemoteClientConnectionState } from "../../lib/connection"; |
| 60 | 60 | import { |
| @@ -62,14 +62,11 @@ import { · 1 unmodified line | ||
| 62 | 62 | normalizeSearchQuery, |
| 63 | 63 | scoreQueryMatch, |
| 64 | 64 | } from "@t3tools/shared/searchRanking"; |
| 65 | −import { | |
| 66 | − applyProviderOptionMenuEvent, | |
| 67 | − buildProviderOptionMenuActions, | |
| 68 | − providerOptionsConfigurationLabel, | |
| 69 | − resolveProviderOptionDescriptors, | |
| 70 | −} from "../../lib/providerOptions"; | |
| 65 | +import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; | |
| 71 | 66 | import { useComposerPathSearch } from "../../state/use-composer-path-search"; |
| 72 | 67 | import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; |
| 68 | +import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet"; | |
| 69 | +import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation"; | |
| 73 | 70 | |
| 74 | 71 | /** |
| 75 | 72 | * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset). |
| @@ -273,15 +270,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer · 197 unmodified lines | ||
| 273 | 270 | const fallbackInputRef = useRef<ComposerEditorHandle>(null); |
| 274 | 271 | const inputRef = props.editorRef ?? fallbackInputRef; |
| 275 | 272 | const [isFocused, setIsFocused] = useState(false); |
| 273 | + const settingsSheetPresentation = useThreadSettingsSheetPresentation({ | |
| 274 | + editorRef: inputRef, | |
| 275 | + isEditorFocused: isFocused, | |
| 276 | + }); | |
| 276 | 277 | const wasExpandedBeforePreviewRef = useRef(false); |
| 277 | 278 | const inFlightThreadIdsRef = useRef(new Set<string>()); |
| 278 | 279 | const { onExpandedChange } = props; |
| 279 | 280 | |
| 280 | 281 | const [previewImageUri, setPreviewImageUri] = useState<string | null>(null); |
| 281 | 282 | const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0; |
| 282 | − const isExpanded = isFocused; | |
| 283 | + // Opening and closing count as active so the composer stays expanded while | |
| 284 | + // focus moves between its native editor and the settings modal. | |
| 285 | + const isExpanded = isFocused || settingsSheetPresentation.isActive; | |
| 283 | 286 | const canSend = hasContent; |
| 284 | 287 | |
| 288 | + // Notify the parent from the derived value, not focus events: the parent | |
| 289 | + // sizes the feed inset from this, and blur-during-sheet would otherwise | |
| 290 | + // report collapsed while the composer still renders expanded. | |
| 291 | + useEffect(() => { | |
| 292 | + onExpandedChange?.(isExpanded); | |
| 293 | + }, [isExpanded, onExpandedChange]); | |
| 294 | + | |
| 285 | 295 | const onPressImage = useCallback( |
| 286 | 296 | (uri: string) => { |
| 287 | 297 | wasExpandedBeforePreviewRef.current = isFocused; |
| @@ -299,13 +309,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer · 11 unmodified lines | ||
| 299 | 309 | |
| 300 | 310 | const handleFocus = useCallback(() => { |
| 301 | 311 | setIsFocused(true); |
| 302 | − onExpandedChange?.(true); | |
| 303 | − }, [onExpandedChange]); | |
| 312 | + }, []); | |
| 304 | 313 | |
| 305 | 314 | const handleBlur = useCallback(() => { |
| 306 | 315 | setIsFocused(false); |
| 307 | − onExpandedChange?.(false); | |
| 308 | − }, [onExpandedChange]); | |
| 316 | + }, []); | |
| 309 | 317 | const showStopAction = |
| 310 | 318 | props.selectedThread.session?.status === "running" || |
| 311 | 319 | props.selectedThread.session?.status === "starting"; |
| @@ -588,6 +596,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer · 276 unmodified lines | ||
| 588 | 596 | [props.serverConfig, currentModelSelection], |
| 589 | 597 | ); |
| 590 | 598 | const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]); |
| 599 | + // An existing thread is bound to its harness: sessions can't move between | |
| 600 | + // provider instances, so the picker only offers the thread's own group. | |
| 601 | + const threadProviderGroups = useMemo( | |
| 602 | + () => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId), | |
| 603 | + [providerGroups, currentModelSelection.instanceId], | |
| 604 | + ); | |
| 591 | 605 | const currentModelOption = |
| 592 | 606 | modelOptions.find( |
| 593 | 607 | (option) => |
| @@ -602,95 +616,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer · 8 unmodified lines | ||
| 602 | 616 | }), |
| 603 | 617 | [currentModelOption?.capabilities, currentModelSelection.options], |
| 604 | 618 | ); |
| 605 | − const configurationLabel = useMemo( | |
| 606 | − () => providerOptionsConfigurationLabel(providerOptionDescriptors), | |
| 607 | − [providerOptionDescriptors], | |
| 608 | − ); | |
| 609 | − const modelMenuActions = useMemo( | |
| 610 | − () => buildModelMenuActions(providerGroups, currentModelSelection), | |
| 611 | − [providerGroups, currentModelSelection], | |
| 612 | − ); | |
| 613 | − | |
| 614 | − // ── Options menu ───────────────────────────────────────── | |
| 615 | − const optionsMenuActions = useMemo( | |
| 616 | − () => [ | |
| 617 | − ...buildProviderOptionMenuActions(providerOptionDescriptors), | |
| 618 | − { | |
| 619 | − id: "options-runtime", | |
| 620 | − title: "Runtime", | |
| 621 | − subtitle: | |
| 622 | − currentRuntimeMode === "approval-required" | |
| 623 | − ? "Approve actions" | |
| 624 | − : currentRuntimeMode === "auto-accept-edits" | |
| 625 | − ? "Auto-accept edits" | |
| 626 | − : currentRuntimeMode === "auto" | |
| 627 | − ? "Auto" | |
| 628 | − : "Full access", | |
| 629 | − subactions: [ | |
| 630 | − { id: "options:runtime:approval-required", title: "Approve actions" }, | |
| 631 | − { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" }, | |
| 632 | − { id: "options:runtime:auto", title: "Auto" }, | |
| 633 | − { id: "options:runtime:full-access", title: "Full access" }, | |
| 634 | − ].map((option) => { | |
| 635 | − const value = option.id.replace("options:runtime:", ""); | |
| 636 | − return { | |
| 637 | − id: option.id, | |
| 638 | − title: option.title, | |
| 639 | − state: currentRuntimeMode === value ? ("on" as const) : undefined, | |
| 640 | − }; | |
| 641 | − }), | |
| 642 | − }, | |
| 643 | − { | |
| 644 | − id: "options-interaction", | |
| 645 | − title: "Interaction", | |
| 646 | − subtitle: currentInteractionMode === "plan" ? "Plan" : "Default", | |
| 647 | − subactions: [ | |
| 648 | − { id: "options:interaction:default", title: "Default" }, | |
| 649 | − { id: "options:interaction:plan", title: "Plan" }, | |
| 650 | − ].map((option) => { | |
| 651 | − const value = option.id.replace("options:interaction:", ""); | |
| 652 | − return { | |
| 653 | − id: option.id, | |
| 654 | − title: option.title, | |
| 655 | − state: currentInteractionMode === value ? ("on" as const) : undefined, | |
| 656 | − }; | |
| 657 | − }), | |
| 658 | − }, | |
| 659 | − ], | |
| 660 | − [currentInteractionMode, currentRuntimeMode, providerOptionDescriptors], | |
| 661 | − ); | |
| 662 | − | |
| 663 | − // ── Menu handlers ──────────────────────────────────────── | |
| 664 | − function handleModelMenuAction(event: string) { | |
| 665 | − if (!event.startsWith("model:")) { | |
| 666 | − return; | |
| 667 | − } | |
| 668 | − const modelKey = event.slice("model:".length); | |
| 669 | − const option = modelOptions.find((o) => o.key === modelKey); | |
| 670 | − if (option) { | |
| 671 | − props.onUpdateModelSelection(option.selection); | |
| 672 | − } | |
| 673 | − } | |
| 674 | − | |
| 675 | − function handleOptionsMenuAction(event: string) { | |
| 676 | − const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event); | |
| 677 | − if (providerOptions) { | |
| 678 | − props.onUpdateModelSelection({ | |
| 679 | − ...currentModelSelection, | |
| 680 | − options: providerOptions, | |
| 681 | − }); | |
| 682 | − return; | |
| 683 | − } | |
| 684 | − if (event.startsWith("options:runtime:")) { | |
| 685 | − const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode; | |
| 686 | − props.onUpdateRuntimeMode(runtimeMode); | |
| 687 | − return; | |
| 688 | − } | |
| 689 | − if (event.startsWith("options:interaction:")) { | |
| 690 | − const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode; | |
| 691 | − props.onUpdateInteractionMode(interactionMode); | |
| 692 | − } | |
| 693 | − } | |
| 619 | + const settingsSummaryLabel = threadSettingsSummaryLabel({ | |
| 620 | + modelLabel: currentModelOption?.label ?? currentModelSelection.model, | |
| 621 | + optionDescriptors: providerOptionDescriptors, | |
| 622 | + runtimeMode: currentRuntimeMode, | |
| 623 | + interactionMode: currentInteractionMode, | |
| 624 | + }); | |
| 694 | 625 | |
| 695 | 626 | return ( |
| 696 | 627 | <Animated.View |
| @@ -861,28 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer · 164 unmodified lines | ||
| 861 | 792 | onPress={() => void props.onPickDraftImages()} |
| 862 | 793 | showChevron={false} |
| 863 | 794 | /> |
| 864 | − <ControlPillMenu | |
| 865 | − actions={modelMenuActions} | |
| 866 | − onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)} | |
| 867 | − > | |
| 868 | − <ComposerToolbarTrigger | |
| 869 | − accessibilityLabel="Model" | |
| 870 | − iconNode={ | |
| 871 | − <ProviderIcon provider={currentModelOption?.providerDriver} size={16} /> | |
| 872 | − } | |
| 873 | − label={currentModelOption?.label ?? currentModelSelection.model} | |
| 874 | − /> | |
| 875 | − </ControlPillMenu> | |
| 876 | − <ControlPillMenu | |
| 877 | − actions={optionsMenuActions} | |
| 878 | − onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)} | |
| 879 | − > | |
| 880 | − <ComposerToolbarTrigger | |
| 881 | − accessibilityLabel="Configuration" | |
| 882 | − icon="slider.horizontal.3" | |
| 883 | − label={configurationLabel} | |
| 884 | − /> | |
| 885 | − </ControlPillMenu> | |
| 795 | + <ComposerToolbarTrigger | |
| 796 | + accessibilityLabel="Thread settings" | |
| 797 | + iconNode={ | |
| 798 | + <ProviderIcon provider={currentModelOption?.providerDriver} size={16} /> | |
| 799 | + } | |
| 800 | + label={settingsSummaryLabel} | |
| 801 | + maxWidth={320} | |
| 802 | + onPress={settingsSheetPresentation.open} | |
| 803 | + /> | |
| 886 | 804 | {showStopAction ? ( |
| 887 | 805 | <ComposerToolbarButton |
| 888 | 806 | accessibilityLabel="Stop" |
| @@ -916,6 +834,21 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer · 27 unmodified lines | ||
| 916 | 834 | ) : null} |
| 917 | 835 | </Animated.View> |
| 918 | 836 | |
| 837 | + <ThreadSettingsSheet | |
| 838 | + visible={settingsSheetPresentation.isVisible} | |
| 839 | + onClose={settingsSheetPresentation.close} | |
| 840 | + onDismissed={settingsSheetPresentation.onDismissed} | |
| 841 | + providerGroups={threadProviderGroups} | |
| 842 | + selectedModel={currentModelSelection} | |
| 843 | + onSelectModel={(option) => props.onUpdateModelSelection(option.selection)} | |
| 844 | + optionDescriptors={providerOptionDescriptors} | |
| 845 | + onUpdateOptionSelections={(options) => | |
| 846 | + props.onUpdateModelSelection({ ...currentModelSelection, options }) | |
| 847 | + } | |
| 848 | + runtimeMode={currentRuntimeMode} | |
| 849 | + onUpdateRuntimeMode={props.onUpdateRuntimeMode} | |
| 850 | + /> | |
| 851 | + | |
| 919 | 852 | <ImageViewing |
| 920 | 853 | images={previewImageUri ? [{ uri: previewImageUri }] : []} |
| 921 | 854 | imageIndex={0} |
| @@ -0,0 +1,678 @@ | ||
| 1 | +import type { | |
| 2 | + ModelSelection, | |
| 3 | + ProviderInteractionMode, | |
| 4 | + ProviderOptionDescriptor, | |
| 5 | + ProviderOptionSelection, | |
| 6 | + RuntimeMode, | |
| 7 | +} from "@t3tools/contracts"; | |
| 8 | +import { | |
| 9 | + getProviderOptionCurrentLabel, | |
| 10 | + getProviderOptionCurrentValue, | |
| 11 | + getProviderOptionDescriptors, | |
| 12 | +} from "@t3tools/shared/model"; | |
| 13 | +import * as Haptics from "expo-haptics"; | |
| 14 | +import { useCallback, useEffect, useRef, useState } from "react"; | |
| 15 | +import { | |
| 16 | + Modal, | |
| 17 | + Platform, | |
| 18 | + Pressable, | |
| 19 | + ScrollView, | |
| 20 | + Switch, | |
| 21 | + useWindowDimensions, | |
| 22 | + View, | |
| 23 | +} from "react-native"; | |
| 24 | +import { useSafeAreaInsets } from "react-native-safe-area-context"; | |
| 25 | + | |
| 26 | +import { SymbolView } from "../../components/AppSymbol"; | |
| 27 | +import { AppText as Text } from "../../components/AppText"; | |
| 28 | +import { ProviderIcon } from "../../components/ProviderIcon"; | |
| 29 | +import { cn } from "../../lib/cn"; | |
| 30 | +import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; | |
| 31 | +import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions"; | |
| 32 | +import { useThemeColor } from "../../lib/useThemeColor"; | |
| 33 | +import { pendingModelAfterPress } from "./thread-settings-sheet-state"; | |
| 34 | +import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation"; | |
| 35 | + | |
| 36 | +/** | |
| 37 | + * The everyday harnesses stay expanded; every other provider (OpenRouter | |
| 38 | + * catalogs and friends) folds behind its header so a 300-model catalog can't | |
| 39 | + * bury the list. | |
| 40 | + */ | |
| 41 | +const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]); | |
| 42 | + | |
| 43 | +/** | |
| 44 | + * Desktop-oriented effort keywords that don't belong in the phone picker. | |
| 45 | + * Prompt-injected values (ultrathink and friends) are filtered from the | |
| 46 | + * descriptor metadata; ultracode is a real option but a workflow trigger, not | |
| 47 | + * a reasoning level. A value set elsewhere still displays, it just isn't | |
| 48 | + * offered. | |
| 49 | + */ | |
| 50 | +const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]); | |
| 51 | + | |
| 52 | +const RUNTIME_MODE_CHOICES: ReadonlyArray<{ | |
| 53 | + readonly mode: RuntimeMode; | |
| 54 | + readonly label: string; | |
| 55 | + readonly shortLabel: string; | |
| 56 | +}> = [ | |
| 57 | + { mode: "approval-required", label: "Approve actions", shortLabel: "Approve" }, | |
| 58 | + { mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" }, | |
| 59 | + { mode: "auto", label: "Auto", shortLabel: "Auto" }, | |
| 60 | + { mode: "full-access", label: "Full access", shortLabel: "Full" }, | |
| 61 | +]; | |
| 62 | + | |
| 63 | +/** | |
| 64 | + * Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill, | |
| 65 | + * covering model, provider options, runtime mode, and plan mode in one label. | |
| 66 | + */ | |
| 67 | +export function threadSettingsSummaryLabel(input: { | |
| 68 | + readonly modelLabel: string; | |
| 69 | + readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>; | |
| 70 | + readonly runtimeMode: RuntimeMode; | |
| 71 | + readonly interactionMode: ProviderInteractionMode; | |
| 72 | +}): string { | |
| 73 | + const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode); | |
| 74 | + return [ | |
| 75 | + input.modelLabel, | |
| 76 | + ...providerOptionValueLabels(input.optionDescriptors), | |
| 77 | + ...(runtime ? [runtime.shortLabel] : []), | |
| 78 | + ...(input.interactionMode === "plan" ? ["Plan"] : []), | |
| 79 | + ].join(" · "); | |
| 80 | +} | |
| 81 | + | |
| 82 | +function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) { | |
| 83 | + const injected = new Set(descriptor.promptInjectedValues ?? []); | |
| 84 | + return descriptor.options.filter( | |
| 85 | + (option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id), | |
| 86 | + ); | |
| 87 | +} | |
| 88 | + | |
| 89 | +function ModelRow(props: { | |
| 90 | + readonly option: ModelOption; | |
| 91 | + readonly selected: boolean; | |
| 92 | + readonly onPress: () => void; | |
| 93 | +}) { | |
| 94 | + const primaryFg = useThemeColor("--color-primary-foreground"); | |
| 95 | + return ( | |
| 96 | + <Pressable | |
| 97 | + accessibilityRole="button" | |
| 98 | + accessibilityState={{ selected: props.selected }} | |
| 99 | + onPress={props.onPress} | |
| 100 | + // Selected rows get the same primary treatment as the submenu rows. | |
| 101 | + // Subtle backgrounds (bg-subtle-strong) get overridden by the OS | |
| 102 | + // selection chrome on iOS 26, so use the explicit high-contrast style | |
| 103 | + // everywhere instead. | |
| 104 | + className={cn( | |
| 105 | + "mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70", | |
| 106 | + props.selected ? "bg-primary" : "bg-transparent", | |
| 107 | + )} | |
| 108 | + > | |
| 109 | + <Text | |
| 110 | + className={cn( | |
| 111 | + "shrink text-sm font-t3-medium", | |
| 112 | + props.selected ? "text-primary-foreground" : "text-foreground", | |
| 113 | + )} | |
| 114 | + numberOfLines={1} | |
| 115 | + > | |
| 116 | + {props.option.label} | |
| 117 | + </Text> | |
| 118 | + {props.option.isDefault ? ( | |
| 119 | + <View className="rounded-md bg-subtle-strong px-1.5 py-0.5"> | |
| 120 | + <Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text> | |
| 121 | + </View> | |
| 122 | + ) : null} | |
| 123 | + {props.option.isLegacy ? ( | |
| 124 | + <View className="rounded-md bg-subtle px-1.5 py-0.5"> | |
| 125 | + <Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text> | |
| 126 | + </View> | |
| 127 | + ) : null} | |
| 128 | + <View className="flex-1" /> | |
| 129 | + {props.selected ? ( | |
| 130 | + <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" /> | |
| 131 | + ) : null} | |
| 132 | + </Pressable> | |
| 133 | + ); | |
| 134 | +} | |
| 135 | + | |
| 136 | +/** | |
| 137 | + * Provider section header with the harness logo. Secondary providers render | |
| 138 | + * as a tappable fold (count + chevron while collapsed); primary providers | |
| 139 | + * and the group holding the current selection are static headers. | |
| 140 | + */ | |
| 141 | +function ProviderHeader(props: { | |
| 142 | + readonly driver: string | undefined; | |
| 143 | + readonly label: string; | |
| 144 | + readonly collapsible: boolean; | |
| 145 | + readonly collapsed: boolean; | |
| 146 | + readonly modelCount: number; | |
| 147 | + readonly onToggle: () => void; | |
| 148 | +}) { | |
| 149 | + const iconSubtle = useThemeColor("--color-icon-subtle"); | |
| 150 | + return ( | |
| 151 | + <Pressable | |
| 152 | + accessibilityRole={props.collapsible ? "button" : "header"} | |
| 153 | + accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined} | |
| 154 | + accessibilityLabel={ | |
| 155 | + props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label | |
| 156 | + } | |
| 157 | + disabled={!props.collapsible} | |
| 158 | + onPress={props.onToggle} | |
| 159 | + className={cn( | |
| 160 | + "mx-2.5 flex-row items-center gap-2 rounded-xl px-3", | |
| 161 | + props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4", | |
| 162 | + )} | |
| 163 | + > | |
| 164 | + <ProviderIcon provider={props.driver} size={15} /> | |
| 165 | + <Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted"> | |
| 166 | + {props.label} | |
| 167 | + </Text> | |
| 168 | + {props.collapsible ? ( | |
| 169 | + <> | |
| 170 | + <View className="flex-1" /> | |
| 171 | + {props.collapsed ? ( | |
| 172 | + <Text className="text-2xs font-t3-medium text-foreground-muted"> | |
| 173 | + {props.modelCount} | |
| 174 | + </Text> | |
| 175 | + ) : null} | |
| 176 | + <SymbolView | |
| 177 | + name={props.collapsed ? "chevron.down" : "chevron.up"} | |
| 178 | + size={11} | |
| 179 | + tintColor={iconSubtle} | |
| 180 | + type="monochrome" | |
| 181 | + /> | |
| 182 | + </> | |
| 183 | + ) : null} | |
| 184 | + </Pressable> | |
| 185 | + ); | |
| 186 | +} | |
| 187 | + | |
| 188 | +/** Compact row that opens a single-choice submenu panel. */ | |
| 189 | +function DisclosureRow(props: { | |
| 190 | + readonly label: string; | |
| 191 | + readonly value: string | undefined; | |
| 192 | + readonly disabled?: boolean; | |
| 193 | + readonly onPress: () => void; | |
| 194 | +}) { | |
| 195 | + const iconSubtle = useThemeColor("--color-icon-subtle"); | |
| 196 | + return ( | |
| 197 | + <Pressable | |
| 198 | + accessibilityRole="button" | |
| 199 | + disabled={props.disabled} | |
| 200 | + onPress={props.onPress} | |
| 201 | + className={cn( | |
| 202 | + "flex-row items-center gap-2 px-5 py-3 active:opacity-70", | |
| 203 | + props.disabled && "opacity-40", | |
| 204 | + )} | |
| 205 | + > | |
| 206 | + <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text> | |
| 207 | + <View className="flex-1" /> | |
| 208 | + {props.value ? ( | |
| 209 | + <Text className="text-sm text-foreground-muted" numberOfLines={1}> | |
| 210 | + {props.value} | |
| 211 | + </Text> | |
| 212 | + ) : null} | |
| 213 | + <SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" /> | |
| 214 | + </Pressable> | |
| 215 | + ); | |
| 216 | +} | |
| 217 | + | |
| 218 | +/** Single option inside a submenu panel. */ | |
| 219 | +function ChoiceRow(props: { | |
| 220 | + readonly label: string; | |
| 221 | + readonly selected: boolean; | |
| 222 | + readonly onPress: () => void; | |
| 223 | +}) { | |
| 224 | + const primaryFg = useThemeColor("--color-primary-foreground"); | |
| 225 | + return ( | |
| 226 | + <Pressable | |
| 227 | + accessibilityRole="button" | |
| 228 | + accessibilityState={{ selected: props.selected }} | |
| 229 | + onPress={props.onPress} | |
| 230 | + className={cn( | |
| 231 | + "mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70", | |
| 232 | + props.selected ? "bg-primary" : "bg-transparent", | |
| 233 | + )} | |
| 234 | + > | |
| 235 | + <Text | |
| 236 | + className={cn( | |
| 237 | + "shrink text-sm font-t3-medium", | |
| 238 | + props.selected ? "text-primary-foreground" : "text-foreground", | |
| 239 | + )} | |
| 240 | + > | |
| 241 | + {props.label} | |
| 242 | + </Text> | |
| 243 | + <View className="flex-1" /> | |
| 244 | + {props.selected ? ( | |
| 245 | + <SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" /> | |
| 246 | + ) : null} | |
| 247 | + </Pressable> | |
| 248 | + ); | |
| 249 | +} | |
| 250 | + | |
| 251 | +function SwitchRow(props: { | |
| 252 | + readonly label: string; | |
| 253 | + readonly value: boolean; | |
| 254 | + readonly disabled?: boolean; | |
| 255 | + readonly onValueChange: (value: boolean) => void; | |
| 256 | +}) { | |
| 257 | + const activeTrack = String(useThemeColor("--color-switch-active")); | |
| 258 | + const track = String(useThemeColor("--color-secondary-border")); | |
| 259 | + return ( | |
| 260 | + <View | |
| 261 | + className={cn( | |
| 262 | + "flex-row items-center justify-between px-5 py-2.5", | |
| 263 | + props.disabled && "opacity-40", | |
| 264 | + )} | |
| 265 | + > | |
| 266 | + <Text className="text-sm font-t3-medium text-foreground">{props.label}</Text> | |
| 267 | + <Switch | |
| 268 | + disabled={props.disabled} | |
| 269 | + ios_backgroundColor={track} | |
| 270 | + onValueChange={props.onValueChange} | |
| 271 | + trackColor={{ false: track, true: activeTrack }} | |
| 272 | + value={props.value} | |
| 273 | + /> | |
| 274 | + </View> | |
| 275 | + ); | |
| 276 | +} | |
| 277 | + | |
| 278 | +type SubmenuPage = | |
| 279 | + | { readonly kind: "descriptor"; readonly id: string } | |
| 280 | + | { readonly kind: "runtime" }; | |
| 281 | + | |
| 282 | +/** | |
| 283 | + * Unified thread settings: the sheet is the provider-grouped model list | |
| 284 | + * (primary harnesses expanded, other providers folded, legacy behind the | |
| 285 | + * top-right pill) with a Save button, plus compact disclosure rows whose | |
| 286 | + * single-choice submenus stack in a small panel over the sheet so it never | |
| 287 | + * changes size. Model changes stage until Save — while staged, the settings | |
| 288 | + * rows edit the staged model's options and Save applies everything together. | |
| 289 | + * | |
| 290 | + * Callers control which harnesses are offered via providerGroups: an | |
| 291 | + * existing thread must pass only its own provider's group, since a session | |
| 292 | + * can't switch harness mid-thread. | |
| 293 | + * | |
| 294 | + * Rendered through an RN Modal (not the root OverlayPortal) so it also | |
| 295 | + * presents above natively-presented form sheets like the new-task draft. | |
| 296 | + * Callers must dismiss the keyboard when opening — the iOS keyboard window | |
| 297 | + * would otherwise cover the lower half of the sheet. | |
| 298 | + */ | |
| 299 | +export function ThreadSettingsSheet(props: { | |
| 300 | + readonly visible: boolean; | |
| 301 | + /** | |
| 302 | + * "save" = the Save/Done button (the user is finished configuring); | |
| 303 | + * "dismiss" = backdrop, grabber, or system back. Hosts only restore the | |
| 304 | + * keyboard for "save" so a stray tap outside a control never pops it. | |
| 305 | + */ | |
| 306 | + readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void; | |
| 307 | + readonly onDismissed: () => void; | |
| 308 | + readonly providerGroups: ReadonlyArray<ProviderGroup>; | |
| 309 | + readonly selectedModel: ModelSelection | null; | |
| 310 | + readonly onSelectModel: (option: ModelOption) => void; | |
| 311 | + readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>; | |
| 312 | + readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void; | |
| 313 | + readonly runtimeMode: RuntimeMode; | |
| 314 | + readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void; | |
| 315 | +}) { | |
| 316 | + const insets = useSafeAreaInsets(); | |
| 317 | + const { height: windowHeight } = useWindowDimensions(); | |
| 318 | + const [showLegacyToggle, setShowLegacyToggle] = useState(false); | |
| 319 | + const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set()); | |
| 320 | + const [pendingModel, setPendingModel] = useState<ModelOption | null>(null); | |
| 321 | + const [submenu, setSubmenu] = useState<SubmenuPage | null>(null); | |
| 322 | + const wasPresentedRef = useRef(false); | |
| 323 | + const notifyDismissed = useCallback(() => { | |
| 324 | + if (!wasPresentedRef.current) { | |
| 325 | + return; | |
| 326 | + } | |
| 327 | + wasPresentedRef.current = false; | |
| 328 | + props.onDismissed(); | |
| 329 | + }, [props.onDismissed]); | |
| 330 | + | |
| 331 | + // Every open starts fresh: no staged model, no submenu, legacy hidden, | |
| 332 | + // secondary providers folded. The sheet stays mounted between opens, so | |
| 333 | + // state would otherwise stick around. | |
| 334 | + useEffect(() => { | |
| 335 | + if (props.visible) { | |
| 336 | + wasPresentedRef.current = true; | |
| 337 | + setShowLegacyToggle(false); | |
| 338 | + setExpandedProviders(new Set()); | |
| 339 | + setPendingModel(null); | |
| 340 | + setSubmenu(null); | |
| 341 | + } else if (Platform.OS === "android" && wasPresentedRef.current) { | |
| 342 | + // React Native only emits Modal.onDismiss on iOS. Android uses no exit | |
| 343 | + // animation below, so the post-commit effect is its dismissal boundary. | |
| 344 | + notifyDismissed(); | |
| 345 | + } | |
| 346 | + }, [notifyDismissed, props.visible]); | |
| 347 | + | |
| 348 | + const isApplied = (option: ModelOption) => | |
| 349 | + option.selection.instanceId === props.selectedModel?.instanceId && | |
| 350 | + option.selection.model === props.selectedModel.model; | |
| 351 | + // The list highlights the staged pick; Save turns it into the applied one. | |
| 352 | + const isDisplayed = (option: ModelOption) => | |
| 353 | + pendingModel ? option.key === pendingModel.key : isApplied(option); | |
| 354 | + | |
| 355 | + // While a model is staged, the settings rows describe and edit the staged | |
| 356 | + // model's options (kept on its pending selection); Save applies model and | |
| 357 | + // options together. Otherwise they edit the applied selection directly. | |
| 358 | + const displayedDescriptors = pendingModel | |
| 359 | + ? pendingModel.capabilities | |
| 360 | + ? getProviderOptionDescriptors({ | |
| 361 | + caps: pendingModel.capabilities, | |
| 362 | + selections: pendingModel.selection.options, | |
| 363 | + }) | |
| 364 | + : [] | |
| 365 | + : props.optionDescriptors; | |
| 366 | + | |
| 367 | + const hasLegacyModels = props.providerGroups.some((group) => | |
| 368 | + group.models.some((model) => model.isLegacy), | |
| 369 | + ); | |
| 370 | + // Legacy stays hidden unless the pill is toggled this open; a highlighted | |
| 371 | + // legacy model is exempted from the filter instead of forcing the whole | |
| 372 | + // legacy list visible. | |
| 373 | + const showLegacy = showLegacyToggle; | |
| 374 | + | |
| 375 | + // Stable settings rows: the union of descriptors across the primary | |
| 376 | + // harnesses' current models (plus whatever the displayed model advertises) | |
| 377 | + // always renders, with unsupported rows disabled instead of vanishing when | |
| 378 | + // the selection changes. Keyed by label, not id — Claude and Codex use | |
| 379 | + // different ids for the same "Reasoning" concept. | |
| 380 | + const descriptorTemplate = (() => { | |
| 381 | + const seen = new Map<string, { type: "select" | "boolean" }>(); | |
| 382 | + for (const group of props.providerGroups) { | |
| 383 | + const driver = group.models[0]?.providerDriver; | |
| 384 | + if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) { | |
| 385 | + continue; | |
| 386 | + } | |
| 387 | + for (const model of group.models) { | |
| 388 | + if (model.isLegacy) { | |
| 389 | + continue; | |
| 390 | + } | |
| 391 | + for (const descriptor of model.capabilities?.optionDescriptors ?? []) { | |
| 392 | + if (!seen.has(descriptor.label)) { | |
| 393 | + seen.set(descriptor.label, { type: descriptor.type }); | |
| 394 | + } | |
| 395 | + } | |
| 396 | + } | |
| 397 | + } | |
| 398 | + for (const descriptor of displayedDescriptors) { | |
| 399 | + if (!seen.has(descriptor.label)) { | |
| 400 | + seen.set(descriptor.label, { type: descriptor.type }); | |
| 401 | + } | |
| 402 | + } | |
| 403 | + return [...seen.entries()].map(([label, entry]) => ({ label, ...entry })); | |
| 404 | + })(); | |
| 405 | + | |
| 406 | + const handleSave = () => { | |
| 407 | + if (pendingModel) { | |
| 408 | + void Haptics.selectionAsync(); | |
| 409 | + props.onSelectModel(pendingModel); | |
| 410 | + } | |
| 411 | + props.onClose("save"); | |
| 412 | + }; | |
| 413 | + | |
| 414 | + const handleOptionChange = (id: string, value: string | boolean) => { | |
| 415 | + const next = applyProviderOptionSelection(displayedDescriptors, { id, value }); | |
| 416 | + if (!next) { | |
| 417 | + return; | |
| 418 | + } | |
| 419 | + if (pendingModel) { | |
| 420 | + setPendingModel({ | |
| 421 | + ...pendingModel, | |
| 422 | + selection: { ...pendingModel.selection, options: next }, | |
| 423 | + }); | |
| 424 | + } else { | |
| 425 | + props.onUpdateOptionSelections(next); | |
| 426 | + } | |
| 427 | + }; | |
| 428 | + | |
| 429 | + const toggleProvider = (providerKey: string) => { | |
| 430 | + setExpandedProviders((current) => { | |
| 431 | + const next = new Set(current); | |
| 432 | + if (!next.delete(providerKey)) { | |
| 433 | + next.add(providerKey); | |
| 434 | + } | |
| 435 | + return next; | |
| 436 | + }); | |
| 437 | + }; | |
| 438 | + | |
| 439 | + const activeDescriptor = | |
| 440 | + submenu?.kind === "descriptor" | |
| 441 | + ? displayedDescriptors.find( | |
| 442 | + (descriptor) => descriptor.type === "select" && descriptor.id === submenu.id, | |
| 443 | + ) | |
| 444 | + : undefined; | |
| 445 | + | |
| 446 | + const submenuContent = | |
| 447 | + submenu?.kind === "runtime" | |
| 448 | + ? { | |
| 449 | + title: "Runtime", | |
| 450 | + rows: RUNTIME_MODE_CHOICES.map((choice) => ({ | |
| 451 | + id: choice.mode, | |
| 452 | + label: choice.label, | |
| 453 | + selected: choice.mode === props.runtimeMode, | |
| 454 | + onPress: () => { | |
| 455 | + void Haptics.selectionAsync(); | |
| 456 | + props.onUpdateRuntimeMode(choice.mode); | |
| 457 | + setSubmenu(null); | |
| 458 | + }, | |
| 459 | + })), | |
| 460 | + } | |
| 461 | + : activeDescriptor?.type === "select" | |
| 462 | + ? { | |
| 463 | + title: activeDescriptor.label, | |
| 464 | + rows: selectableChoices(activeDescriptor).map((choice) => ({ | |
| 465 | + id: choice.id, | |
| 466 | + label: choice.label, | |
| 467 | + selected: choice.id === getProviderOptionCurrentValue(activeDescriptor), | |
| 468 | + onPress: () => { | |
| 469 | + void Haptics.selectionAsync(); | |
| 470 | + handleOptionChange(activeDescriptor.id, choice.id); | |
| 471 | + setSubmenu(null); | |
| 472 | + }, | |
| 473 | + })), | |
| 474 | + } | |
| 475 | + : null; | |
| 476 | + | |
| 477 | + return ( | |
| 478 | + <Modal | |
| 479 | + transparent | |
| 480 | + statusBarTranslucent | |
| 481 | + navigationBarTranslucent | |
| 482 | + animationType={Platform.OS === "ios" ? "fade" : "none"} | |
| 483 | + visible={props.visible} | |
| 484 | + onDismiss={notifyDismissed} | |
| 485 | + onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")} | |
| 486 | + > | |
| 487 | + <View className="flex-1 justify-end"> | |
| 488 | + <Pressable | |
| 489 | + accessibilityLabel="Close thread settings" | |
| 490 | + className="absolute inset-0 bg-backdrop" | |
| 491 | + onPress={() => props.onClose("dismiss")} | |
| 492 | + /> | |
| 493 | + <View | |
| 494 | + className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet" | |
| 495 | + style={{ maxHeight: windowHeight * 0.85 }} | |
| 496 | + > | |
| 497 | + {/* The grabber doubles as the accessible close control: the dim | |
| 498 | + backdrop above a tall sheet is a sliver, and VoiceOver can't | |
| 499 | + reach it at all. */} | |
| 500 | + <Pressable | |
| 501 | + accessibilityLabel="Close thread settings" | |
| 502 | + accessibilityRole="button" | |
| 503 | + onPress={() => props.onClose("dismiss")} | |
| 504 | + className="items-center pb-1 pt-2.5" | |
| 505 | + > | |
| 506 | + <View className="h-1 w-9 rounded-full bg-subtle-strong" /> | |
| 507 | + </Pressable> | |
| 508 | + {hasLegacyModels ? ( | |
| 509 | + <View className="flex-row justify-end px-4 pb-1.5"> | |
| 510 | + <Pressable | |
| 511 | + accessibilityRole="button" | |
| 512 | + accessibilityState={{ selected: showLegacy }} | |
| 513 | + hitSlop={8} | |
| 514 | + onPress={() => { | |
| 515 | + void Haptics.selectionAsync(); | |
| 516 | + setShowLegacyToggle(!showLegacy); | |
| 517 | + }} | |
| 518 | + className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70" | |
| 519 | + > | |
| 520 | + <Text className="text-2xs font-t3-medium text-foreground-muted"> | |
| 521 | + {showLegacy ? "Hide legacy models" : "Show legacy models"} | |
| 522 | + </Text> | |
| 523 | + </Pressable> | |
| 524 | + </View> | |
| 525 | + ) : null} | |
| 526 | + {/* Only the model list scrolls. Provider catalogs can run to | |
| 527 | + hundreds of models (OpenRouter), so the rows below stay pinned | |
| 528 | + and reachable instead of living at the end of that scroll. */} | |
| 529 | + <ScrollView | |
| 530 | + style={{ flexShrink: 1 }} | |
| 531 | + contentContainerStyle={{ paddingBottom: 8 }} | |
| 532 | + showsVerticalScrollIndicator={false} | |
| 533 | + > | |
| 534 | + {props.providerGroups.map((group) => { | |
| 535 | + const driver = group.models[0]?.providerDriver; | |
| 536 | + const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver); | |
| 537 | + const visibleModels = showLegacy | |
| 538 | + ? group.models | |
| 539 | + : group.models.filter((model) => !model.isLegacy || isDisplayed(model)); | |
| 540 | + if (visibleModels.length === 0) { | |
| 541 | + return null; | |
| 542 | + } | |
| 543 | + const containsSelection = group.models.some(isDisplayed); | |
| 544 | + const collapsible = !isPrimary && !containsSelection; | |
| 545 | + const collapsed = collapsible && !expandedProviders.has(group.providerKey); | |
| 546 | + return ( | |
| 547 | + <View key={group.providerKey}> | |
| 548 | + <ProviderHeader | |
| 549 | + driver={driver} | |
| 550 | + label={group.providerLabel} | |
| 551 | + collapsible={collapsible} | |
| 552 | + collapsed={collapsed} | |
| 553 | + modelCount={visibleModels.length} | |
| 554 | + onToggle={() => toggleProvider(group.providerKey)} | |
| 555 | + /> | |
| 556 | + {collapsed | |
| 557 | + ? null | |
| 558 | + : visibleModels.map((option) => ( | |
| 559 | + <ModelRow | |
| 560 | + key={option.key} | |
| 561 | + option={option} | |
| 562 | + selected={isDisplayed(option)} | |
| 563 | + onPress={() => { | |
| 564 | + void Haptics.selectionAsync(); | |
| 565 | + // Re-tapping the applied model cancels staging. | |
| 566 | + setPendingModel((current) => | |
| 567 | + pendingModelAfterPress({ | |
| 568 | + current, | |
| 569 | + pressed: option, | |
| 570 | + pressedIsApplied: isApplied(option), | |
| 571 | + }), | |
| 572 | + ); | |
| 573 | + }} | |
| 574 | + /> | |
| 575 | + ))} | |
| 576 | + </View> | |
| 577 | + ); | |
| 578 | + })} | |
| 579 | + </ScrollView> | |
| 580 | + | |
| 581 | + <View className="mx-5 h-px bg-border" /> | |
| 582 | + | |
| 583 | + <View style={{ paddingBottom: insets.bottom + 12 }}> | |
| 584 | + {descriptorTemplate.map((entry) => { | |
| 585 | + const live = displayedDescriptors.find( | |
| 586 | + (descriptor) => descriptor.label === entry.label, | |
| 587 | + ); | |
| 588 | + if ((live?.type ?? entry.type) === "select") { | |
| 589 | + return ( | |
| 590 | + <DisclosureRow | |
| 591 | + key={entry.label} | |
| 592 | + label={entry.label} | |
| 593 | + value={live ? getProviderOptionCurrentLabel(live) : undefined} | |
| 594 | + disabled={!live} | |
| 595 | + onPress={() => { | |
| 596 | + if (live) { | |
| 597 | + setSubmenu({ kind: "descriptor", id: live.id }); | |
| 598 | + } | |
| 599 | + }} | |
| 600 | + /> | |
| 601 | + ); | |
| 602 | + } | |
| 603 | + return ( | |
| 604 | + <SwitchRow | |
| 605 | + key={entry.label} | |
| 606 | + label={entry.label} | |
| 607 | + value={live?.type === "boolean" ? (live.currentValue ?? false) : false} | |
| 608 | + disabled={!live} | |
| 609 | + onValueChange={(value) => { | |
| 610 | + if (live) { | |
| 611 | + handleOptionChange(live.id, value); | |
| 612 | + } | |
| 613 | + }} | |
| 614 | + /> | |
| 615 | + ); | |
| 616 | + })} | |
| 617 | + <DisclosureRow | |
| 618 | + label="Runtime" | |
| 619 | + value={ | |
| 620 | + RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label | |
| 621 | + } | |
| 622 | + onPress={() => setSubmenu({ kind: "runtime" })} | |
| 623 | + /> | |
| 624 | + <Pressable | |
| 625 | + accessibilityRole="button" | |
| 626 | + onPress={handleSave} | |
| 627 | + className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80" | |
| 628 | + > | |
| 629 | + <Text className="text-sm font-t3-bold text-primary-foreground"> | |
| 630 | + {pendingModel ? "Save" : "Done"} | |
| 631 | + </Text> | |
| 632 | + </Pressable> | |
| 633 | + </View> | |
| 634 | + </View> | |
| 635 | + | |
| 636 | + {/* Submenus stack over the sheet instead of replacing its content, | |
| 637 | + so the main sheet keeps its size while drilling in and out. */} | |
| 638 | + {submenuContent ? ( | |
| 639 | + <View className="absolute inset-0 justify-end"> | |
| 640 | + <Pressable | |
| 641 | + accessibilityLabel={`Close ${submenuContent.title}`} | |
| 642 | + className="absolute inset-0 bg-backdrop" | |
| 643 | + onPress={() => setSubmenu(null)} | |
| 644 | + /> | |
| 645 | + <View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"> | |
| 646 | + <Pressable | |
| 647 | + accessibilityLabel={`Close ${submenuContent.title}`} | |
| 648 | + accessibilityRole="button" | |
| 649 | + onPress={() => setSubmenu(null)} | |
| 650 | + className="items-center pb-1 pt-2.5" | |
| 651 | + > | |
| 652 | + <View className="h-1 w-9 rounded-full bg-subtle-strong" /> | |
| 653 | + </Pressable> | |
| 654 | + <Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted"> | |
| 655 | + {submenuContent.title} | |
| 656 | + </Text> | |
| 657 | + <ScrollView | |
| 658 | + style={{ maxHeight: windowHeight * 0.5 }} | |
| 659 | + contentContainerStyle={{ paddingBottom: insets.bottom + 12 }} | |
| 660 | + showsVerticalScrollIndicator={false} | |
| 661 | + bounces={false} | |
| 662 | + > | |
| 663 | + {submenuContent.rows.map((row) => ( | |
| 664 | + <ChoiceRow | |
| 665 | + key={row.id} | |
| 666 | + label={row.label} | |
| 667 | + selected={row.selected} | |
| 668 | + onPress={row.onPress} | |
| 669 | + /> | |
| 670 | + ))} | |
| 671 | + </ScrollView> | |
| 672 | + </View> | |
| 673 | + </View> | |
| 674 | + ) : null} | |
| 675 | + </View> | |
| 676 | + </Modal> | |
| 677 | + ); | |
| 678 | +} | |
| @@ -25,6 +25,7 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions"; · 24 unmodified lines | ||
| 25 | 25 | import { |
| 26 | 26 | buildModelOptions, |
| 27 | 27 | groupByProvider, |
| 28 | + resolveDefaultableModelSelection, | |
| 28 | 29 | resolveSelectableModelSelection, |
| 29 | 30 | } from "../../lib/modelOptions"; |
| 30 | 31 | import { scopedProjectKey } from "../../lib/scopedEntities"; |
| @@ -147,7 +148,10 @@ type NewTaskFlowContextValue = { · 116 unmodified lines | ||
| 147 | 148 | readonly reset: () => void; |
| 148 | 149 | readonly setProject: (project: EnvironmentProject) => void; |
| 149 | 150 | readonly selectEnvironment: (environmentId: EnvironmentId) => void; |
| 150 | − readonly setSelectedModelKey: (key: string | null) => void; | |
| 151 | + readonly setSelectedModelKey: ( | |
| 152 | + key: string | null, | |
| 153 | + options?: ReadonlyArray<ProviderOptionSelection>, | |
| 154 | + ) => void; | |
| 151 | 155 | readonly setWorkspaceMode: (mode: WorkspaceMode) => void; |
| 152 | 156 | readonly selectBranch: (branch: VcsRef) => void; |
| 153 | 157 | readonly setStartFromOrigin: (value: boolean) => void; |
| @@ -359,14 +363,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { · 205 unmodified lines | ||
| 359 | 363 | const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE; |
| 360 | 364 | const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE; |
| 361 | 365 | |
| 362 | − // Stored selections (draft and project default) only count while their | |
| 363 | − // provider is usable on the server; otherwise the server's default model | |
| 364 | − // wins instead of silently targeting a disabled provider. | |
| 366 | + // Stored selections only count while their provider is usable on the | |
| 367 | + // server; otherwise the server's default model wins instead of silently | |
| 368 | + // targeting a disabled provider. The draft selection is an explicit pick | |
| 369 | + // and passes through as-is; the project default (last used, possibly from | |
| 370 | + // desktop) is implicit and additionally never resolves to a legacy model. | |
| 365 | 371 | const draftModelSelection = resolveSelectableModelSelection( |
| 366 | 372 | selectedEnvironmentServerConfig, |
| 367 | 373 | selectedProjectDraft.modelSelection ?? null, |
| 368 | 374 | ); |
| 369 | − const projectDefaultModelSelection = resolveSelectableModelSelection( | |
| 375 | + const projectDefaultModelSelection = resolveDefaultableModelSelection( | |
| 370 | 376 | selectedEnvironmentServerConfig, |
| 371 | 377 | selectedProject?.defaultModelSelection ?? null, |
| 372 | 378 | ); |
| @@ -404,7 +410,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { · 31 unmodified lines | ||
| 404 | 410 | [selectedEnvironmentServerConfig, selectedModel?.instanceId], |
| 405 | 411 | ); |
| 406 | 412 | const setSelectedModelKey = useCallback( |
| 407 | − (key: string | null) => { | |
| 413 | + // Options ride along in the same write: a follow-up setSelectedModelOptions | |
| 414 | + // call would rebuild the selection from the stale pre-switch model. | |
| 415 | + (key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => { | |
| 408 | 416 | if (!key || !selectedProjectDraftKey) { |
| 409 | 417 | return; |
| 410 | 418 | } |
| @@ -413,7 +421,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { · 2 unmodified lines | ||
| 413 | 421 | return; |
| 414 | 422 | } |
| 415 | 423 | updateComposerDraftSettings(selectedProjectDraftKey, { |
| 416 | − modelSelection: option.selection, | |
| 424 | + modelSelection: options ? { ...option.selection, options } : option.selection, | |
| 417 | 425 | }); |
| 418 | 426 | }, |
| 419 | 427 | [modelOptions, selectedProjectDraftKey], |
| @@ -0,0 +1,64 @@ | ||
| 1 | +import { describe, expect, it } from "vite-plus/test"; | |
| 2 | + | |
| 3 | +import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts"; | |
| 4 | + | |
| 5 | +import type { ModelOption } from "../../lib/modelOptions"; | |
| 6 | +import { pendingModelAfterPress } from "./thread-settings-sheet-state"; | |
| 7 | + | |
| 8 | +function modelOption( | |
| 9 | + model: string, | |
| 10 | + options: ReadonlyArray<ProviderOptionSelection> = [], | |
| 11 | +): ModelOption { | |
| 12 | + return { | |
| 13 | + key: `codex:${model}`, | |
| 14 | + label: model, | |
| 15 | + subtitle: "Codex", | |
| 16 | + providerKey: "codex", | |
| 17 | + providerLabel: "Codex", | |
| 18 | + providerDriver: "codex", | |
| 19 | + isDefault: false, | |
| 20 | + isLegacy: false, | |
| 21 | + capabilities: null, | |
| 22 | + selection: { | |
| 23 | + instanceId: ProviderInstanceId.make("codex"), | |
| 24 | + model, | |
| 25 | + options, | |
| 26 | + }, | |
| 27 | + }; | |
| 28 | +} | |
| 29 | + | |
| 30 | +describe("thread settings sheet state", () => { | |
| 31 | + it("clears staging when the applied model is pressed", () => { | |
| 32 | + expect( | |
| 33 | + pendingModelAfterPress({ | |
| 34 | + current: modelOption("gpt-next"), | |
| 35 | + pressed: modelOption("gpt-current"), | |
| 36 | + pressedIsApplied: true, | |
| 37 | + }), | |
| 38 | + ).toBeNull(); | |
| 39 | + }); | |
| 40 | + | |
| 41 | + it("preserves staged options when the highlighted model is pressed again", () => { | |
| 42 | + const pending = modelOption("gpt-next", [{ id: "effort", value: "high" }]); | |
| 43 | + | |
| 44 | + expect( | |
| 45 | + pendingModelAfterPress({ | |
| 46 | + current: pending, | |
| 47 | + pressed: modelOption("gpt-next"), | |
| 48 | + pressedIsApplied: false, | |
| 49 | + }), | |
| 50 | + ).toBe(pending); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("stages a different model", () => { | |
| 54 | + const pressed = modelOption("gpt-other"); | |
| 55 | + | |
| 56 | + expect( | |
| 57 | + pendingModelAfterPress({ | |
| 58 | + current: modelOption("gpt-next"), | |
| 59 | + pressed, | |
| 60 | + pressedIsApplied: false, | |
| 61 | + }), | |
| 62 | + ).toBe(pressed); | |
| 63 | + }); | |
| 64 | +}); | |
| @@ -0,0 +1,13 @@ | ||
| 1 | +import type { ModelOption } from "../../lib/modelOptions"; | |
| 2 | + | |
| 3 | +/** Preserve staged provider options when the highlighted model is tapped again. */ | |
| 4 | +export function pendingModelAfterPress(input: { | |
| 5 | + readonly current: ModelOption | null; | |
| 6 | + readonly pressed: ModelOption; | |
| 7 | + readonly pressedIsApplied: boolean; | |
| 8 | +}): ModelOption | null { | |
| 9 | + if (input.pressedIsApplied) { | |
| 10 | + return null; | |
| 11 | + } | |
| 12 | + return input.current?.key === input.pressed.key ? input.current : input.pressed; | |
| 13 | +} | |
| @@ -104,20 +104,24 @@ describe("resolveThreadListV2SnoozeMenuSelection", () => { · 103 unmodified lines | ||
| 104 | 104 | |
| 105 | 105 | describe("resolveThreadListV2Enabled", () => { |
| 106 | 106 | it("defaults on when the device has never chosen", () => { |
| 107 | − expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe( | |
| 108 | − true, | |
| 109 | − ); | |
| 107 | + expect( | |
| 108 | + resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: true }), | |
| 109 | + ).toBe(true); | |
| 110 | 110 | }); |
| 111 | 111 | |
| 112 | − it("honors an explicit device opt-out", () => { | |
| 113 | − expect(resolveThreadListV2Enabled({ preference: false, preferencesLoaded: true })).toBe(false); | |
| 114 | − expect(resolveThreadListV2Enabled({ preference: true, preferencesLoaded: true })).toBe(true); | |
| 112 | + it("honors an explicit legacy opt-in", () => { | |
| 113 | + expect(resolveThreadListV2Enabled({ legacyPreference: true, preferencesLoaded: true })).toBe( | |
| 114 | + false, | |
| 115 | + ); | |
| 116 | + expect(resolveThreadListV2Enabled({ legacyPreference: false, preferencesLoaded: true })).toBe( | |
| 117 | + true, | |
| 118 | + ); | |
| 115 | 119 | }); |
| 116 | 120 | |
| 117 | 121 | it("holds the default while preferences are still loading so the list does not remount", () => { |
| 118 | − expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: false })).toBe( | |
| 119 | − true, | |
| 120 | − ); | |
| 122 | + expect( | |
| 123 | + resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: false }), | |
| 124 | + ).toBe(true); | |
| 121 | 125 | }); |
| 122 | 126 | }); |
| 123 | 127 | |
| @@ -103,23 +103,23 @@ export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10; · 102 unmodified lines | ||
| 103 | 103 | export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25; |
| 104 | 104 | |
| 105 | 105 | /** |
| 106 | − * Thread List v2 is on by default on every app variant; the Settings → Beta | |
| 107 | − * toggle is an opt-out. Preferences persist as sparse patches, so `undefined` | |
| 108 | − * genuinely means "never chosen". | |
| 106 | + * The flat Thread List v2 is the default on every app variant; the Settings → | |
| 107 | + * Legacy toggle opts a device back into the grouped legacy list. Preferences | |
| 108 | + * persist as sparse patches, so `undefined` genuinely means "never chosen". | |
| 109 | 109 | * |
| 110 | 110 | * `preferencesLoaded` guards the startup window: preferences load |
| 111 | 111 | * asynchronously, and rendering one list before the stored choice arrives would |
| 112 | 112 | * remount the whole thing a tick later. While loading, hold the default — that |
| 113 | − * is where every device without an explicit opt-out lands anyway. | |
| 113 | + * is where every device without an explicit legacy opt-in lands anyway. | |
| 114 | 114 | */ |
| 115 | 115 | export function resolveThreadListV2Enabled(input: { |
| 116 | − readonly preference: boolean | undefined; | |
| 116 | + readonly legacyPreference: boolean | undefined; | |
| 117 | 117 | readonly preferencesLoaded: boolean; |
| 118 | 118 | }): boolean { |
| 119 | 119 | if (!input.preferencesLoaded) { |
| 120 | 120 | return true; |
| 121 | 121 | } |
| 122 | − return input.preference ?? true; | |
| 122 | + return input.legacyPreference !== true; | |
| 123 | 123 | } |
| 124 | 124 | |
| 125 | 125 | export function resolveThreadListV2Status( |
| @@ -5,15 +5,15 @@ import { mobilePreferencesAtom } from "../../state/preferences"; · 4 unmodified lines | ||
| 5 | 5 | import { resolveThreadListV2Enabled } from "./threadListV2"; |
| 6 | 6 | |
| 7 | 7 | /** |
| 8 | − * Resolved Thread List v2 state: the device-local preference if the user has | |
| 9 | − * set one, otherwise the default (on). Every consumer must read through this | |
| 8 | + * Resolved Thread List v2 state: on unless the device opted into the legacy | |
| 9 | + * grouped list (Settings → Legacy). Every consumer must read through this | |
| 10 | 10 | * rather than the raw preference, which is undefined until explicitly chosen. |
| 11 | 11 | */ |
| 12 | 12 | export function useThreadListV2Enabled(): boolean { |
| 13 | 13 | const preferencesResult = useAtomValue(mobilePreferencesAtom); |
| 14 | 14 | const loaded = AsyncResult.isSuccess(preferencesResult); |
| 15 | 15 | return resolveThreadListV2Enabled({ |
| 16 | − preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined, | |
| 16 | + legacyPreference: loaded ? preferencesResult.value.legacyThreadListEnabled : undefined, | |
| 17 | 17 | preferencesLoaded: loaded, |
| 18 | 18 | }); |
| 19 | 19 | } |
| @@ -0,0 +1,98 @@ | ||
| 1 | +import { useCallback, useEffect, useRef, useState, type RefObject } from "react"; | |
| 2 | +import { KeyboardController } from "react-native-keyboard-controller"; | |
| 3 | + | |
| 4 | +import type { ComposerEditorHandle } from "../../components/ComposerEditor"; | |
| 5 | + | |
| 6 | +export type ThreadSettingsSheetCloseReason = "save" | "dismiss"; | |
| 7 | + | |
| 8 | +type PresentationPhase = "closed" | "opening" | "visible" | "closing"; | |
| 9 | + | |
| 10 | +/** | |
| 11 | + * Keeps the custom native composer and the settings modal from owning focus at | |
| 12 | + * the same time. Opening waits for the keyboard dismissal to finish, while | |
| 13 | + * focus restoration waits for the modal's dismissal callback. | |
| 14 | + */ | |
| 15 | +export function useThreadSettingsSheetPresentation(input: { | |
| 16 | + readonly editorRef: RefObject<ComposerEditorHandle | null>; | |
| 17 | + readonly isEditorFocused: boolean; | |
| 18 | +}) { | |
| 19 | + const [phase, setPhase] = useState<PresentationPhase>("closed"); | |
| 20 | + const isActiveRef = useRef(false); | |
| 21 | + const isMountedRef = useRef(true); | |
| 22 | + const openingIdRef = useRef(0); | |
| 23 | + const restoreFocusOnSaveRef = useRef(false); | |
| 24 | + const shouldRestoreAfterDismissRef = useRef(false); | |
| 25 | + | |
| 26 | + useEffect( | |
| 27 | + () => () => { | |
| 28 | + isMountedRef.current = false; | |
| 29 | + isActiveRef.current = false; | |
| 30 | + openingIdRef.current += 1; | |
| 31 | + }, | |
| 32 | + [], | |
| 33 | + ); | |
| 34 | + | |
| 35 | + const open = useCallback(() => { | |
| 36 | + if (isActiveRef.current) { | |
| 37 | + return; | |
| 38 | + } | |
| 39 | + | |
| 40 | + isActiveRef.current = true; | |
| 41 | + restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible(); | |
| 42 | + shouldRestoreAfterDismissRef.current = false; | |
| 43 | + setPhase("opening"); | |
| 44 | + | |
| 45 | + const openingId = openingIdRef.current + 1; | |
| 46 | + openingIdRef.current = openingId; | |
| 47 | + | |
| 48 | + // Keyboard.dismiss() only tracks React Native TextInputs. The composer is | |
| 49 | + // a custom native text view, so explicitly resign its first responder too. | |
| 50 | + input.editorRef.current?.blur(); | |
| 51 | + void KeyboardController.dismiss().then(() => { | |
| 52 | + if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) { | |
| 53 | + return; | |
| 54 | + } | |
| 55 | + setPhase("visible"); | |
| 56 | + }); | |
| 57 | + }, [input.editorRef, input.isEditorFocused]); | |
| 58 | + | |
| 59 | + const close = useCallback((reason: ThreadSettingsSheetCloseReason) => { | |
| 60 | + if (!isActiveRef.current) { | |
| 61 | + return; | |
| 62 | + } | |
| 63 | + | |
| 64 | + openingIdRef.current += 1; | |
| 65 | + shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current; | |
| 66 | + setPhase("closing"); | |
| 67 | + }, []); | |
| 68 | + | |
| 69 | + const onDismissed = useCallback(() => { | |
| 70 | + const shouldRestoreFocus = shouldRestoreAfterDismissRef.current; | |
| 71 | + shouldRestoreAfterDismissRef.current = false; | |
| 72 | + restoreFocusOnSaveRef.current = false; | |
| 73 | + isActiveRef.current = false; | |
| 74 | + setPhase("closed"); | |
| 75 | + | |
| 76 | + if (shouldRestoreFocus) { | |
| 77 | + input.editorRef.current?.focus(); | |
| 78 | + } | |
| 79 | + }, [input.editorRef]); | |
| 80 | + | |
| 81 | + // The new-task screen can have an autofocus queued before the sheet opens. | |
| 82 | + // Preserve that intent for Save without allowing it to focus under the modal. | |
| 83 | + const restoreFocusAfterSave = useCallback(() => { | |
| 84 | + if (isActiveRef.current) { | |
| 85 | + restoreFocusOnSaveRef.current = true; | |
| 86 | + } | |
| 87 | + }, []); | |
| 88 | + | |
| 89 | + return { | |
| 90 | + isActive: phase !== "closed", | |
| 91 | + isActiveRef, | |
| 92 | + isVisible: phase === "visible", | |
| 93 | + open, | |
| 94 | + close, | |
| 95 | + onDismissed, | |
| 96 | + restoreFocusAfterSave, | |
| 97 | + } as const; | |
| 98 | +} | |
| @@ -3,14 +3,14 @@ import { describe, expect, it } from "vite-plus/test"; · 2 unmodified lines | ||
| 3 | 3 | import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts"; |
| 4 | 4 | |
| 5 | 5 | import { |
| 6 | − buildModelMenuActions, | |
| 7 | 6 | buildModelOptions, |
| 8 | 7 | groupByProvider, |
| 8 | + resolveDefaultableModelSelection, | |
| 9 | 9 | resolveSelectableModelSelection, |
| 10 | 10 | } from "./modelOptions"; |
| 11 | 11 | |
| 12 | 12 | describe("mobile model options", () => { |
| 13 | − it("folds legacy models into a provider-scoped menu", () => { | |
| 13 | + it("groups models by provider and flags legacy entries", () => { | |
| 14 | 14 | const config = { |
| 15 | 15 | providers: [ |
| 16 | 16 | { |
| @@ -39,51 +39,14 @@ describe("mobile model options", () => { · 22 unmodified lines | ||
| 39 | 39 | ], |
| 40 | 40 | } as unknown as ServerConfig; |
| 41 | 41 | |
| 42 | − const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null); | |
| 43 | − | |
| 44 | − expect(actions).toMatchObject([ | |
| 45 | − { | |
| 46 | − title: "Codex", | |
| 47 | − subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }], | |
| 48 | − }, | |
| 42 | + expect(groupByProvider(buildModelOptions(config, null))).toMatchObject([ | |
| 49 | 43 | { |
| 50 | − id: "legacy-models:codex", | |
| 51 | − title: "Codex legacy models", | |
| 52 | − subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }], | |
| 53 | − }, | |
| 54 | − ]); | |
| 55 | − }); | |
| 56 | − | |
| 57 | − it("omits an empty provider menu when every model is legacy", () => { | |
| 58 | − const config = { | |
| 59 | − providers: [ | |
| 60 | − { | |
| 61 | − instanceId: "codex", | |
| 62 | − driver: "codex", | |
| 63 | − displayName: "Codex", | |
| 64 | − enabled: true, | |
| 65 | − installed: true, | |
| 66 | − auth: { status: "authenticated" }, | |
| 67 | − models: [ | |
| 68 | − { | |
| 69 | − slug: "gpt-5.4", | |
| 70 | − name: "GPT-5.4", | |
| 71 | − isCustom: false, | |
| 72 | − isLegacy: true, | |
| 73 | − capabilities: null, | |
| 74 | − }, | |
| 75 | − ], | |
| 76 | − }, | |
| 77 | − ], | |
| 78 | − } as unknown as ServerConfig; | |
| 79 | − | |
| 80 | − expect( | |
| 81 | − buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null), | |
| 82 | − ).toMatchObject([ | |
| 83 | − { | |
| 84 | − id: "legacy-models:codex", | |
| 85 | − title: "Codex legacy models", | |
| 86 | − subactions: [{ id: "model:codex:gpt-5.4" }], | |
| 44 | + providerKey: "codex", | |
| 45 | + providerLabel: "Codex", | |
| 46 | + models: [ | |
| 47 | + { key: "codex:gpt-5.6-sol", label: "GPT-5.6 Sol", isLegacy: false }, | |
| 48 | + { key: "codex:gpt-5.4", label: "GPT-5.4", isLegacy: true }, | |
| 49 | + ], | |
| 87 | 50 | }, |
| 88 | 51 | ]); |
| 89 | 52 | }); |
| @@ -174,4 +137,38 @@ describe("mobile model options", () => { · 84 unmodified lines | ||
| 174 | 137 | // No config (environment offline) — nothing to validate against. |
| 175 | 138 | expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled); |
| 176 | 139 | }); |
| 140 | + | |
| 141 | + it("keeps legacy models out of implicit defaults", () => { | |
| 142 | + const config = { | |
| 143 | + providers: [ | |
| 144 | + { | |
| 145 | + instanceId: "codex", | |
| 146 | + driver: "codex", | |
| 147 | + displayName: "Codex", | |
| 148 | + enabled: true, | |
| 149 | + installed: true, | |
| 150 | + auth: { status: "authenticated" }, | |
| 151 | + models: [ | |
| 152 | + { slug: "gpt-5.6-sol", name: "GPT-5.6 Sol", isCustom: false, capabilities: null }, | |
| 153 | + { | |
| 154 | + slug: "gpt-5.4", | |
| 155 | + name: "GPT-5.4", | |
| 156 | + isCustom: false, | |
| 157 | + isLegacy: true, | |
| 158 | + capabilities: null, | |
| 159 | + }, | |
| 160 | + ], | |
| 161 | + }, | |
| 162 | + ], | |
| 163 | + } as unknown as ServerConfig; | |
| 164 | + | |
| 165 | + const current = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }; | |
| 166 | + const legacy = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }; | |
| 167 | + | |
| 168 | + expect(resolveDefaultableModelSelection(config, current)).toBe(current); | |
| 169 | + // A legacy last-used selection falls through to the provider default. | |
| 170 | + expect(resolveDefaultableModelSelection(config, legacy)).toBeNull(); | |
| 171 | + // Offline: nothing to validate against, selection passes through. | |
| 172 | + expect(resolveDefaultableModelSelection(null, legacy)).toBe(legacy); | |
| 173 | + }); | |
| 177 | 174 | }); |
| @@ -3,7 +3,6 @@ import type { · 2 unmodified lines | ||
| 3 | 3 | ModelSelection, |
| 4 | 4 | ServerConfig as T3ServerConfig, |
| 5 | 5 | } from "@t3tools/contracts"; |
| 6 | −import type { MenuAction } from "@react-native-menu/menu"; | |
| 7 | 6 | import { |
| 8 | 7 | buildProviderOptionSelectionsFromDescriptors, |
| 9 | 8 | getProviderOptionDescriptors, |
| @@ -85,6 +84,26 @@ export function resolveSelectableModelSelection( · 75 unmodified lines | ||
| 85 | 84 | : null; |
| 86 | 85 | } |
| 87 | 86 | |
| 87 | +/** | |
| 88 | + * Like resolveSelectableModelSelection, but additionally rejects legacy | |
| 89 | + * models. Used for implicit defaults (stored draft, project last-used): a | |
| 90 | + * new thread should never quietly start on a legacy model, so those fall | |
| 91 | + * through to the provider's default instead. Explicit picks in the settings | |
| 92 | + * sheet are unaffected. | |
| 93 | + */ | |
| 94 | +export function resolveDefaultableModelSelection( | |
| 95 | + config: T3ServerConfig | null | undefined, | |
| 96 | + selection: ModelSelection | null, | |
| 97 | +): ModelSelection | null { | |
| 98 | + const usable = resolveSelectableModelSelection(config, selection); | |
| 99 | + if (!usable || !config) { | |
| 100 | + return usable; | |
| 101 | + } | |
| 102 | + const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId); | |
| 103 | + const model = provider?.models.find((candidate) => candidate.slug === usable.model); | |
| 104 | + return model?.isLegacy === true ? null : usable; | |
| 105 | +} | |
| 106 | + | |
| 88 | 107 | export function buildModelOptions( |
| 89 | 108 | config: T3ServerConfig | null | undefined, |
| 90 | 109 | fallbackModelSelection: ModelSelection | null, |
| @@ -168,53 +187,3 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr · 77 unmodified lines | ||
| 168 | 187 | models: group.models, |
| 169 | 188 | })); |
| 170 | 189 | } |
| 171 | − | |
| 172 | −function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction { | |
| 173 | − return { | |
| 174 | − id: `model:${option.key}`, | |
| 175 | − title: option.label, | |
| 176 | − state: | |
| 177 | − option.selection.instanceId === selectedModel?.instanceId && | |
| 178 | − option.selection.model === selectedModel.model | |
| 179 | − ? "on" | |
| 180 | − : undefined, | |
| 181 | − }; | |
| 182 | −} | |
| 183 | − | |
| 184 | −export function buildModelMenuActions( | |
| 185 | − groups: ReadonlyArray<ProviderGroup>, | |
| 186 | − selectedModel: ModelSelection | null, | |
| 187 | −): MenuAction[] { | |
| 188 | − return groups.flatMap((group) => { | |
| 189 | − const currentModels = group.models.filter((model) => !model.isLegacy); | |
| 190 | − const legacyModels = group.models.filter((model) => model.isLegacy); | |
| 191 | − const selected = group.models.find( | |
| 192 | − (model) => | |
| 193 | − model.selection.instanceId === selectedModel?.instanceId && | |
| 194 | − model.selection.model === selectedModel.model, | |
| 195 | − ); | |
| 196 | − | |
| 197 | − return [ | |
| 198 | − ...(currentModels.length > 0 | |
| 199 | − ? [ | |
| 200 | − { | |
| 201 | − id: `provider:${group.providerKey}`, | |
| 202 | − title: group.providerLabel, | |
| 203 | − subtitle: selected && !selected.isLegacy ? selected.label : undefined, | |
| 204 | − subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)), | |
| 205 | − }, | |
| 206 | − ] | |
| 207 | − : []), | |
| 208 | − ...(legacyModels.length > 0 | |
| 209 | − ? [ | |
| 210 | − { | |
| 211 | − id: `legacy-models:${group.providerKey}`, | |
| 212 | − title: `${group.providerLabel} legacy models`, | |
| 213 | − subtitle: selected?.isLegacy ? selected.label : undefined, | |
| 214 | − subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)), | |
| 215 | − }, | |
| 216 | − ] | |
| 217 | − : []), | |
| 218 | − ]; | |
| 219 | − }); | |
| 220 | −} | |
| @@ -3,9 +3,8 @@ import { describe, expect, it } from "vite-plus/test"; · 2 unmodified lines | ||
| 3 | 3 | import type { ModelCapabilities } from "@t3tools/contracts"; |
| 4 | 4 | |
| 5 | 5 | import { |
| 6 | − applyProviderOptionMenuEvent, | |
| 7 | − buildProviderOptionMenuActions, | |
| 8 | − providerOptionsConfigurationLabel, | |
| 6 | + applyProviderOptionSelection, | |
| 7 | + providerOptionValueLabels, | |
| 9 | 8 | resolveProviderOptionDescriptors, |
| 10 | 9 | } from "./providerOptions"; |
| 11 | 10 | |
| @@ -35,31 +34,13 @@ const CODEX_CAPABILITIES: ModelCapabilities = { · 23 unmodified lines | ||
| 35 | 34 | }; |
| 36 | 35 | |
| 37 | 36 | describe("mobile provider options", () => { |
| 38 | − it("renders the option descriptors advertised by the selected model", () => { | |
| 37 | + it("summarizes the option values currently in effect", () => { | |
| 39 | 38 | const descriptors = resolveProviderOptionDescriptors({ |
| 40 | 39 | capabilities: CODEX_CAPABILITIES, |
| 41 | 40 | selections: undefined, |
| 42 | 41 | }); |
| 43 | 42 | |
| 44 | − expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([ | |
| 45 | − { | |
| 46 | − title: "Reasoning", | |
| 47 | − subtitle: "Medium", | |
| 48 | − subactions: [ | |
| 49 | − { title: "Medium (default)", state: "on" }, | |
| 50 | − { title: "High", state: undefined }, | |
| 51 | − ], | |
| 52 | − }, | |
| 53 | − { | |
| 54 | − title: "Service Tier", | |
| 55 | − subtitle: "Standard", | |
| 56 | − subactions: [ | |
| 57 | − { title: "Standard (default)", state: "on" }, | |
| 58 | − { title: "Fast", state: undefined }, | |
| 59 | − ], | |
| 60 | − }, | |
| 61 | − ]); | |
| 62 | − expect(providerOptionsConfigurationLabel(descriptors)).toBe("Medium · Standard"); | |
| 43 | + expect(providerOptionValueLabels(descriptors)).toEqual(["Medium", "Standard"]); | |
| 63 | 44 | }); |
| 64 | 45 | |
| 65 | 46 | it("updates generic select options without knowing provider-specific ids", () => { |
| @@ -67,14 +48,18 @@ describe("mobile provider options", () => { · 1 unmodified line | ||
| 67 | 48 | capabilities: CODEX_CAPABILITIES, |
| 68 | 49 | selections: undefined, |
| 69 | 50 | }); |
| 70 | − const actions = buildProviderOptionMenuActions(descriptors); | |
| 71 | − const fastEvent = actions[1]?.subactions?.[1]?.id; | |
| 72 | 51 | |
| 73 | − expect(fastEvent).toBeDefined(); | |
| 74 | − expect(applyProviderOptionMenuEvent(descriptors, fastEvent!)).toEqual([ | |
| 52 | + expect( | |
| 53 | + applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "priority" }), | |
| 54 | + ).toEqual([ | |
| 75 | 55 | { id: "reasoningEffort", value: "medium" }, |
| 76 | 56 | { id: "serviceTier", value: "priority" }, |
| 77 | 57 | ]); |
| 58 | + // Choices the model doesn't advertise are rejected, not stored. | |
| 59 | + expect( | |
| 60 | + applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "turbo" }), | |
| 61 | + ).toBeNull(); | |
| 62 | + expect(applyProviderOptionSelection(descriptors, { id: "unknown", value: "high" })).toBeNull(); | |
| 78 | 63 | }); |
| 79 | 64 | |
| 80 | 65 | it("treats an unspecified boolean capability as off", () => { |
| @@ -85,16 +70,9 @@ describe("mobile provider options", () => { · 4 unmodified lines | ||
| 85 | 70 | selections: undefined, |
| 86 | 71 | }); |
| 87 | 72 | |
| 88 | − expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([ | |
| 89 | − { | |
| 90 | − title: "Fast Mode", | |
| 91 | − subtitle: "Off", | |
| 92 | − subactions: [ | |
| 93 | − { title: "Off", state: "on" }, | |
| 94 | − { title: "On", state: undefined }, | |
| 95 | − ], | |
| 96 | − }, | |
| 73 | + expect(providerOptionValueLabels(descriptors)).toEqual([]); | |
| 74 | + expect(applyProviderOptionSelection(descriptors, { id: "fastMode", value: true })).toEqual([ | |
| 75 | + { id: "fastMode", value: true }, | |
| 97 | 76 | ]); |
| 98 | − expect(providerOptionsConfigurationLabel(descriptors)).toBe("Configuration"); | |
| 99 | 77 | }); |
| 100 | 78 | }); |
| @@ -3,48 +3,12 @@ import type { · 2 unmodified lines | ||
| 3 | 3 | ProviderOptionDescriptor, |
| 4 | 4 | ProviderOptionSelection, |
| 5 | 5 | } from "@t3tools/contracts"; |
| 6 | −import type { MenuAction } from "@react-native-menu/menu"; | |
| 7 | 6 | import { |
| 8 | 7 | buildProviderOptionSelectionsFromDescriptors, |
| 9 | 8 | getProviderOptionCurrentLabel, |
| 10 | − getProviderOptionCurrentValue, | |
| 11 | 9 | getProviderOptionDescriptors, |
| 12 | 10 | } from "@t3tools/shared/model"; |
| 13 | 11 | |
| 14 | −const PROVIDER_OPTION_EVENT_PREFIX = "provider-option:"; | |
| 15 | − | |
| 16 | −function providerOptionEvent(id: string, value: string | boolean): string { | |
| 17 | − return `${PROVIDER_OPTION_EVENT_PREFIX}${encodeURIComponent(JSON.stringify({ id, value }))}`; | |
| 18 | −} | |
| 19 | − | |
| 20 | −function parseProviderOptionEvent( | |
| 21 | − event: string, | |
| 22 | −): { readonly id: string; readonly value: string | boolean } | null { | |
| 23 | − if (!event.startsWith(PROVIDER_OPTION_EVENT_PREFIX)) { | |
| 24 | − return null; | |
| 25 | − } | |
| 26 | − | |
| 27 | − try { | |
| 28 | − const parsed: unknown = JSON.parse( | |
| 29 | − decodeURIComponent(event.slice(PROVIDER_OPTION_EVENT_PREFIX.length)), | |
| 30 | − ); | |
| 31 | − if ( | |
| 32 | − typeof parsed === "object" && | |
| 33 | − parsed !== null && | |
| 34 | − "id" in parsed && | |
| 35 | − typeof parsed.id === "string" && | |
| 36 | − "value" in parsed && | |
| 37 | − (typeof parsed.value === "string" || typeof parsed.value === "boolean") | |
| 38 | − ) { | |
| 39 | − return { id: parsed.id, value: parsed.value }; | |
| 40 | − } | |
| 41 | − } catch { | |
| 42 | − return null; | |
| 43 | − } | |
| 44 | − | |
| 45 | − return null; | |
| 46 | −} | |
| 47 | − | |
| 48 | 12 | export function resolveProviderOptionDescriptors(input: { |
| 49 | 13 | readonly capabilities: ModelCapabilities | null | undefined; |
| 50 | 14 | readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined; |
| @@ -58,72 +22,41 @@ export function resolveProviderOptionDescriptors(input: { · 7 unmodified lines | ||
| 58 | 22 | }); |
| 59 | 23 | } |
| 60 | 24 | |
| 61 | −export function buildProviderOptionMenuActions( | |
| 62 | − descriptors: ReadonlyArray<ProviderOptionDescriptor>, | |
| 63 | −): ReadonlyArray<MenuAction> { | |
| 64 | − return descriptors.map((descriptor) => { | |
| 65 | − const currentValue = | |
| 66 | − descriptor.type === "boolean" | |
| 67 | − ? (descriptor.currentValue ?? false) | |
| 68 | − : getProviderOptionCurrentValue(descriptor); | |
| 69 | − const choices = | |
| 70 | − descriptor.type === "select" | |
| 71 | − ? descriptor.options.map((option) => ({ | |
| 72 | − id: providerOptionEvent(descriptor.id, option.id), | |
| 73 | − title: `${option.label}${option.isDefault ? " (default)" : ""}`, | |
| 74 | − state: currentValue === option.id ? ("on" as const) : undefined, | |
| 75 | − })) | |
| 76 | − : ([false, true] as const).map((value) => ({ | |
| 77 | − id: providerOptionEvent(descriptor.id, value), | |
| 78 | − title: value ? "On" : "Off", | |
| 79 | − state: currentValue === value ? ("on" as const) : undefined, | |
| 80 | − })); | |
| 81 | − | |
| 82 | − return { | |
| 83 | − id: `provider-option-menu:${descriptor.id}`, | |
| 84 | − title: descriptor.label, | |
| 85 | − subtitle: | |
| 86 | − descriptor.type === "boolean" | |
| 87 | − ? currentValue | |
| 88 | − ? "On" | |
| 89 | − : "Off" | |
| 90 | − : getProviderOptionCurrentLabel(descriptor), | |
| 91 | − subactions: choices, | |
| 92 | − }; | |
| 93 | − }); | |
| 94 | −} | |
| 95 | − | |
| 96 | −export function providerOptionsConfigurationLabel( | |
| 25 | +/** | |
| 26 | + * Labels for the option values currently in effect (select values plus | |
| 27 | + * enabled booleans), used to summarize the thread configuration in the | |
| 28 | + * composer trigger pill. | |
| 29 | + */ | |
| 30 | +export function providerOptionValueLabels( | |
| 97 | 31 | descriptors: ReadonlyArray<ProviderOptionDescriptor>, |
| 98 | −): string { | |
| 99 | − const labels = descriptors.flatMap((descriptor) => { | |
| 32 | +): ReadonlyArray<string> { | |
| 33 | + return descriptors.flatMap((descriptor) => { | |
| 100 | 34 | if (descriptor.type === "boolean") { |
| 101 | 35 | return descriptor.currentValue ? [descriptor.label] : []; |
| 102 | 36 | } |
| 103 | 37 | const label = getProviderOptionCurrentLabel(descriptor); |
| 104 | 38 | return label ? [label] : []; |
| 105 | 39 | }); |
| 106 | − return labels.length > 0 ? labels.join(" · ") : "Configuration"; | |
| 107 | 40 | } |
| 108 | 41 | |
| 109 | −export function applyProviderOptionMenuEvent( | |
| 42 | +/** | |
| 43 | + * Applies one option change (by descriptor id) and returns the full selection | |
| 44 | + * list to store on the model selection, or null when the change doesn't match | |
| 45 | + * an advertised descriptor / choice. | |
| 46 | + */ | |
| 47 | +export function applyProviderOptionSelection( | |
| 110 | 48 | descriptors: ReadonlyArray<ProviderOptionDescriptor>, |
| 111 | − event: string, | |
| 49 | + change: ProviderOptionSelection, | |
| 112 | 50 | ): ReadonlyArray<ProviderOptionSelection> | null { |
| 113 | − const selection = parseProviderOptionEvent(event); | |
| 114 | − if (!selection) { | |
| 115 | − return null; | |
| 116 | − } | |
| 117 | − | |
| 118 | − const descriptor = descriptors.find((candidate) => candidate.id === selection.id); | |
| 51 | + const descriptor = descriptors.find((candidate) => candidate.id === change.id); | |
| 119 | 52 | if (!descriptor) { |
| 120 | 53 | return null; |
| 121 | 54 | } |
| 122 | 55 | if ( |
| 123 | − (descriptor.type === "boolean" && typeof selection.value !== "boolean") || | |
| 56 | + (descriptor.type === "boolean" && typeof change.value !== "boolean") || | |
| 124 | 57 | (descriptor.type === "select" && |
| 125 | − (typeof selection.value !== "string" || | |
| 126 | − !descriptor.options.some((option) => option.id === selection.value))) | |
| 58 | + (typeof change.value !== "string" || | |
| 59 | + !descriptor.options.some((option) => option.id === change.value))) | |
| 127 | 60 | ) { |
| 128 | 61 | return null; |
| 129 | 62 | } |
| @@ -132,7 +65,7 @@ export function applyProviderOptionMenuEvent( · 2 unmodified lines | ||
| 132 | 65 | candidate.id === descriptor.id |
| 133 | 66 | ? { |
| 134 | 67 | ...candidate, |
| 135 | − currentValue: selection.value, | |
| 68 | + currentValue: change.value, | |
| 136 | 69 | } |
| 137 | 70 | : candidate, |
| 138 | 71 | ) as ReadonlyArray<ProviderOptionDescriptor>; |
| @@ -27,12 +27,13 @@ export interface Preferences { · 26 unmodified lines | ||
| 27 | 27 | readonly projectGroupingEnabled?: boolean; |
| 28 | 28 | readonly projectGroupingMode?: SidebarProjectGroupingMode; |
| 29 | 29 | /** |
| 30 | − * Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no | |
| 31 | − * client-settings sync, so the flat v2 thread list is opted out of per | |
| 32 | − * device. Undefined means the user has never chosen, which resolves to on — | |
| 33 | − * see `resolveThreadListV2Enabled`. | |
| 30 | + * Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has | |
| 31 | + * no client-settings sync, so the legacy grouped thread list is opted into | |
| 32 | + * per device. Deliberately a fresh key (was `threadListV2Enabled`, an | |
| 33 | + * opt-out): sanitizing drops the old key, so every device resets to the | |
| 34 | + * default flat list — see `resolveThreadListV2Enabled`. | |
| 34 | 35 | */ |
| 35 | − readonly threadListV2Enabled?: boolean; | |
| 36 | + readonly legacyThreadListEnabled?: boolean; | |
| 36 | 37 | } |
| 37 | 38 | |
| 38 | 39 | export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()( |
| @@ -84,7 +85,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { · 45 unmodified lines | ||
| 84 | 85 | collapsedProjectGroups?: readonly string[]; |
| 85 | 86 | projectGroupingEnabled?: boolean; |
| 86 | 87 | projectGroupingMode?: SidebarProjectGroupingMode; |
| 87 | − threadListV2Enabled?: boolean; | |
| 88 | + legacyThreadListEnabled?: boolean; | |
| 88 | 89 | } = {}; |
| 89 | 90 | |
| 90 | 91 | if (typeof parsed.liveActivitiesEnabled === "boolean") { |
| @@ -121,8 +122,8 @@ function sanitizePreferences(parsed: Preferences): Preferences { · 30 unmodified lines | ||
| 121 | 122 | ) { |
| 122 | 123 | preferences.projectGroupingMode = parsed.projectGroupingMode; |
| 123 | 124 | } |
| 124 | − if (typeof parsed.threadListV2Enabled === "boolean") { | |
| 125 | − preferences.threadListV2Enabled = parsed.threadListV2Enabled; | |
| 125 | + if (typeof parsed.legacyThreadListEnabled === "boolean") { | |
| 126 | + preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled; | |
| 126 | 127 | } |
| 127 | 128 | return preferences; |
| 128 | 129 | } |
| @@ -45,6 +45,7 @@ export const RPC_REQUIRED_SCOPES = { · 44 unmodified lines | ||
| 45 | 45 | [WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope, |
| 46 | 46 | [WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope, |
| 47 | 47 | [WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope, |
| 48 | + [WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope, | |
| 48 | 49 | [WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope, |
| 49 | 50 | [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope, |
| 50 | 51 | [WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope, |
| @@ -5,6 +5,7 @@ import * as NodeChildProcess from "node:child_process"; · 4 unmodified lines | ||
| 5 | 5 | |
| 6 | 6 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 7 | 7 | import { it } from "@effect/vitest"; |
| 8 | +import * as Duration from "effect/Duration"; | |
| 8 | 9 | import * as Effect from "effect/Effect"; |
| 9 | 10 | import * as FileSystem from "effect/FileSystem"; |
| 10 | 11 | import * as Layer from "effect/Layer"; |
| @@ -948,6 +949,73 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { · 937 unmodified lines | ||
| 948 | 949 | }), |
| 949 | 950 | ); |
| 950 | 951 | |
| 952 | + it.effect("status skips the provider lookup for a branch that was never pushed", () => | |
| 953 | + Effect.gen(function* () { | |
| 954 | + const repoDir = yield* makeTempDir("t3code-git-manager-"); | |
| 955 | + yield* initRepo(repoDir); | |
| 956 | + const remoteDir = yield* createBareRemote(); | |
| 957 | + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); | |
| 958 | + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); | |
| 959 | + yield* runGit(repoDir, ["checkout", "-b", "feature/never-pushed"]); | |
| 960 | + | |
| 961 | + const { manager, ghCalls } = yield* makeManager(); | |
| 962 | + | |
| 963 | + const status = yield* manager.status({ cwd: repoDir }); | |
| 964 | + | |
| 965 | + expect(status.refName).toBe("feature/never-pushed"); | |
| 966 | + expect(status.pr).toBeNull(); | |
| 967 | + expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(0); | |
| 968 | + }), | |
| 969 | + ); | |
| 970 | + | |
| 971 | + it.effect("status still looks up PRs for a branch pushed without --set-upstream", () => | |
| 972 | + Effect.gen(function* () { | |
| 973 | + const repoDir = yield* makeTempDir("t3code-git-manager-"); | |
| 974 | + yield* initRepo(repoDir); | |
| 975 | + const remoteDir = yield* createBareRemote(); | |
| 976 | + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); | |
| 977 | + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); | |
| 978 | + yield* runGit(repoDir, ["checkout", "-b", "feature/pushed-no-upstream"]); | |
| 979 | + // No `-u`, so the remote-tracking ref exists but branch.<name>.merge does | |
| 980 | + // not. Most terminal and agent pushes land this way, and they can still | |
| 981 | + // have a PR, so the skip must not trigger here. | |
| 982 | + yield* runGit(repoDir, ["push", "origin", "feature/pushed-no-upstream"]); | |
| 983 | + | |
| 984 | + const { manager, ghCalls } = yield* makeManager({ | |
| 985 | + ghScenario: { | |
| 986 | + prListSequence: [ | |
| 987 | + // @effect-diagnostics-next-line preferSchemaOverJson:off | |
| 988 | + JSON.stringify([ | |
| 989 | + { | |
| 990 | + number: 214, | |
| 991 | + title: "Pushed without upstream", | |
| 992 | + url: "https://github.com/pingdotgg/t3code/pull/214", | |
| 993 | + baseRefName: "main", | |
| 994 | + headRefName: "feature/pushed-no-upstream", | |
| 995 | + state: "OPEN", | |
| 996 | + updatedAt: "2026-04-01T15:00:00Z", | |
| 997 | + }, | |
| 998 | + ]), | |
| 999 | + ], | |
| 1000 | + }, | |
| 1001 | + }); | |
| 1002 | + | |
| 1003 | + const status = yield* manager.status({ cwd: repoDir }); | |
| 1004 | + | |
| 1005 | + expect(status.pr?.number).toBe(214); | |
| 1006 | + expect(ghCalls.filter((call) => call.startsWith("pr list ")).length).toBeGreaterThan(0); | |
| 1007 | + }), | |
| 1008 | + ); | |
| 1009 | + | |
| 1010 | + it("backs off repeated PR lookup failures past the healthy refresh cadence", () => { | |
| 1011 | + expect(Duration.toMillis(GitManager.prLookupFailureTtl(1))).toBe(20_000); | |
| 1012 | + expect(Duration.toMillis(GitManager.prLookupFailureTtl(2))).toBe(40_000); | |
| 1013 | + // The point of the backoff: by the third retry a failing branch must not be | |
| 1014 | + // asking more often than a healthy one, which refreshes every 2 minutes. | |
| 1015 | + expect(Duration.toMillis(GitManager.prLookupFailureTtl(4))).toBeGreaterThan(120_000); | |
| 1016 | + expect(Duration.toMillis(GitManager.prLookupFailureTtl(20))).toBe(900_000); | |
| 1017 | + }); | |
| 1018 | + | |
| 951 | 1019 | it.effect( |
| 952 | 1020 | "status ignores unrelated fork PRs when the current branch tracks the same repository", |
| 953 | 1021 | () => |
| @@ -110,8 +110,25 @@ const TOAST_DESCRIPTION_MAX = 72; · 109 unmodified lines | ||
| 110 | 110 | const STATUS_RESULT_CACHE_TTL = Duration.seconds(1); |
| 111 | 111 | const STATUS_RESULT_CACHE_CAPACITY = 2_048; |
| 112 | 112 | const PR_LOOKUP_CACHE_TTL = Duration.minutes(2); |
| 113 | −const PR_LOOKUP_FAILURE_TTL = Duration.seconds(20); | |
| 113 | +const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20); | |
| 114 | +const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15); | |
| 114 | 115 | const PR_LOOKUP_CACHE_CAPACITY = 2_048; |
| 116 | + | |
| 117 | +/** | |
| 118 | + * How long a failed PR lookup is cached, given the number of consecutive | |
| 119 | + * failures for that branch. | |
| 120 | + * | |
| 121 | + * A hosting provider rejects a throttled request immediately, so caching every | |
| 122 | + * failure for a flat 20s made a rate-limited poller re-ask *faster* than a | |
| 123 | + * healthy one does (which waits PR_LOOKUP_CACHE_TTL), turning a transient 429 | |
| 124 | + * into sustained pressure. Backing off per branch keeps the retry rate below | |
| 125 | + * the healthy rate once a branch has failed more than a couple of times. | |
| 126 | + */ | |
| 127 | +export function prLookupFailureTtl(consecutiveFailures: number): Duration.Duration { | |
| 128 | + const exponent = Math.max(0, consecutiveFailures - 1); | |
| 129 | + const backoffMs = Duration.toMillis(PR_LOOKUP_FAILURE_BASE_TTL) * Math.pow(2, exponent); | |
| 130 | + return Duration.min(Duration.millis(backoffMs), PR_LOOKUP_FAILURE_MAX_TTL); | |
| 131 | +} | |
| 115 | 132 | type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never; |
| 116 | 133 | type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>; |
| 117 | 134 | type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>; |
| @@ -889,6 +906,23 @@ export const make = Effect.gen(function* () { · 771 unmodified lines | ||
| 889 | 906 | // back to a null upstreamRef. |
| 890 | 907 | const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) => |
| 891 | 908 | [cwd, details.branch, details.upstreamRef ?? "", String(prLookupEpoch(cwd))].join("\u0000"); |
| 909 | + // Consecutive failures per cache key, so a branch that keeps failing waits | |
| 910 | + // longer before the next attempt. Cleared as soon as a lookup succeeds. | |
| 911 | + const prLookupFailureStreakByKey = new Map<string, number>(); | |
| 912 | + const nextPrLookupFailureTtl = (key: string) => { | |
| 913 | + if ( | |
| 914 | + !prLookupFailureStreakByKey.has(key) && | |
| 915 | + prLookupFailureStreakByKey.size >= PR_LOOKUP_CACHE_CAPACITY | |
| 916 | + ) { | |
| 917 | + const oldestKey = prLookupFailureStreakByKey.keys().next().value; | |
| 918 | + if (oldestKey !== undefined) { | |
| 919 | + prLookupFailureStreakByKey.delete(oldestKey); | |
| 920 | + } | |
| 921 | + } | |
| 922 | + const streak = (prLookupFailureStreakByKey.get(key) ?? 0) + 1; | |
| 923 | + prLookupFailureStreakByKey.set(key, streak); | |
| 924 | + return prLookupFailureTtl(streak); | |
| 925 | + }; | |
| 892 | 926 | const prLookupCache = yield* Cache.makeWith( |
| 893 | 927 | (key: string) => { |
| 894 | 928 | const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000"); |
| @@ -896,17 +930,26 @@ export const make = Effect.gen(function* () { · 1 unmodified line | ||
| 896 | 930 | branch, |
| 897 | 931 | upstreamRef: upstreamRef.length > 0 ? upstreamRef : null, |
| 898 | 932 | }; |
| 899 | − return resolveBranchHeadContext(cwd, details).pipe( | |
| 900 | − Effect.flatMap((headContext) => | |
| 901 | − findLatestPrForHeadContext(cwd, headContext).pipe( | |
| 902 | − Effect.map((latest) => ({ latest, headContext })), | |
| 903 | − ), | |
| 904 | − ), | |
| 905 | − ); | |
| 933 | + return Effect.gen(function* () { | |
| 934 | + const headContext = yield* resolveBranchHeadContext(cwd, details); | |
| 935 | + // Only skip when the branch is untracked as well: anything carrying an | |
| 936 | + // upstream keeps the old behaviour. | |
| 937 | + if (details.upstreamRef === null && (yield* isUnpublishedBranch(cwd, headContext))) { | |
| 938 | + return { latest: null, headContext }; | |
| 939 | + } | |
| 940 | + const latest = yield* findLatestPrForHeadContext(cwd, headContext); | |
| 941 | + return { latest, headContext }; | |
| 942 | + }); | |
| 906 | 943 | }, |
| 907 | 944 | { |
| 908 | 945 | capacity: PR_LOOKUP_CACHE_CAPACITY, |
| 909 | − timeToLive: (exit) => (Exit.isSuccess(exit) ? PR_LOOKUP_CACHE_TTL : PR_LOOKUP_FAILURE_TTL), | |
| 946 | + timeToLive: (exit, key) => { | |
| 947 | + if (Exit.isSuccess(exit)) { | |
| 948 | + prLookupFailureStreakByKey.delete(key); | |
| 949 | + return PR_LOOKUP_CACHE_TTL; | |
| 950 | + } | |
| 951 | + return nextPrLookupFailureTtl(key); | |
| 952 | + }, | |
| 910 | 953 | }, |
| 911 | 954 | ); |
| 912 | 955 | // A transient lookup failure (rate limit, network blip) must not clear an |
| @@ -1169,6 +1212,43 @@ export const make = Effect.gen(function* () { · 256 unmodified lines | ||
| 1169 | 1212 | } satisfies BranchHeadContext; |
| 1170 | 1213 | }); |
| 1171 | 1214 | |
| 1215 | + /** | |
| 1216 | + * Whether git has no record of this branch on any remote, so a change request | |
| 1217 | + * cannot exist for it and asking the provider is a guaranteed-empty API call. | |
| 1218 | + * | |
| 1219 | + * `git push` writes the remote-tracking ref even without `-u` (how most | |
| 1220 | + * terminal and agent pushes land), which makes this a safer "did it ever | |
| 1221 | + * reach the host" test than looking for upstream config, and the glob spans | |
| 1222 | + * every remote so a fork branch still counts. A repository that tracks no | |
| 1223 | + * remotes at all cannot answer the question, because then every branch looks | |
| 1224 | + * unpublished; it, and any failed probe, keeps the lookup. | |
| 1225 | + */ | |
| 1226 | + const isUnpublishedBranch = Effect.fn("isUnpublishedBranch")(function* ( | |
| 1227 | + cwd: string, | |
| 1228 | + headContext: Pick<BranchHeadContext, "headBranch">, | |
| 1229 | + ) { | |
| 1230 | + if (headContext.headBranch.length === 0) { | |
| 1231 | + return false; | |
| 1232 | + } | |
| 1233 | + const matchesRef = (pattern: string) => | |
| 1234 | + gitCore | |
| 1235 | + .execute({ | |
| 1236 | + operation: "GitManager.isUnpublishedBranch", | |
| 1237 | + cwd, | |
| 1238 | + args: ["for-each-ref", "--count=1", "--format=%(refname)", pattern], | |
| 1239 | + timeoutMs: 5_000, | |
| 1240 | + }) | |
| 1241 | + .pipe(Effect.map((result) => result.stdout.trim().length > 0)); | |
| 1242 | + | |
| 1243 | + return yield* Effect.all( | |
| 1244 | + [matchesRef("refs/remotes"), matchesRef(`refs/remotes/*/${headContext.headBranch}`)], | |
| 1245 | + { concurrency: "unbounded" }, | |
| 1246 | + ).pipe( | |
| 1247 | + Effect.map(([tracksAnyRemote, tracksThisBranch]) => tracksAnyRemote && !tracksThisBranch), | |
| 1248 | + Effect.orElseSucceed(() => false), | |
| 1249 | + ); | |
| 1250 | + }); | |
| 1251 | + | |
| 1172 | 1252 | const findOpenPr = Effect.fn("findOpenPr")(function* ( |
| 1173 | 1253 | cwd: string, |
| 1174 | 1254 | headContext: Pick< |
| @@ -2199,7 +2199,7 @@ describe("ProviderRuntimeIngestion", () => { · 2198 unmodified lines | ||
| 2199 | 2199 | }); |
| 2200 | 2200 | |
| 2201 | 2201 | it("starts a new streaming assistant message segment after approval", async () => { |
| 2202 | − const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } }); | |
| 2202 | + const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } }); | |
| 2203 | 2203 | const startedAt = "2026-03-28T07:00:00.000Z"; |
| 2204 | 2204 | const pausedAt = "2026-03-28T07:00:01.000Z"; |
| 2205 | 2205 | const resumedAt = "2026-03-28T07:00:02.000Z"; |
| @@ -2306,7 +2306,7 @@ describe("ProviderRuntimeIngestion", () => { · 100 unmodified lines | ||
| 2306 | 2306 | }); |
| 2307 | 2307 | |
| 2308 | 2308 | it("streams assistant deltas when thread.turn.start requests streaming mode", async () => { |
| 2309 | − const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } }); | |
| 2309 | + const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } }); | |
| 2310 | 2310 | const now = "2026-01-01T00:00:00.000Z"; |
| 2311 | 2311 | |
| 2312 | 2312 | await Effect.runPromise( |
| @@ -1655,7 +1655,7 @@ const make = Effect.gen(function* () { · 1654 unmodified lines | ||
| 1655 | 1655 | |
| 1656 | 1656 | const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( |
| 1657 | 1657 | serverSettingsService.getSettings, |
| 1658 | − (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), | |
| 1658 | + (settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"), | |
| 1659 | 1659 | ); |
| 1660 | 1660 | if (assistantDeliveryMode === "buffered") { |
| 1661 | 1661 | const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); |
| @@ -1691,7 +1691,7 @@ const make = Effect.gen(function* () { · 29 unmodified lines | ||
| 1691 | 1691 | const detailedThread = yield* getLoadedThreadDetail(); |
| 1692 | 1692 | const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( |
| 1693 | 1693 | serverSettingsService.getSettings, |
| 1694 | − (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), | |
| 1694 | + (settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"), | |
| 1695 | 1695 | ); |
| 1696 | 1696 | const flushedMessageIds = |
| 1697 | 1697 | assistantDeliveryMode === "buffered" |
| @@ -68,6 +68,7 @@ function makeReadModel( · 67 unmodified lines | ||
| 68 | 68 | readonly lastError: string | null; |
| 69 | 69 | readonly updatedAt: string; |
| 70 | 70 | } | null; |
| 71 | + readonly backgroundLiveness?: "working" | "monitoring" | null; | |
| 71 | 72 | }>, |
| 72 | 73 | ) { |
| 73 | 74 | const now = "2026-01-01T00:00:00.000Z"; |
| @@ -109,6 +110,7 @@ function makeReadModel( · 35 unmodified lines | ||
| 109 | 110 | latestTurn: null, |
| 110 | 111 | messages: [], |
| 111 | 112 | session: thread.session, |
| 113 | + backgroundLiveness: thread.backgroundLiveness ?? null, | |
| 112 | 114 | activities: [], |
| 113 | 115 | proposedPlans: [], |
| 114 | 116 | checkpoints: [], |
| @@ -135,6 +137,14 @@ describe("ProviderSessionReaper", () => { · 20 unmodified lines | ||
| 135 | 137 | runtime = null; |
| 136 | 138 | }); |
| 137 | 139 | |
| 140 | + // Shared start sequence so each test adds no manual Effect runners | |
| 141 | + // (no-manual-effect-runtime-in-tests tracks this file's legacy count). | |
| 142 | + async function startReaper() { | |
| 143 | + const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); | |
| 144 | + scope = await Effect.runPromise(Scope.make("sequential")); | |
| 145 | + await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); | |
| 146 | + } | |
| 147 | + | |
| 138 | 148 | async function createHarness(input: { |
| 139 | 149 | readonly readModel: ReturnType<typeof makeReadModel>; |
| 140 | 150 | readonly stopSessionImplementation?: (input: { |
| @@ -261,9 +271,7 @@ describe("ProviderSessionReaper", () => { · 120 unmodified lines | ||
| 261 | 271 | }), |
| 262 | 272 | ); |
| 263 | 273 | |
| 264 | − const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); | |
| 265 | − scope = await Effect.runPromise(Scope.make("sequential")); | |
| 266 | − await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); | |
| 274 | + await startReaper(); | |
| 267 | 275 | |
| 268 | 276 | await waitFor(() => harness.stopSession.mock.calls.length === 1); |
| 269 | 277 | |
| @@ -311,9 +319,55 @@ describe("ProviderSessionReaper", () => { · 41 unmodified lines | ||
| 311 | 319 | }), |
| 312 | 320 | ); |
| 313 | 321 | |
| 314 | − const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); | |
| 315 | − scope = await Effect.runPromise(Scope.make("sequential")); | |
| 316 | − await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); | |
| 322 | + await startReaper(); | |
| 323 | + await Effect.runPromise(drainFibers); | |
| 324 | + | |
| 325 | + expect(harness.stopSession).not.toHaveBeenCalled(); | |
| 326 | + const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); | |
| 327 | + expect(Option.isSome(remaining)).toBe(true); | |
| 328 | + }); | |
| 329 | + | |
| 330 | + it("skips stale sessions while background work is still live", async () => { | |
| 331 | + const threadId = ThreadId.make("thread-reaper-background-work"); | |
| 332 | + const now = "2026-01-01T00:00:00.000Z"; | |
| 333 | + const harness = await createHarness({ | |
| 334 | + readModel: makeReadModel([ | |
| 335 | + { | |
| 336 | + id: threadId, | |
| 337 | + session: { | |
| 338 | + threadId, | |
| 339 | + status: "ready", | |
| 340 | + providerName: "claudeAgent", | |
| 341 | + runtimeMode: "full-access", | |
| 342 | + activeTurnId: null, | |
| 343 | + lastError: null, | |
| 344 | + updatedAt: now, | |
| 345 | + }, | |
| 346 | + backgroundLiveness: "working", | |
| 347 | + }, | |
| 348 | + ]), | |
| 349 | + }); | |
| 350 | + const repository = await runtime!.runPromise( | |
| 351 | + Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), | |
| 352 | + ); | |
| 353 | + | |
| 354 | + await runtime!.runPromise( | |
| 355 | + repository.upsert({ | |
| 356 | + threadId, | |
| 357 | + providerName: "claudeAgent", | |
| 358 | + providerInstanceId: null, | |
| 359 | + adapterKey: "claudeAgent", | |
| 360 | + runtimeMode: "full-access", | |
| 361 | + status: "running", | |
| 362 | + lastSeenAt: "2026-04-14T00:00:00.000Z", | |
| 363 | + resumeCursor: { | |
| 364 | + opaque: "resume-background-work", | |
| 365 | + }, | |
| 366 | + runtimePayload: null, | |
| 367 | + }), | |
| 368 | + ); | |
| 369 | + | |
| 370 | + await startReaper(); | |
| 317 | 371 | await Effect.runPromise(drainFibers); |
| 318 | 372 | |
| 319 | 373 | expect(harness.stopSession).not.toHaveBeenCalled(); |
| @@ -360,9 +414,7 @@ describe("ProviderSessionReaper", () => { · 40 unmodified lines | ||
| 360 | 414 | }), |
| 361 | 415 | ); |
| 362 | 416 | |
| 363 | − const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); | |
| 364 | − scope = await Effect.runPromise(Scope.make("sequential")); | |
| 365 | − await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); | |
| 417 | + await startReaper(); | |
| 366 | 418 | await Effect.runPromise(drainFibers); |
| 367 | 419 | |
| 368 | 420 | expect(harness.stopSession).not.toHaveBeenCalled(); |
| @@ -409,9 +461,7 @@ describe("ProviderSessionReaper", () => { · 40 unmodified lines | ||
| 409 | 461 | }), |
| 410 | 462 | ); |
| 411 | 463 | |
| 412 | − const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); | |
| 413 | − scope = await Effect.runPromise(Scope.make("sequential")); | |
| 414 | − await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); | |
| 464 | + await startReaper(); | |
| 415 | 465 | await Effect.runPromise(drainFibers); |
| 416 | 466 | |
| 417 | 467 | expect(harness.stopSession).not.toHaveBeenCalled(); |
| @@ -495,9 +545,7 @@ describe("ProviderSessionReaper", () => { · 77 unmodified lines | ||
| 495 | 545 | }), |
| 496 | 546 | ); |
| 497 | 547 | |
| 498 | − const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); | |
| 499 | − scope = await Effect.runPromise(Scope.make("sequential")); | |
| 500 | − await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); | |
| 548 | + await startReaper(); | |
| 501 | 549 | |
| 502 | 550 | await waitFor(() => harness.stopSession.mock.calls.length === 2); |
| 503 | 551 | |
| @@ -578,9 +626,7 @@ describe("ProviderSessionReaper", () => { · 74 unmodified lines | ||
| 578 | 626 | }), |
| 579 | 627 | ); |
| 580 | 628 | |
| 581 | − const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); | |
| 582 | − scope = await Effect.runPromise(Scope.make("sequential")); | |
| 583 | − await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); | |
| 629 | + await startReaper(); | |
| 584 | 630 | |
| 585 | 631 | await waitFor(() => harness.stopSession.mock.calls.length === 2); |
| 586 | 632 | |
| @@ -71,6 +71,19 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = · 70 unmodified lines | ||
| 71 | 71 | continue; |
| 72 | 72 | } |
| 73 | 73 | |
| 74 | + // The turn can settle while background work runs on (subagent | |
| 75 | + // fleets, workflow runs, Monitor watch loops). Those live inside the | |
| 76 | + // provider process, so stopping the session would kill them silently, | |
| 77 | + // and nothing bumps lastSeenAt between turns. | |
| 78 | + if (thread?.backgroundLiveness != null) { | |
| 79 | + yield* Effect.logDebug("provider.session.reaper.skipped-background-work", { | |
| 80 | + threadId: binding.threadId, | |
| 81 | + backgroundLiveness: thread.backgroundLiveness, | |
| 82 | + idleDurationMs, | |
| 83 | + }); | |
| 84 | + continue; | |
| 85 | + } | |
| 86 | + | |
| 74 | 87 | const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe( |
| 75 | 88 | Effect.tap(() => |
| 76 | 89 | Effect.logInfo("provider.session.reaped", { |
| @@ -149,6 +149,7 @@ import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryR · 148 unmodified lines | ||
| 149 | 149 | import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; |
| 150 | 150 | import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; |
| 151 | 151 | import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; |
| 152 | +import * as UsageService from "./usage/UsageService.ts"; | |
| 152 | 153 | import * as Data from "effect/Data"; |
| 153 | 154 | |
| 154 | 155 | import { makeOrchestrationIntegrationHarness } from "../integration/OrchestrationEngineHarness.integration.ts"; |
| @@ -825,6 +826,7 @@ const buildAppUnderTest = (options?: { · 670 unmodified lines | ||
| 825 | 826 | |
| 826 | 827 | const appLayer = servedRoutesLayer.pipe( |
| 827 | 828 | Layer.provide(resourceTelemetryLayer), |
| 829 | + Layer.provide(UsageService.layerTest), | |
| 828 | 830 | Layer.provide( |
| 829 | 831 | Layer.mock(BrowserTraceCollector.BrowserTraceCollector)({ |
| 830 | 832 | record: () => Effect.void, |
| @@ -101,6 +101,7 @@ import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClien · 100 unmodified lines | ||
| 101 | 101 | import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; |
| 102 | 102 | import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts"; |
| 103 | 103 | import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; |
| 104 | +import * as UsageService from "./usage/UsageService.ts"; | |
| 104 | 105 | import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts"; |
| 105 | 106 | import { |
| 106 | 107 | clearPersistedServerRuntimeState, |
| @@ -158,6 +159,8 @@ const BackgroundLayerLive = BackgroundPolicy.layer.pipe( · 51 unmodified lines | ||
| 158 | 159 | Layer.provideMerge(ServerSettingsLayerLive), |
| 159 | 160 | ); |
| 160 | 161 | |
| 162 | +const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive)); | |
| 163 | + | |
| 161 | 164 | const ResourceDiagnosticsLayerLive = Layer.mergeAll( |
| 162 | 165 | ResourceTelemetryLayerLive, |
| 163 | 166 | ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)), |
| @@ -410,6 +413,7 @@ const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe( · 246 unmodified lines | ||
| 410 | 413 | // Misc. |
| 411 | 414 | Layer.provideMerge(BackgroundLayerLive), |
| 412 | 415 | Layer.provideMerge(ResourceDiagnosticsLayerLive), |
| 416 | + Layer.provideMerge(UsageLayerLive), | |
| 413 | 417 | Layer.provideMerge(TraceDiagnostics.layer), |
| 414 | 418 | Layer.provideMerge(AnalyticsService.layer), |
| 415 | 419 | Layer.provideMerge(ExternalLauncher.layer), |
| @@ -0,0 +1,420 @@ | ||
| 1 | +/** | |
| 2 | + * UsageService - scans provider transcripts and returns priced daily usage. | |
| 3 | + * | |
| 4 | + * The scan reads the provider CLIs' own session files rather than T3 Code's | |
| 5 | + * orchestration projections, so usage covers turns driven outside T3 Code too. | |
| 6 | + * This is the approach `ccusage` takes. | |
| 7 | + * | |
| 8 | + * Transcripts are append-only, so parsed records are memoised per file by | |
| 9 | + * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm | |
| 10 | + * scans only reparse files that changed. | |
| 11 | + * | |
| 12 | + * @module UsageService | |
| 13 | + */ | |
| 14 | +import * as NodeOS from "node:os"; | |
| 15 | + | |
| 16 | +import { | |
| 17 | + USAGE_CONTRACT_VERSION, | |
| 18 | + type UsageProviderKind, | |
| 19 | + type UsageSource, | |
| 20 | + type UsageSummary, | |
| 21 | + type UsageSummaryInput, | |
| 22 | + UsageReadError, | |
| 23 | +} from "@t3tools/contracts"; | |
| 24 | +import * as Cause from "effect/Cause"; | |
| 25 | +import * as Clock from "effect/Clock"; | |
| 26 | +import * as Context from "effect/Context"; | |
| 27 | +import * as DateTime from "effect/DateTime"; | |
| 28 | +import * as Effect from "effect/Effect"; | |
| 29 | +import * as FileSystem from "effect/FileSystem"; | |
| 30 | +import * as Layer from "effect/Layer"; | |
| 31 | +import * as Option from "effect/Option"; | |
| 32 | +import * as Path from "effect/Path"; | |
| 33 | +import * as Schema from "effect/Schema"; | |
| 34 | +import { HttpClient, HttpClientResponse } from "effect/unstable/http"; | |
| 35 | + | |
| 36 | +import { ServerConfig } from "../config.ts"; | |
| 37 | +import * as ServerSettings from "../serverSettings.ts"; | |
| 38 | +import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts"; | |
| 39 | +import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; | |
| 40 | +import { UsageAggregator } from "./usageAggregation.ts"; | |
| 41 | +import { parseRateTable, type RateTable } from "./usagePricing.ts"; | |
| 42 | +import { | |
| 43 | + listTranscriptFiles, | |
| 44 | + readDirectoryVolumeId, | |
| 45 | + readTranscriptRecords, | |
| 46 | +} from "./usageTranscriptReader.ts"; | |
| 47 | +import { | |
| 48 | + decodeScanCache, | |
| 49 | + dedupeWithinFile, | |
| 50 | + encodeScanCache, | |
| 51 | + pruneScanCache, | |
| 52 | + type ScanCache, | |
| 53 | +} from "./usageScanCache.ts"; | |
| 54 | +import type { UsageRecord } from "./usageTranscripts.ts"; | |
| 55 | + | |
| 56 | +const LITELLM_RATES_URL = | |
| 57 | + "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"; | |
| 58 | + | |
| 59 | +/** Rates move rarely; a day-old table keeps the page working offline. */ | |
| 60 | +const RATES_TTL_MS = 24 * 60 * 60 * 1000; | |
| 61 | + | |
| 62 | +/** | |
| 63 | + * Files are filtered by mtime before opening. The slack covers a session whose | |
| 64 | + * last write lands just before local midnight on the window's first day. | |
| 65 | + */ | |
| 66 | +const MTIME_SLACK_MS = 36 * 60 * 60 * 1000; | |
| 67 | + | |
| 68 | +/** Longest window the UI offers, plus slack. Older entries are pruned. */ | |
| 69 | +const CACHE_RETENTION_DAYS = 90; | |
| 70 | + | |
| 71 | +/** On-disk shape of the rate snapshot. */ | |
| 72 | +const RatesCacheFile = Schema.Struct({ | |
| 73 | + fetchedAtMs: Schema.Number, | |
| 74 | + document: Schema.Unknown, | |
| 75 | +}); | |
| 76 | +const decodeRatesCache = Schema.decodeUnknownEffect( | |
| 77 | + Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>), | |
| 78 | +); | |
| 79 | +const encodeRatesCache = Schema.encodeEffect( | |
| 80 | + Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>), | |
| 81 | +); | |
| 82 | + | |
| 83 | +/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */ | |
| 84 | +const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>); | |
| 85 | +const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson); | |
| 86 | +const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson); | |
| 87 | + | |
| 88 | +export class UsageService extends Context.Service< | |
| 89 | + UsageService, | |
| 90 | + { | |
| 91 | + readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>; | |
| 92 | + } | |
| 93 | +>()("t3/usage/UsageService") {} | |
| 94 | + | |
| 95 | +/** Empty summary, for suites that only need the RPC surface to resolve. */ | |
| 96 | +export const layerTest = Layer.succeed( | |
| 97 | + UsageService, | |
| 98 | + UsageService.of({ | |
| 99 | + readSummary: (input) => | |
| 100 | + Effect.succeed({ | |
| 101 | + contractVersion: USAGE_CONTRACT_VERSION, | |
| 102 | + readAt: "1970-01-01T00:00:00.000Z", | |
| 103 | + timeZone: input.timeZone, | |
| 104 | + sinceDay: input.sinceDay, | |
| 105 | + untilDay: input.untilDay, | |
| 106 | + buckets: [], | |
| 107 | + sources: [], | |
| 108 | + pricing: { | |
| 109 | + status: "unavailable", | |
| 110 | + source: LITELLM_RATES_URL, | |
| 111 | + fetchedAt: null, | |
| 112 | + knownModels: 0, | |
| 113 | + }, | |
| 114 | + scanDurationMs: 0, | |
| 115 | + }), | |
| 116 | + }), | |
| 117 | +); | |
| 118 | + | |
| 119 | +export const make = Effect.gen(function* () { | |
| 120 | + const fileSystem = yield* FileSystem.FileSystem; | |
| 121 | + const path = yield* Path.Path; | |
| 122 | + const config = yield* ServerConfig; | |
| 123 | + const settingsService = yield* ServerSettings.ServerSettingsService; | |
| 124 | + const httpClient = yield* HttpClient.HttpClient; | |
| 125 | + | |
| 126 | + const fileCache: ScanCache = new Map(); | |
| 127 | + let cacheDirty = false; | |
| 128 | + | |
| 129 | + const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json"); | |
| 130 | + const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json"); | |
| 131 | + let rates: RateTable = new Map(); | |
| 132 | + let ratesFetchedAtMs: number | null = null; | |
| 133 | + let ratesStatus: UsageSummary["pricing"]["status"] = "unavailable"; | |
| 134 | + | |
| 135 | + /** | |
| 136 | + * Loads the LiteLLM rate table, preferring a fresh copy and falling back to | |
| 137 | + * the on-disk snapshot. With neither, every model reports as unpriced rather | |
| 138 | + * than the page failing. | |
| 139 | + */ | |
| 140 | + const ensureRates = Effect.fn("UsageService.ensureRates")(function* () { | |
| 141 | + const now = yield* Clock.currentTimeMillis; | |
| 142 | + if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < RATES_TTL_MS) return; | |
| 143 | + | |
| 144 | + if (ratesFetchedAtMs === null) { | |
| 145 | + const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe( | |
| 146 | + Effect.flatMap((raw) => decodeRatesCache(raw)), | |
| 147 | + Effect.catchCause(() => Effect.succeed(null)), | |
| 148 | + ); | |
| 149 | + if (fromDisk !== null) { | |
| 150 | + const parsed = parseRateTable(fromDisk.document); | |
| 151 | + if (parsed.size > 0) { | |
| 152 | + rates = parsed; | |
| 153 | + ratesFetchedAtMs = fromDisk.fetchedAtMs; | |
| 154 | + ratesStatus = "cached"; | |
| 155 | + if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return; | |
| 156 | + } | |
| 157 | + } | |
| 158 | + } | |
| 159 | + | |
| 160 | + const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe( | |
| 161 | + Effect.flatMap(HttpClientResponse.filterStatusOk), | |
| 162 | + Effect.flatMap((response) => response.json), | |
| 163 | + Effect.timeout(10_000), | |
| 164 | + Effect.catchCause(() => Effect.succeed(null)), | |
| 165 | + ); | |
| 166 | + if (fetched === null) { | |
| 167 | + // The refresh failed; whatever we are serving is now past its TTL and | |
| 168 | + // must not keep claiming to be fresh. | |
| 169 | + if (rates.size > 0) ratesStatus = "cached"; | |
| 170 | + return; | |
| 171 | + } | |
| 172 | + | |
| 173 | + const parsed = parseRateTable(fetched); | |
| 174 | + if (parsed.size === 0) return; | |
| 175 | + | |
| 176 | + rates = parsed; | |
| 177 | + ratesFetchedAtMs = now; | |
| 178 | + ratesStatus = "fresh"; | |
| 179 | + | |
| 180 | + yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe( | |
| 181 | + Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)), | |
| 182 | + Effect.catchCause(() => Effect.void), | |
| 183 | + ); | |
| 184 | + }); | |
| 185 | + | |
| 186 | + /** | |
| 187 | + * Claude's config dir is the home itself when overridden, but a default | |
| 188 | + * install nests transcripts under `~/.claude/projects`. Probe both. | |
| 189 | + */ | |
| 190 | + const resolveClaudeTranscriptDir = (homePath: string) => | |
| 191 | + Effect.gen(function* () { | |
| 192 | + const nested = path.join(homePath, ".claude", "projects"); | |
| 193 | + const nestedExists = yield* fileSystem | |
| 194 | + .exists(nested) | |
| 195 | + .pipe(Effect.catchCause(() => Effect.succeed(false))); | |
| 196 | + return nestedExists ? nested : path.join(homePath, "projects"); | |
| 197 | + }); | |
| 198 | + | |
| 199 | + /** Resolves the transcript directory for each provider. */ | |
| 200 | + const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* () { | |
| 201 | + // A settings failure must surface as an error: swallowing it here would | |
| 202 | + // present "zero usage from every provider" as a valid answer. | |
| 203 | + const settings = yield* settingsService.getSettings.pipe( | |
| 204 | + Effect.catchCause( | |
| 205 | + (cause) => | |
| 206 | + new UsageReadError({ | |
| 207 | + reason: "scanFailed", | |
| 208 | + // Bounded description; the squashed failure travels as the cause. | |
| 209 | + // Squashed, not the Cause tree: a full tree in a Defect field is | |
| 210 | + // the unbounded wire payload the bounded detail exists to avoid. | |
| 211 | + detail: "Server settings could not be read.", | |
| 212 | + cause: Cause.squash(cause), | |
| 213 | + }), | |
| 214 | + ), | |
| 215 | + ); | |
| 216 | + | |
| 217 | + const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent); | |
| 218 | + const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome); | |
| 219 | + const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex); | |
| 220 | + | |
| 221 | + return [ | |
| 222 | + { provider: "claude" as const, dir: claudeDir }, | |
| 223 | + { provider: "codex" as const, dir: path.join(codexLayout.sharedHomePath, "sessions") }, | |
| 224 | + ]; | |
| 225 | + }); | |
| 226 | + | |
| 227 | + /** | |
| 228 | + * Loads the persisted scan cache exactly once per process. | |
| 229 | + * | |
| 230 | + * `Effect.cached` makes concurrent first readers await the same load rather | |
| 231 | + * than each seeing a "loaded" flag set before the read finished and cold | |
| 232 | + * scanning against an empty cache. | |
| 233 | + */ | |
| 234 | + const ensureScanCacheLoaded = yield* Effect.cached( | |
| 235 | + Effect.gen(function* () { | |
| 236 | + const document = yield* fileSystem.readFileString(scanCachePath).pipe( | |
| 237 | + Effect.flatMap((raw) => decodeScanCacheFile(raw)), | |
| 238 | + Effect.catchCause(() => Effect.succeed(null)), | |
| 239 | + ); | |
| 240 | + if (document === null) return; | |
| 241 | + for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry); | |
| 242 | + }), | |
| 243 | + ); | |
| 244 | + | |
| 245 | + const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () { | |
| 246 | + if (!cacheDirty) return; | |
| 247 | + // Cleared only after the write lands, so a failed persist is retried on | |
| 248 | + // the next scan instead of leaving disk permanently stale. | |
| 249 | + yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe( | |
| 250 | + Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)), | |
| 251 | + Effect.map(() => { | |
| 252 | + cacheDirty = false; | |
| 253 | + }), | |
| 254 | + // A cache we cannot write is a slower next start, not a failed read. | |
| 255 | + Effect.catchCause(() => Effect.void), | |
| 256 | + ); | |
| 257 | + }); | |
| 258 | + | |
| 259 | + /** Parses one transcript, reusing the cached result when it is unchanged. */ | |
| 260 | + const readFileRecords = ( | |
| 261 | + filePath: string, | |
| 262 | + size: number, | |
| 263 | + mtimeMs: number, | |
| 264 | + provider: UsageProviderKind, | |
| 265 | + ): Effect.Effect<readonly UsageRecord[]> => | |
| 266 | + Effect.gen(function* () { | |
| 267 | + const cached = fileCache.get(filePath); | |
| 268 | + // Provider is part of the identity: if both providers were ever pointed | |
| 269 | + // at one directory, a hit parsed by the other parser must not be reused. | |
| 270 | + if ( | |
| 271 | + cached && | |
| 272 | + cached.size === size && | |
| 273 | + cached.mtimeMs === mtimeMs && | |
| 274 | + cached.provider === provider | |
| 275 | + ) { | |
| 276 | + return cached.records; | |
| 277 | + } | |
| 278 | + | |
| 279 | + const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider)); | |
| 280 | + // A read failure is not an empty transcript: caching it under this | |
| 281 | + // (size, mtime) would silently drop the file's usage until it changes. | |
| 282 | + if (parsed === null) return []; | |
| 283 | + // Stored already de-duplicated within the file, which is 99% of all | |
| 284 | + // duplicates. The aggregator still runs the cross-file dedupe pass. | |
| 285 | + const records = dedupeWithinFile(parsed); | |
| 286 | + | |
| 287 | + fileCache.set(filePath, { size, mtimeMs, provider, records }); | |
| 288 | + cacheDirty = true; | |
| 289 | + return records; | |
| 290 | + }); | |
| 291 | + | |
| 292 | + const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) { | |
| 293 | + if (input.sinceDay > input.untilDay) { | |
| 294 | + return yield* new UsageReadError({ | |
| 295 | + reason: "invalidWindow", | |
| 296 | + detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`, | |
| 297 | + }); | |
| 298 | + } | |
| 299 | + | |
| 300 | + const startedAtMs = yield* Clock.currentTimeMillis; | |
| 301 | + yield* ensureRates(); | |
| 302 | + yield* ensureScanCacheLoaded; | |
| 303 | + | |
| 304 | + const hostId = NodeOS.hostname(); | |
| 305 | + // The home resolvers ask for `Path` themselves; satisfy them from the | |
| 306 | + // instance we already hold so `readSummary` stays context-free. | |
| 307 | + const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path)); | |
| 308 | + const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`); | |
| 309 | + if (Option.isNone(windowStart)) { | |
| 310 | + return yield* new UsageReadError({ | |
| 311 | + reason: "invalidWindow", | |
| 312 | + detail: `sinceDay '${input.sinceDay}' is not a valid date`, | |
| 313 | + }); | |
| 314 | + } | |
| 315 | + const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS; | |
| 316 | + | |
| 317 | + const aggregator = new UsageAggregator({ | |
| 318 | + timeZone: input.timeZone, | |
| 319 | + sinceDay: input.sinceDay, | |
| 320 | + untilDay: input.untilDay, | |
| 321 | + rates, | |
| 322 | + }); | |
| 323 | + | |
| 324 | + const sources: UsageSource[] = []; | |
| 325 | + const livePaths = new Set<string>(); | |
| 326 | + const walkedRoots: string[] = []; | |
| 327 | + | |
| 328 | + for (const { provider, dir } of dirs) { | |
| 329 | + const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir)); | |
| 330 | + const exists = yield* fileSystem | |
| 331 | + .exists(dir) | |
| 332 | + .pipe(Effect.catchCause(() => Effect.succeed(false))); | |
| 333 | + | |
| 334 | + if (!exists) { | |
| 335 | + sources.push({ | |
| 336 | + fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId }, | |
| 337 | + status: "missing", | |
| 338 | + scannedFiles: 0, | |
| 339 | + skippedFiles: 0, | |
| 340 | + malformedRecords: 0, | |
| 341 | + distinctSessions: 0, | |
| 342 | + message: "No transcript directory on this environment.", | |
| 343 | + }); | |
| 344 | + continue; | |
| 345 | + } | |
| 346 | + | |
| 347 | + walkedRoots.push(dir); | |
| 348 | + const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs)); | |
| 349 | + let scannedFiles = 0; | |
| 350 | + let skippedFiles = 0; | |
| 351 | + // Distinct per directory. Buckets carry per-cell session counts, but a | |
| 352 | + // session spans days and models, so clients total this figure instead. | |
| 353 | + const sessionIds = new Set<string>(); | |
| 354 | + | |
| 355 | + for (const file of files) { | |
| 356 | + livePaths.add(file.path); | |
| 357 | + const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider); | |
| 358 | + if (records.length === 0) { | |
| 359 | + skippedFiles += 1; | |
| 360 | + continue; | |
| 361 | + } | |
| 362 | + scannedFiles += 1; | |
| 363 | + for (const record of records) { | |
| 364 | + // Only sessions that contributed in-window count: the mtime slack | |
| 365 | + // admits boundary files whose records fall outside the range. | |
| 366 | + if (aggregator.add(record) && record.sessionId.length > 0) { | |
| 367 | + sessionIds.add(record.sessionId); | |
| 368 | + } | |
| 369 | + } | |
| 370 | + } | |
| 371 | + | |
| 372 | + sources.push({ | |
| 373 | + fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId }, | |
| 374 | + status: "ok", | |
| 375 | + scannedFiles, | |
| 376 | + skippedFiles, | |
| 377 | + malformedRecords: 0, | |
| 378 | + distinctSessions: sessionIds.size, | |
| 379 | + message: null, | |
| 380 | + }); | |
| 381 | + } | |
| 382 | + | |
| 383 | + const pruned = pruneScanCache(fileCache, { | |
| 384 | + livePaths, | |
| 385 | + walkedRoots, | |
| 386 | + windowStartMs, | |
| 387 | + retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000, | |
| 388 | + }); | |
| 389 | + if (pruned > 0) cacheDirty = true; | |
| 390 | + yield* persistScanCache(); | |
| 391 | + | |
| 392 | + const aggregated = aggregator.finish(); | |
| 393 | + const readAt = yield* DateTime.now; | |
| 394 | + const finishedAtMs = yield* Clock.currentTimeMillis; | |
| 395 | + | |
| 396 | + return { | |
| 397 | + contractVersion: USAGE_CONTRACT_VERSION, | |
| 398 | + readAt: DateTime.formatIso(readAt), | |
| 399 | + timeZone: input.timeZone, | |
| 400 | + sinceDay: input.sinceDay, | |
| 401 | + untilDay: input.untilDay, | |
| 402 | + buckets: aggregated.buckets, | |
| 403 | + sources, | |
| 404 | + pricing: { | |
| 405 | + status: ratesStatus, | |
| 406 | + source: LITELLM_RATES_URL, | |
| 407 | + fetchedAt: | |
| 408 | + ratesFetchedAtMs === null | |
| 409 | + ? null | |
| 410 | + : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)), | |
| 411 | + knownModels: rates.size, | |
| 412 | + }, | |
| 413 | + scanDurationMs: Math.max(0, finishedAtMs - startedAtMs), | |
| 414 | + } satisfies UsageSummary; | |
| 415 | + }); | |
| 416 | + | |
| 417 | + return { readSummary } as const; | |
| 418 | +}); | |
| 419 | + | |
| 420 | +export const layer = Layer.effect(UsageService, make); | |
| @@ -0,0 +1,132 @@ | ||
| 1 | +import { describe, expect, it } from "@effect/vitest"; | |
| 2 | + | |
| 3 | +import { UsageAggregator } from "./usageAggregation.ts"; | |
| 4 | +import type { RateTable } from "./usagePricing.ts"; | |
| 5 | +import type { UsageRecord } from "./usageTranscripts.ts"; | |
| 6 | + | |
| 7 | +const rates: RateTable = new Map([ | |
| 8 | + [ | |
| 9 | + "claude-fable-5", | |
| 10 | + { | |
| 11 | + inputCostPerToken: 1e-5, | |
| 12 | + outputCostPerToken: 5e-5, | |
| 13 | + cacheReadCostPerToken: 1e-6, | |
| 14 | + cacheCreationCostPerToken: 1.25e-5, | |
| 15 | + }, | |
| 16 | + ], | |
| 17 | +]); | |
| 18 | + | |
| 19 | +function record(overrides: Partial<UsageRecord> = {}): UsageRecord { | |
| 20 | + return { | |
| 21 | + provider: "claude", | |
| 22 | + // 2026-08-07T04:05Z is still Aug 6 in Los Angeles. | |
| 23 | + timestampMs: Date.parse("2026-08-07T04:05:13.944Z"), | |
| 24 | + model: "claude-fable-5", | |
| 25 | + sessionId: "session-a", | |
| 26 | + totals: { | |
| 27 | + uncachedInputTokens: 100, | |
| 28 | + cachedInputTokens: 1000, | |
| 29 | + cacheCreationTokens: 10, | |
| 30 | + outputTokens: 50, | |
| 31 | + reasoningTokens: 0, | |
| 32 | + }, | |
| 33 | + reportedCostUsd: null, | |
| 34 | + dedupeKey: null, | |
| 35 | + ...overrides, | |
| 36 | + }; | |
| 37 | +} | |
| 38 | + | |
| 39 | +function aggregate(records: readonly UsageRecord[], timeZone = "UTC") { | |
| 40 | + const aggregator = new UsageAggregator({ | |
| 41 | + timeZone, | |
| 42 | + sinceDay: "2026-08-01", | |
| 43 | + untilDay: "2026-08-31", | |
| 44 | + rates, | |
| 45 | + }); | |
| 46 | + for (const item of records) aggregator.add(item); | |
| 47 | + return aggregator.finish(); | |
| 48 | +} | |
| 49 | + | |
| 50 | +describe("UsageAggregator", () => { | |
| 51 | + it("keeps only the first record for a repeated dedupe key", () => { | |
| 52 | + const result = aggregate([ | |
| 53 | + record({ dedupeKey: "msg_1:" }), | |
| 54 | + record({ dedupeKey: "msg_1:" }), | |
| 55 | + record({ dedupeKey: "msg_1:" }), | |
| 56 | + ]); | |
| 57 | + | |
| 58 | + expect(result.duplicatesDropped).toBe(2); | |
| 59 | + expect(result.buckets).toHaveLength(1); | |
| 60 | + expect(result.buckets[0]?.records).toBe(1); | |
| 61 | + expect(result.buckets[0]?.totals.outputTokens).toBe(50); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("still sums records that carry no dedupe key", () => { | |
| 65 | + const result = aggregate([record(), record()]); | |
| 66 | + | |
| 67 | + expect(result.duplicatesDropped).toBe(0); | |
| 68 | + expect(result.buckets[0]?.totals.outputTokens).toBe(100); | |
| 69 | + }); | |
| 70 | + | |
| 71 | + it("buckets by the day in the requested time zone", () => { | |
| 72 | + const utc = aggregate([record()], "UTC"); | |
| 73 | + const losAngeles = aggregate([record()], "America/Los_Angeles"); | |
| 74 | + | |
| 75 | + expect(utc.buckets[0]?.day).toBe("2026-08-07"); | |
| 76 | + expect(losAngeles.buckets[0]?.day).toBe("2026-08-06"); | |
| 77 | + }); | |
| 78 | + | |
| 79 | + it("prices against the rate table", () => { | |
| 80 | + const result = aggregate([record()]); | |
| 81 | + | |
| 82 | + // 100*1e-5 + 1000*1e-6 + 10*1.25e-5 + 50*5e-5 | |
| 83 | + expect(result.buckets[0]?.costUsd).toBeCloseTo(0.004625, 9); | |
| 84 | + expect(result.buckets[0]?.costSource).toBe("modelPriced"); | |
| 85 | + }); | |
| 86 | + | |
| 87 | + it("counts tokens but not cost for a model with no rate", () => { | |
| 88 | + const result = aggregate([record({ model: "kimi-k3" })]); | |
| 89 | + | |
| 90 | + expect(result.buckets[0]?.costUsd).toBe(0); | |
| 91 | + expect(result.buckets[0]?.costSource).toBe("unpriced"); | |
| 92 | + expect(result.buckets[0]?.unpricedRecords).toBe(1); | |
| 93 | + expect(result.buckets[0]?.totals.outputTokens).toBe(50); | |
| 94 | + }); | |
| 95 | + | |
| 96 | + it("prefers a reported cost over the rate table", () => { | |
| 97 | + const result = aggregate([record({ reportedCostUsd: 1.25 })]); | |
| 98 | + | |
| 99 | + expect(result.buckets[0]?.costUsd).toBe(1.25); | |
| 100 | + expect(result.buckets[0]?.costSource).toBe("providerReported"); | |
| 101 | + }); | |
| 102 | + | |
| 103 | + it("drops records outside the window", () => { | |
| 104 | + const result = aggregate([record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") })]); | |
| 105 | + | |
| 106 | + expect(result.outOfWindow).toBe(1); | |
| 107 | + expect(result.buckets).toHaveLength(0); | |
| 108 | + }); | |
| 109 | + | |
| 110 | + it("reports whether a record contributed", () => { | |
| 111 | + const aggregator = new UsageAggregator({ | |
| 112 | + timeZone: "UTC", | |
| 113 | + sinceDay: "2026-08-01", | |
| 114 | + untilDay: "2026-08-31", | |
| 115 | + rates, | |
| 116 | + }); | |
| 117 | + | |
| 118 | + expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(true); | |
| 119 | + expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(false); | |
| 120 | + expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false); | |
| 121 | + }); | |
| 122 | + | |
| 123 | + it("separates providers and models into their own buckets", () => { | |
| 124 | + const result = aggregate([ | |
| 125 | + record(), | |
| 126 | + record({ provider: "codex", model: "gpt-5.6-sol" }), | |
| 127 | + record({ model: "claude-opus-5" }), | |
| 128 | + ]); | |
| 129 | + | |
| 130 | + expect(result.buckets).toHaveLength(3); | |
| 131 | + }); | |
| 132 | +}); | |
Binary file not shown.
| @@ -0,0 +1,148 @@ | ||
| 1 | +/** | |
| 2 | + * Model rate lookup and cost arithmetic. | |
| 3 | + * | |
| 4 | + * Rates come from LiteLLM's `model_prices_and_context_window.json`, the same | |
| 5 | + * table `ccusage` prices against. Everything here is pure: fetching and caching | |
| 6 | + * the table lives in `UsageService`. | |
| 7 | + * | |
| 8 | + * @module usagePricing | |
| 9 | + */ | |
| 10 | +import type { UsageCostSource, UsageTokenTotals } from "@t3tools/contracts"; | |
| 11 | + | |
| 12 | +/** | |
| 13 | + * The subset of a LiteLLM entry we price against. All values are USD per token. | |
| 14 | + * | |
| 15 | + * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`, | |
| 16 | + * `*_priority`, `*_batches`). We deliberately price at the base tier: the | |
| 17 | + * transcripts don't record which tier served a request, so anything else would | |
| 18 | + * be a guess dressed up as precision. | |
| 19 | + */ | |
| 20 | +export interface ModelRate { | |
| 21 | + readonly inputCostPerToken: number; | |
| 22 | + readonly outputCostPerToken: number; | |
| 23 | + readonly cacheReadCostPerToken: number; | |
| 24 | + readonly cacheCreationCostPerToken: number; | |
| 25 | +} | |
| 26 | + | |
| 27 | +export type RateTable = ReadonlyMap<string, ModelRate>; | |
| 28 | + | |
| 29 | +/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */ | |
| 30 | +interface LiteLlmEntry { | |
| 31 | + readonly input_cost_per_token?: unknown; | |
| 32 | + readonly output_cost_per_token?: unknown; | |
| 33 | + readonly cache_read_input_token_cost?: unknown; | |
| 34 | + readonly cache_creation_input_token_cost?: unknown; | |
| 35 | +} | |
| 36 | + | |
| 37 | +function finiteNumber(value: unknown): number | null { | |
| 38 | + return typeof value === "number" && Number.isFinite(value) ? value : null; | |
| 39 | +} | |
| 40 | + | |
| 41 | +/** | |
| 42 | + * Projects the LiteLLM document into a rate table. | |
| 43 | + * | |
| 44 | + * Entries without both an input and an output rate are dropped: a half-priced | |
| 45 | + * model would silently under-report cost, which is worse than reporting the | |
| 46 | + * model as unpriced. | |
| 47 | + */ | |
| 48 | +export function parseRateTable(document: unknown): RateTable { | |
| 49 | + const table = new Map<string, ModelRate>(); | |
| 50 | + if (typeof document !== "object" || document === null) return table; | |
| 51 | + | |
| 52 | + for (const [name, raw] of Object.entries(document as Record<string, unknown>)) { | |
| 53 | + if (typeof raw !== "object" || raw === null) continue; | |
| 54 | + const entry = raw as LiteLlmEntry; | |
| 55 | + const input = finiteNumber(entry.input_cost_per_token); | |
| 56 | + const output = finiteNumber(entry.output_cost_per_token); | |
| 57 | + if (input === null || output === null) continue; | |
| 58 | + | |
| 59 | + table.set(normalizeModelName(name), { | |
| 60 | + inputCostPerToken: input, | |
| 61 | + outputCostPerToken: output, | |
| 62 | + // Anthropic bills cache reads at a discount and cache writes at a | |
| 63 | + // premium. When a model omits them, cached input is priced as plain | |
| 64 | + // input rather than as free. | |
| 65 | + cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input, | |
| 66 | + cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input, | |
| 67 | + }); | |
| 68 | + } | |
| 69 | + return table; | |
| 70 | +} | |
| 71 | + | |
| 72 | +/** | |
| 73 | + * Canonicalises a model name for lookup. | |
| 74 | + * | |
| 75 | + * Strips a `provider/` prefix (LiteLLM publishes both `claude-opus-5` and | |
| 76 | + * `anthropic/claude-opus-5`) and lowercases, since transcripts are inconsistent | |
| 77 | + * about casing. | |
| 78 | + */ | |
| 79 | +export function normalizeModelName(model: string): string { | |
| 80 | + const trimmed = model.trim().toLowerCase(); | |
| 81 | + const slash = trimmed.lastIndexOf("/"); | |
| 82 | + return slash === -1 ? trimmed : trimmed.slice(slash + 1); | |
| 83 | +} | |
| 84 | + | |
| 85 | +/** | |
| 86 | + * Models we never price, regardless of the table. | |
| 87 | + * | |
| 88 | + * `<synthetic>` marks locally generated messages that were never billed. Bare | |
| 89 | + * family names ("opus", "sonnet") are genuinely ambiguous across generations, | |
| 90 | + * so we report them as unpriced instead of guessing a generation. | |
| 91 | + */ | |
| 92 | +const UNPRICEABLE_MODELS = new Set([ | |
| 93 | + "<synthetic>", | |
| 94 | + "synthetic", | |
| 95 | + "opus", | |
| 96 | + "sonnet", | |
| 97 | + "haiku", | |
| 98 | + "fable", | |
| 99 | +]); | |
| 100 | + | |
| 101 | +export function lookupRate(table: RateTable, model: string): ModelRate | null { | |
| 102 | + const normalized = normalizeModelName(model); | |
| 103 | + if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null; | |
| 104 | + return table.get(normalized) ?? null; | |
| 105 | +} | |
| 106 | + | |
| 107 | +export interface PricedUsage { | |
| 108 | + readonly costUsd: number; | |
| 109 | + readonly costSource: UsageCostSource; | |
| 110 | +} | |
| 111 | + | |
| 112 | +/** | |
| 113 | + * Prices a bucket's tokens. | |
| 114 | + * | |
| 115 | + * `reasoningTokens` is intentionally not charged separately: it is already | |
| 116 | + * counted inside `outputTokens`. | |
| 117 | + */ | |
| 118 | +export function priceUsage( | |
| 119 | + table: RateTable, | |
| 120 | + model: string, | |
| 121 | + totals: UsageTokenTotals, | |
| 122 | + reportedCostUsd: number | null, | |
| 123 | +): PricedUsage { | |
| 124 | + if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) { | |
| 125 | + return { costUsd: reportedCostUsd, costSource: "providerReported" }; | |
| 126 | + } | |
| 127 | + | |
| 128 | + const rate = lookupRate(table, model); | |
| 129 | + if (rate === null) return { costUsd: 0, costSource: "unpriced" }; | |
| 130 | + | |
| 131 | + const costUsd = | |
| 132 | + totals.uncachedInputTokens * rate.inputCostPerToken + | |
| 133 | + totals.cachedInputTokens * rate.cacheReadCostPerToken + | |
| 134 | + totals.cacheCreationTokens * rate.cacheCreationCostPerToken + | |
| 135 | + totals.outputTokens * rate.outputCostPerToken; | |
| 136 | + | |
| 137 | + return { costUsd, costSource: "modelPriced" }; | |
| 138 | +} | |
| 139 | + | |
| 140 | +/** | |
| 141 | + * What the cached input would have cost at full input rates, minus what it | |
| 142 | + * actually cost. Drives the "cache savings" figure. | |
| 143 | + */ | |
| 144 | +export function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number { | |
| 145 | + const rate = lookupRate(table, model); | |
| 146 | + if (rate === null) return 0; | |
| 147 | + return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken); | |
| 148 | +} | |
| @@ -0,0 +1,206 @@ | ||
| 1 | +import { describe, expect, it } from "@effect/vitest"; | |
| 2 | + | |
| 3 | +import { | |
| 4 | + decodeScanCache, | |
| 5 | + dedupeWithinFile, | |
| 6 | + encodeScanCache, | |
| 7 | + pruneScanCache, | |
| 8 | + type ScanCache, | |
| 9 | +} from "./usageScanCache.ts"; | |
| 10 | +import type { UsageRecord } from "./usageTranscripts.ts"; | |
| 11 | + | |
| 12 | +function record(overrides: Partial<UsageRecord> = {}): UsageRecord { | |
| 13 | + return { | |
| 14 | + provider: "claude", | |
| 15 | + timestampMs: 1_786_000_000_000, | |
| 16 | + model: "claude-fable-5", | |
| 17 | + sessionId: "session-a", | |
| 18 | + totals: { | |
| 19 | + uncachedInputTokens: 2, | |
| 20 | + cachedInputTokens: 1000, | |
| 21 | + cacheCreationTokens: 10, | |
| 22 | + outputTokens: 50, | |
| 23 | + reasoningTokens: 0, | |
| 24 | + }, | |
| 25 | + reportedCostUsd: null, | |
| 26 | + dedupeKey: "msg_1:", | |
| 27 | + ...overrides, | |
| 28 | + }; | |
| 29 | +} | |
| 30 | + | |
| 31 | +function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]): ScanCache { | |
| 32 | + const cache: ScanCache = new Map(); | |
| 33 | + for (const [path, mtimeMs, records] of entries) { | |
| 34 | + cache.set(path, { size: records.length * 10, mtimeMs, provider: "claude", records }); | |
| 35 | + } | |
| 36 | + return cache; | |
| 37 | +} | |
| 38 | + | |
| 39 | +describe("scan cache round trip", () => { | |
| 40 | + it("restores records unchanged", () => { | |
| 41 | + const original = cacheWith([ | |
| 42 | + ["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5" })]], | |
| 43 | + ["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]], | |
| 44 | + ]); | |
| 45 | + | |
| 46 | + const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original)))); | |
| 47 | + | |
| 48 | + expect(restored.size).toBe(2); | |
| 49 | + expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl")); | |
| 50 | + expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl")); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("interns repeated model and session strings", () => { | |
| 54 | + const encoded = encodeScanCache( | |
| 55 | + cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]), | |
| 56 | + ); | |
| 57 | + | |
| 58 | + expect(encoded.models).toEqual(["claude-fable-5"]); | |
| 59 | + expect(encoded.sessions).toEqual(["session-a"]); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + it("treats a corrupt or foreign document as an empty cache", () => { | |
| 63 | + // A bad cache should cost one cold scan, never a broken page. | |
| 64 | + expect(decodeScanCache(null).size).toBe(0); | |
| 65 | + expect(decodeScanCache("nonsense").size).toBe(0); | |
| 66 | + expect(decodeScanCache({ version: 999, models: [], sessions: [], files: {} }).size).toBe(0); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + it("skips malformed file entries but keeps good ones", () => { | |
| 70 | + const encoded = encodeScanCache(cacheWith([["/good.jsonl", 100, [record()]]])); | |
| 71 | + const withJunk = { | |
| 72 | + ...encoded, | |
| 73 | + files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } }, | |
| 74 | + }; | |
| 75 | + | |
| 76 | + const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk))); | |
| 77 | + expect([...restored.keys()]).toEqual(["/good.jsonl"]); | |
| 78 | + }); | |
| 79 | + | |
| 80 | + it("rejects the whole cache when an intern table holds a non-string", () => { | |
| 81 | + // models: [1] would pass the undefined guard, put a number in a record's | |
| 82 | + // model, and crash normalizeModelName at aggregate time. | |
| 83 | + const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]])); | |
| 84 | + const poisoned = { ...encoded, models: [1] }; | |
| 85 | + | |
| 86 | + expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned))).size).toBe(0); | |
| 87 | + }); | |
| 88 | + | |
| 89 | + it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => { | |
| 90 | + // Keeping the surviving rows under the original (size, mtime) would read | |
| 91 | + // as a valid warm hit and the file would never be re-parsed. | |
| 92 | + const encoded = encodeScanCache( | |
| 93 | + cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]), | |
| 94 | + ); | |
| 95 | + const rows = encoded.files["/a.jsonl"]!.r; | |
| 96 | + const poisoned = { | |
| 97 | + ...encoded, | |
| 98 | + files: { | |
| 99 | + "/a.jsonl": { | |
| 100 | + ...encoded.files["/a.jsonl"]!, | |
| 101 | + r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]], | |
| 102 | + }, | |
| 103 | + }, | |
| 104 | + }; | |
| 105 | + | |
| 106 | + const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned))); | |
| 107 | + expect(restored.has("/a.jsonl")).toBe(false); | |
| 108 | + }); | |
| 109 | +}); | |
| 110 | + | |
| 111 | +describe("pruneScanCache", () => { | |
| 112 | + const retentionCutoffMs = 1000; | |
| 113 | + | |
| 114 | + it("drops entries older than retention", () => { | |
| 115 | + const cache = cacheWith([["/old.jsonl", 500, [record()]]]); | |
| 116 | + | |
| 117 | + const removed = pruneScanCache(cache, { | |
| 118 | + livePaths: new Set(), | |
| 119 | + walkedRoots: ["/"], | |
| 120 | + windowStartMs: 400, | |
| 121 | + retentionCutoffMs, | |
| 122 | + }); | |
| 123 | + | |
| 124 | + expect(removed).toBe(1); | |
| 125 | + expect(cache.size).toBe(0); | |
| 126 | + }); | |
| 127 | + | |
| 128 | + it("drops in-window entries whose file has disappeared", () => { | |
| 129 | + const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]); | |
| 130 | + | |
| 131 | + pruneScanCache(cache, { | |
| 132 | + livePaths: new Set(), | |
| 133 | + walkedRoots: ["/"], | |
| 134 | + windowStartMs: 4000, | |
| 135 | + retentionCutoffMs, | |
| 136 | + }); | |
| 137 | + | |
| 138 | + expect(cache.size).toBe(0); | |
| 139 | + }); | |
| 140 | + | |
| 141 | + it("keeps entries outside the walked window that are still within retention", () => { | |
| 142 | + // Viewing 7 days must not evict the 30-day entries, which that walk never | |
| 143 | + // looked for and so cannot prove are gone. | |
| 144 | + const cache = cacheWith([["/older-but-valid.jsonl", 2000, [record()]]]); | |
| 145 | + | |
| 146 | + const removed = pruneScanCache(cache, { | |
| 147 | + livePaths: new Set(), | |
| 148 | + walkedRoots: ["/"], | |
| 149 | + windowStartMs: 4000, | |
| 150 | + retentionCutoffMs, | |
| 151 | + }); | |
| 152 | + | |
| 153 | + expect(removed).toBe(0); | |
| 154 | + expect(cache.size).toBe(1); | |
| 155 | + }); | |
| 156 | + | |
| 157 | + it("keeps entries the walk saw", () => { | |
| 158 | + const cache = cacheWith([["/live.jsonl", 5000, [record()]]]); | |
| 159 | + | |
| 160 | + pruneScanCache(cache, { | |
| 161 | + livePaths: new Set(["/live.jsonl"]), | |
| 162 | + walkedRoots: ["/"], | |
| 163 | + windowStartMs: 4000, | |
| 164 | + retentionCutoffMs, | |
| 165 | + }); | |
| 166 | + | |
| 167 | + expect(cache.size).toBe(1); | |
| 168 | + }); | |
| 169 | +}); | |
| 170 | + | |
| 171 | +describe("pruneScanCache with an unwalked root", () => { | |
| 172 | + it("keeps in-window entries for a provider whose directory was not walked", () => { | |
| 173 | + // A missing provider root or failed settings read leaves livePaths without | |
| 174 | + // that provider's files. Its warm entries must survive the pass. | |
| 175 | + const cache = cacheWith([["/codex/sessions/a.jsonl", 5000, [record()]]]); | |
| 176 | + | |
| 177 | + const removed = pruneScanCache(cache, { | |
| 178 | + livePaths: new Set(), | |
| 179 | + walkedRoots: ["/claude/projects"], | |
| 180 | + windowStartMs: 4000, | |
| 181 | + retentionCutoffMs: 1000, | |
| 182 | + }); | |
| 183 | + | |
| 184 | + expect(removed).toBe(0); | |
| 185 | + expect(cache.size).toBe(1); | |
| 186 | + }); | |
| 187 | +}); | |
| 188 | + | |
| 189 | +describe("dedupeWithinFile", () => { | |
| 190 | + it("keeps the first record per dedupe key", () => { | |
| 191 | + const kept = dedupeWithinFile([ | |
| 192 | + record({ totals: { ...record().totals, outputTokens: 1 } }), | |
| 193 | + record({ totals: { ...record().totals, outputTokens: 999 } }), | |
| 194 | + record({ dedupeKey: "msg_2:" }), | |
| 195 | + ]); | |
| 196 | + | |
| 197 | + expect(kept).toHaveLength(2); | |
| 198 | + expect(kept[0]?.totals.outputTokens).toBe(1); | |
| 199 | + }); | |
| 200 | + | |
| 201 | + it("keeps every record that has no dedupe key", () => { | |
| 202 | + expect( | |
| 203 | + dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]), | |
| 204 | + ).toHaveLength(2); | |
| 205 | + }); | |
| 206 | +}); | |
| @@ -0,0 +1,253 @@ | ||
| 1 | +/** | |
| 2 | + * Durable per-file scan cache. | |
| 3 | + * | |
| 4 | + * Transcripts are append-only and a file that has not changed can never yield | |
| 5 | + * different usage, so parsed records are keyed by `(size, mtime)` and reused. | |
| 6 | + * Without this every server restart re-parses the whole window: roughly 3.5s | |
| 7 | + * for a 30-day scan here, against ~11ms to reload this cache. | |
| 8 | + * | |
| 9 | + * Caching *per file* rather than per day is deliberate. It is timezone | |
| 10 | + * independent, so changing the reporting zone does not invalidate anything, and | |
| 11 | + * it keeps cross-file de-duplication exact: cached entries are de-duplicated | |
| 12 | + * within their own file only, and the aggregator still applies the global | |
| 13 | + * dedupe pass over the small surviving key set. | |
| 14 | + * | |
| 15 | + * @module usageScanCache | |
| 16 | + */ | |
| 17 | +import type { UsageProviderKind } from "@t3tools/contracts"; | |
| 18 | + | |
| 19 | +import type { UsageRecord } from "./usageTranscripts.ts"; | |
| 20 | + | |
| 21 | +export const USAGE_SCAN_CACHE_VERSION = 1 as const; | |
| 22 | + | |
| 23 | +export interface CachedFile { | |
| 24 | + readonly size: number; | |
| 25 | + readonly mtimeMs: number; | |
| 26 | + readonly provider: UsageProviderKind; | |
| 27 | + readonly records: readonly UsageRecord[]; | |
| 28 | +} | |
| 29 | + | |
| 30 | +export type ScanCache = Map<string, CachedFile>; | |
| 31 | + | |
| 32 | +/** | |
| 33 | + * Row layout for the serialised form. Positional and interned rather than | |
| 34 | + * object-per-record: on a 30-day window that is the difference between a file | |
| 35 | + * measured in tens of megabytes and one under six. | |
| 36 | + */ | |
| 37 | +type SerializedRecord = readonly [ | |
| 38 | + timestampMs: number, | |
| 39 | + modelIndex: number, | |
| 40 | + sessionIndex: number, | |
| 41 | + uncachedInputTokens: number, | |
| 42 | + cachedInputTokens: number, | |
| 43 | + cacheCreationTokens: number, | |
| 44 | + outputTokens: number, | |
| 45 | + reasoningTokens: number, | |
| 46 | + dedupeKey: string | null, | |
| 47 | + reportedCostUsd: number | null, | |
| 48 | +]; | |
| 49 | + | |
| 50 | +interface SerializedFile { | |
| 51 | + readonly s: number; | |
| 52 | + readonly m: number; | |
| 53 | + readonly p: UsageProviderKind; | |
| 54 | + readonly r: readonly SerializedRecord[]; | |
| 55 | +} | |
| 56 | + | |
| 57 | +interface SerializedCache { | |
| 58 | + readonly version: number; | |
| 59 | + readonly models: readonly string[]; | |
| 60 | + readonly sessions: readonly string[]; | |
| 61 | + readonly files: Readonly<Record<string, SerializedFile>>; | |
| 62 | +} | |
| 63 | + | |
| 64 | +/** Serialises the cache, interning the repeated model and session strings. */ | |
| 65 | +export function encodeScanCache(cache: ScanCache): SerializedCache { | |
| 66 | + const models: string[] = []; | |
| 67 | + const sessions: string[] = []; | |
| 68 | + const modelIndex = new Map<string, number>(); | |
| 69 | + const sessionIndex = new Map<string, number>(); | |
| 70 | + | |
| 71 | + const intern = (table: string[], index: Map<string, number>, value: string): number => { | |
| 72 | + const existing = index.get(value); | |
| 73 | + if (existing !== undefined) return existing; | |
| 74 | + const next = table.length; | |
| 75 | + table.push(value); | |
| 76 | + index.set(value, next); | |
| 77 | + return next; | |
| 78 | + }; | |
| 79 | + | |
| 80 | + const files: Record<string, SerializedFile> = {}; | |
| 81 | + for (const [path, entry] of cache) { | |
| 82 | + files[path] = { | |
| 83 | + s: entry.size, | |
| 84 | + m: entry.mtimeMs, | |
| 85 | + p: entry.provider, | |
| 86 | + r: entry.records.map((record) => [ | |
| 87 | + record.timestampMs, | |
| 88 | + intern(models, modelIndex, record.model), | |
| 89 | + intern(sessions, sessionIndex, record.sessionId), | |
| 90 | + record.totals.uncachedInputTokens, | |
| 91 | + record.totals.cachedInputTokens, | |
| 92 | + record.totals.cacheCreationTokens, | |
| 93 | + record.totals.outputTokens, | |
| 94 | + record.totals.reasoningTokens, | |
| 95 | + record.dedupeKey, | |
| 96 | + record.reportedCostUsd, | |
| 97 | + ]), | |
| 98 | + }; | |
| 99 | + } | |
| 100 | + | |
| 101 | + return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files }; | |
| 102 | +} | |
| 103 | + | |
| 104 | +function isRecordArray(value: unknown): value is readonly unknown[] { | |
| 105 | + return Array.isArray(value); | |
| 106 | +} | |
| 107 | + | |
| 108 | +/** | |
| 109 | + * Rebuilds the cache from a parsed document. | |
| 110 | + * | |
| 111 | + * Anything malformed yields an empty cache rather than an error: a corrupt | |
| 112 | + * cache should cost one cold scan, never a broken page. | |
| 113 | + */ | |
| 114 | +export function decodeScanCache(document: unknown): ScanCache { | |
| 115 | + const cache: ScanCache = new Map(); | |
| 116 | + if (typeof document !== "object" || document === null) return cache; | |
| 117 | + | |
| 118 | + const root = document as Partial<SerializedCache>; | |
| 119 | + if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache; | |
| 120 | + if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache; | |
| 121 | + if (typeof root.files !== "object" || root.files === null) return cache; | |
| 122 | + | |
| 123 | + // The intern tables must be all strings: a numeric entry would pass the | |
| 124 | + // undefined guard below, land in a record's model, and crash the aggregate | |
| 125 | + // at normalizeModelName. A corrupt table rejects the whole cache. | |
| 126 | + if (!root.models.every((value) => typeof value === "string")) return cache; | |
| 127 | + if (!root.sessions.every((value) => typeof value === "string")) return cache; | |
| 128 | + const models = root.models as readonly string[]; | |
| 129 | + const sessions = root.sessions as readonly string[]; | |
| 130 | + | |
| 131 | + for (const [path, raw] of Object.entries(root.files)) { | |
| 132 | + if (typeof raw !== "object" || raw === null) continue; | |
| 133 | + const entry = raw as Partial<SerializedFile>; | |
| 134 | + if (typeof entry.s !== "number" || typeof entry.m !== "number") continue; | |
| 135 | + if (entry.p !== "claude" && entry.p !== "codex") continue; | |
| 136 | + if (!isRecordArray(entry.r)) continue; | |
| 137 | + | |
| 138 | + const provider: UsageProviderKind = entry.p; | |
| 139 | + const records: UsageRecord[] = []; | |
| 140 | + // Any corrupt row disqualifies the whole entry. Keeping the survivors | |
| 141 | + // under the original (size, mtime) would read as a valid warm hit and the | |
| 142 | + // file would never be re-parsed, silently losing the dropped rows' usage. | |
| 143 | + let corrupt = false; | |
| 144 | + for (const row of entry.r) { | |
| 145 | + if (!isRecordArray(row) || row.length < 10) { | |
| 146 | + corrupt = true; | |
| 147 | + break; | |
| 148 | + } | |
| 149 | + const [ | |
| 150 | + timestampMs, | |
| 151 | + modelIndex, | |
| 152 | + sessionIndex, | |
| 153 | + uncached, | |
| 154 | + cached, | |
| 155 | + cacheCreation, | |
| 156 | + output, | |
| 157 | + reasoning, | |
| 158 | + dedupeKey, | |
| 159 | + reportedCostUsd, | |
| 160 | + ] = row as SerializedRecord; | |
| 161 | + | |
| 162 | + const model = typeof modelIndex === "number" ? models[modelIndex] : undefined; | |
| 163 | + if ( | |
| 164 | + typeof timestampMs !== "number" || | |
| 165 | + !Number.isFinite(timestampMs) || | |
| 166 | + model === undefined || | |
| 167 | + !Number.isFinite(uncached) || | |
| 168 | + !Number.isFinite(cached) || | |
| 169 | + !Number.isFinite(cacheCreation) || | |
| 170 | + !Number.isFinite(output) || | |
| 171 | + !Number.isFinite(reasoning) | |
| 172 | + ) { | |
| 173 | + corrupt = true; | |
| 174 | + break; | |
| 175 | + } | |
| 176 | + | |
| 177 | + records.push({ | |
| 178 | + provider, | |
| 179 | + timestampMs, | |
| 180 | + model, | |
| 181 | + sessionId: (typeof sessionIndex === "number" ? sessions[sessionIndex] : undefined) ?? "", | |
| 182 | + totals: { | |
| 183 | + uncachedInputTokens: uncached, | |
| 184 | + cachedInputTokens: cached, | |
| 185 | + cacheCreationTokens: cacheCreation, | |
| 186 | + outputTokens: output, | |
| 187 | + reasoningTokens: reasoning, | |
| 188 | + }, | |
| 189 | + reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null, | |
| 190 | + dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null, | |
| 191 | + }); | |
| 192 | + } | |
| 193 | + | |
| 194 | + if (corrupt) continue; | |
| 195 | + cache.set(path, { size: entry.s, mtimeMs: entry.m, provider, records }); | |
| 196 | + } | |
| 197 | + | |
| 198 | + return cache; | |
| 199 | +} | |
| 200 | + | |
| 201 | +export interface PruneOptions { | |
| 202 | + /** Files the walk just saw. Only meaningful inside the walked window. */ | |
| 203 | + readonly livePaths: ReadonlySet<string>; | |
| 204 | + /** | |
| 205 | + * Roots the walk actually completed. Absence from `livePaths` only proves a | |
| 206 | + * file is gone when its root was walked: a provider whose directory failed to | |
| 207 | + * resolve this pass must not have its warm entries purged. | |
| 208 | + */ | |
| 209 | + readonly walkedRoots: readonly string[]; | |
| 210 | + /** Start of the walked window; entries older than this were not looked for. */ | |
| 211 | + readonly windowStartMs: number; | |
| 212 | + /** Entries older than this are dropped regardless. */ | |
| 213 | + readonly retentionCutoffMs: number; | |
| 214 | +} | |
| 215 | + | |
| 216 | +/** | |
| 217 | + * Drops aged-out entries, and entries for files that have disappeared. | |
| 218 | + * | |
| 219 | + * The walk only covers the requested window, so absence from `livePaths` only | |
| 220 | + * proves deletion for entries *inside* that window. Pruning everything the walk | |
| 221 | + * missed would evict the 30-day entries every time someone looked at 7 days. | |
| 222 | + * | |
| 223 | + * Replaces an earlier record cap that cleared the whole cache once exceeded, | |
| 224 | + * which meant a large enough window never warmed up at all. | |
| 225 | + */ | |
| 226 | +export function pruneScanCache(cache: ScanCache, options: PruneOptions): number { | |
| 227 | + let removed = 0; | |
| 228 | + for (const [path, entry] of cache) { | |
| 229 | + const agedOut = entry.mtimeMs < options.retentionCutoffMs; | |
| 230 | + const underWalkedRoot = options.walkedRoots.some((root) => path.startsWith(root)); | |
| 231 | + const deleted = | |
| 232 | + underWalkedRoot && entry.mtimeMs >= options.windowStartMs && !options.livePaths.has(path); | |
| 233 | + if (agedOut || deleted) { | |
| 234 | + cache.delete(path); | |
| 235 | + removed += 1; | |
| 236 | + } | |
| 237 | + } | |
| 238 | + return removed; | |
| 239 | +} | |
| 240 | + | |
| 241 | +/** Within-file de-duplication, applied before an entry is cached. */ | |
| 242 | +export function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] { | |
| 243 | + const seen = new Set<string>(); | |
| 244 | + const kept: UsageRecord[] = []; | |
| 245 | + for (const record of records) { | |
| 246 | + if (record.dedupeKey !== null) { | |
| 247 | + if (seen.has(record.dedupeKey)) continue; | |
| 248 | + seen.add(record.dedupeKey); | |
| 249 | + } | |
| 250 | + kept.push(record); | |
| 251 | + } | |
| 252 | + return kept; | |
| 253 | +} | |
| @@ -0,0 +1,141 @@ | ||
| 1 | +// @effect-diagnostics nodeBuiltinImport:off | |
| 2 | +/** | |
| 3 | + * Raw filesystem access for transcript scanning. | |
| 4 | + * | |
| 5 | + * Isolated here so the rest of the usage code stays on Effect's `FileSystem`. | |
| 6 | + * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB | |
| 7 | + * across ~1,500 files, and `readline` over a read stream is roughly an order of | |
| 8 | + * magnitude cheaper than materialising each file. The equivalent Effect stream | |
| 9 | + * pipeline is idiomatic but not fast enough to sit behind a page load. | |
| 10 | + * | |
| 11 | + * @module usageTranscriptReader | |
| 12 | + */ | |
| 13 | +import * as NodeFS from "node:fs"; | |
| 14 | +import * as NodeFSP from "node:fs/promises"; | |
| 15 | +import * as NodePath from "node:path"; | |
| 16 | +import * as NodeReadline from "node:readline"; | |
| 17 | + | |
| 18 | +import type { UsageProviderKind } from "@t3tools/contracts"; | |
| 19 | + | |
| 20 | +import { | |
| 21 | + initialCodexScanState, | |
| 22 | + mightCarryUsage, | |
| 23 | + parseClaudeLine, | |
| 24 | + parseCodexLine, | |
| 25 | + type UsageRecord, | |
| 26 | +} from "./usageTranscripts.ts"; | |
| 27 | + | |
| 28 | +export interface TranscriptFile { | |
| 29 | + readonly path: string; | |
| 30 | + readonly size: number; | |
| 31 | + readonly mtimeMs: number; | |
| 32 | +} | |
| 33 | + | |
| 34 | +/** | |
| 35 | + * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`. | |
| 36 | + * | |
| 37 | + * Errors on individual entries are swallowed: session files rotate and get | |
| 38 | + * removed while the walk is in flight, and a partial listing is far better than | |
| 39 | + * failing the page. | |
| 40 | + */ | |
| 41 | +export async function listTranscriptFiles( | |
| 42 | + root: string, | |
| 43 | + sinceMs: number, | |
| 44 | +): Promise<readonly TranscriptFile[]> { | |
| 45 | + const found: TranscriptFile[] = []; | |
| 46 | + | |
| 47 | + const walk = async (dir: string): Promise<void> => { | |
| 48 | + let entries; | |
| 49 | + try { | |
| 50 | + entries = await NodeFSP.readdir(dir, { withFileTypes: true }); | |
| 51 | + } catch { | |
| 52 | + return; | |
| 53 | + } | |
| 54 | + for (const entry of entries) { | |
| 55 | + const child = NodePath.join(dir, entry.name); | |
| 56 | + if (entry.isDirectory()) { | |
| 57 | + await walk(child); | |
| 58 | + continue; | |
| 59 | + } | |
| 60 | + if (!entry.name.endsWith(".jsonl")) continue; | |
| 61 | + try { | |
| 62 | + const stats = await NodeFSP.stat(child); | |
| 63 | + if (stats.mtimeMs >= sinceMs) { | |
| 64 | + found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs }); | |
| 65 | + } | |
| 66 | + } catch { | |
| 67 | + // Vanished between readdir and stat. | |
| 68 | + } | |
| 69 | + } | |
| 70 | + }; | |
| 71 | + | |
| 72 | + await walk(root); | |
| 73 | + return found; | |
| 74 | +} | |
| 75 | + | |
| 76 | +/** | |
| 77 | + * Filesystem identity of a directory, as `device:inode`. | |
| 78 | + * | |
| 79 | + * Used to tell "two servers reading the same transcript directory" apart from | |
| 80 | + * "two machines whose hostname and home path happen to match". Returns an empty | |
| 81 | + * string when the directory cannot be stat'd. | |
| 82 | + */ | |
| 83 | +export async function readDirectoryVolumeId(path: string): Promise<string> { | |
| 84 | + try { | |
| 85 | + const stats = await NodeFSP.stat(path); | |
| 86 | + return `${stats.dev}:${stats.ino}`; | |
| 87 | + } catch { | |
| 88 | + return ""; | |
| 89 | + } | |
| 90 | +} | |
| 91 | + | |
| 92 | +/** | |
| 93 | + * Streams one transcript and returns the usage records it contains, or `null` | |
| 94 | + * when the file could not be read. | |
| 95 | + * | |
| 96 | + * The distinction matters to the caller's cache: a genuinely empty transcript | |
| 97 | + * is a stable fact worth memoising, while a transient read failure memoised | |
| 98 | + * under the same `(size, mtime)` key would silently drop that file's usage | |
| 99 | + * until the file next changes. | |
| 100 | + * | |
| 101 | + * Codex carries the active model on `turn_context` lines that hold no usage of | |
| 102 | + * their own, so those still have to pass through the reducer to keep model | |
| 103 | + * attribution correct. | |
| 104 | + */ | |
| 105 | +export async function readTranscriptRecords( | |
| 106 | + filePath: string, | |
| 107 | + provider: UsageProviderKind, | |
| 108 | +): Promise<readonly UsageRecord[] | null> { | |
| 109 | + const records: UsageRecord[] = []; | |
| 110 | + const codexState = initialCodexScanState(); | |
| 111 | + | |
| 112 | + try { | |
| 113 | + const lines = NodeReadline.createInterface({ | |
| 114 | + input: NodeFS.createReadStream(filePath, { encoding: "utf8" }), | |
| 115 | + crlfDelay: Infinity, | |
| 116 | + }); | |
| 117 | + | |
| 118 | + for await (const line of lines) { | |
| 119 | + if (provider === "codex") { | |
| 120 | + if ( | |
| 121 | + !mightCarryUsage(line, provider) && | |
| 122 | + !line.includes('"turn_context"') && | |
| 123 | + !line.includes('"session_meta"') | |
| 124 | + ) { | |
| 125 | + continue; | |
| 126 | + } | |
| 127 | + const record = parseCodexLine(line, codexState); | |
| 128 | + if (record !== null) records.push(record); | |
| 129 | + continue; | |
| 130 | + } | |
| 131 | + | |
| 132 | + if (!mightCarryUsage(line, provider)) continue; | |
| 133 | + const record = parseClaudeLine(line); | |
| 134 | + if (record !== null) records.push(record); | |
| 135 | + } | |
| 136 | + } catch { | |
| 137 | + return null; | |
| 138 | + } | |
| 139 | + | |
| 140 | + return records; | |
| 141 | +} | |
| @@ -0,0 +1,151 @@ | ||
| 1 | +import { describe, expect, it } from "@effect/vitest"; | |
| 2 | + | |
| 3 | +import { | |
| 4 | + initialCodexScanState, | |
| 5 | + parseClaudeLine, | |
| 6 | + parseCodexLine, | |
| 7 | + totalTokens, | |
| 8 | +} from "./usageTranscripts.ts"; | |
| 9 | + | |
| 10 | +/** Shaped after a real Claude Code assistant record. */ | |
| 11 | +function claudeLine(overrides: { | |
| 12 | + messageId: string; | |
| 13 | + contentType: string; | |
| 14 | + model?: string; | |
| 15 | + outputTokens?: number; | |
| 16 | +}): string { | |
| 17 | + return JSON.stringify({ | |
| 18 | + type: "assistant", | |
| 19 | + timestamp: "2026-08-07T04:05:13.944Z", | |
| 20 | + sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0", | |
| 21 | + cwd: "/home/theo/project", | |
| 22 | + message: { | |
| 23 | + id: overrides.messageId, | |
| 24 | + role: "assistant", | |
| 25 | + model: overrides.model ?? "claude-fable-5", | |
| 26 | + content: [{ type: overrides.contentType }], | |
| 27 | + usage: { | |
| 28 | + input_tokens: 2, | |
| 29 | + cache_creation_input_tokens: 66818, | |
| 30 | + cache_read_input_tokens: 1000, | |
| 31 | + output_tokens: overrides.outputTokens ?? 286, | |
| 32 | + }, | |
| 33 | + }, | |
| 34 | + }); | |
| 35 | +} | |
| 36 | + | |
| 37 | +describe("parseClaudeLine", () => { | |
| 38 | + it("extracts token totals and a dedupe key", () => { | |
| 39 | + const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" })); | |
| 40 | + | |
| 41 | + expect(record).not.toBeNull(); | |
| 42 | + expect(record?.provider).toBe("claude"); | |
| 43 | + expect(record?.model).toBe("claude-fable-5"); | |
| 44 | + expect(record?.totals).toEqual({ | |
| 45 | + uncachedInputTokens: 2, | |
| 46 | + cachedInputTokens: 1000, | |
| 47 | + cacheCreationTokens: 66818, | |
| 48 | + outputTokens: 286, | |
| 49 | + reasoningTokens: 0, | |
| 50 | + }); | |
| 51 | + expect(record?.dedupeKey).toBe("msg_1:"); | |
| 52 | + }); | |
| 53 | + | |
| 54 | + it("gives every content block of one message the same dedupe key", () => { | |
| 55 | + // T3 Code writes one record per content block, each repeating the parent | |
| 56 | + // message's full usage. Summing them would overcount ~2.4x on real data. | |
| 57 | + const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" })); | |
| 58 | + const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" })); | |
| 59 | + | |
| 60 | + expect(text?.dedupeKey).toBe(toolUse?.dedupeKey); | |
| 61 | + expect(text?.totals).toEqual(toolUse?.totals); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("ignores records that are not assistant messages", () => { | |
| 65 | + expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull(); | |
| 66 | + expect(parseClaudeLine("not json")).toBeNull(); | |
| 67 | + }); | |
| 68 | +}); | |
| 69 | + | |
| 70 | +describe("parseCodexLine", () => { | |
| 71 | + const sessionMeta = JSON.stringify({ | |
| 72 | + type: "session_meta", | |
| 73 | + timestamp: "2026-08-01T05:17:41.289Z", | |
| 74 | + payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" }, | |
| 75 | + }); | |
| 76 | + const turnContext = JSON.stringify({ | |
| 77 | + type: "turn_context", | |
| 78 | + timestamp: "2026-08-01T05:17:42.694Z", | |
| 79 | + payload: { type: "turn_context", model: "gpt-5.6-sol" }, | |
| 80 | + }); | |
| 81 | + const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) => | |
| 82 | + JSON.stringify({ | |
| 83 | + type: "event_msg", | |
| 84 | + timestamp: "2026-08-01T05:17:49.919Z", | |
| 85 | + payload: { | |
| 86 | + type: "token_count", | |
| 87 | + info: { | |
| 88 | + last_token_usage: { | |
| 89 | + input_tokens: inputTokens, | |
| 90 | + cached_input_tokens: cached, | |
| 91 | + cache_write_input_tokens: 0, | |
| 92 | + output_tokens: output, | |
| 93 | + reasoning_output_tokens: reasoning, | |
| 94 | + }, | |
| 95 | + }, | |
| 96 | + }, | |
| 97 | + }); | |
| 98 | + | |
| 99 | + it("attributes usage to the model from the preceding turn context", () => { | |
| 100 | + const state = initialCodexScanState(); | |
| 101 | + parseCodexLine(sessionMeta, state); | |
| 102 | + parseCodexLine(turnContext, state); | |
| 103 | + const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state); | |
| 104 | + | |
| 105 | + expect(record?.provider).toBe("codex"); | |
| 106 | + expect(record?.model).toBe("gpt-5.6-sol"); | |
| 107 | + expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f"); | |
| 108 | + // Codex reports input_tokens inclusive of the cached portion. | |
| 109 | + expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008); | |
| 110 | + expect(record?.totals.cachedInputTokens).toBe(11008); | |
| 111 | + expect(record?.totals.reasoningTokens).toBe(116); | |
| 112 | + }); | |
| 113 | + | |
| 114 | + it("skips a repeated token_count so deltas are not double counted", () => { | |
| 115 | + const state = initialCodexScanState(); | |
| 116 | + parseCodexLine(turnContext, state); | |
| 117 | + const first = parseCodexLine(tokenCount(100, 0, 10, 0), state); | |
| 118 | + const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state); | |
| 119 | + | |
| 120 | + expect(first).not.toBeNull(); | |
| 121 | + expect(repeat).toBeNull(); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + it("drops usage that arrives before any model is known", () => { | |
| 125 | + const state = initialCodexScanState(); | |
| 126 | + expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull(); | |
| 127 | + }); | |
| 128 | + | |
| 129 | + it("does not let a pre-model event poison the duplicate signature", () => { | |
| 130 | + // A token_count before its turn_context is dropped; the identical event | |
| 131 | + // re-emitted once the model is known must still be counted. | |
| 132 | + const state = initialCodexScanState(); | |
| 133 | + expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull(); | |
| 134 | + parseCodexLine(turnContext, state); | |
| 135 | + expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull(); | |
| 136 | + }); | |
| 137 | +}); | |
| 138 | + | |
| 139 | +describe("totalTokens", () => { | |
| 140 | + it("does not add reasoning on top of output", () => { | |
| 141 | + expect( | |
| 142 | + totalTokens({ | |
| 143 | + uncachedInputTokens: 10, | |
| 144 | + cachedInputTokens: 20, | |
| 145 | + cacheCreationTokens: 30, | |
| 146 | + outputTokens: 40, | |
| 147 | + reasoningTokens: 25, | |
| 148 | + }), | |
| 149 | + ).toBe(100); | |
| 150 | + }); | |
| 151 | +}); | |
| @@ -0,0 +1,246 @@ | ||
| 1 | +/** | |
| 2 | + * Pure parsers for the provider CLIs' on-disk session transcripts. | |
| 3 | + * | |
| 4 | + * Both parsers are line-at-a-time reducers so callers can stream large files | |
| 5 | + * without materialising them. Neither touches the filesystem. | |
| 6 | + * | |
| 7 | + * @module usageTranscripts | |
| 8 | + */ | |
| 9 | +import type { UsageProviderKind, UsageTokenTotals } from "@t3tools/contracts"; | |
| 10 | + | |
| 11 | +export interface UsageRecord { | |
| 12 | + readonly provider: UsageProviderKind; | |
| 13 | + readonly timestampMs: number; | |
| 14 | + readonly model: string; | |
| 15 | + readonly sessionId: string; | |
| 16 | + readonly totals: UsageTokenTotals; | |
| 17 | + readonly reportedCostUsd: number | null; | |
| 18 | + /** | |
| 19 | + * Key for cross-file de-duplication, or `null` when the record is inherently | |
| 20 | + * unique and needs no dedup. | |
| 21 | + */ | |
| 22 | + readonly dedupeKey: string | null; | |
| 23 | +} | |
| 24 | + | |
| 25 | +const EMPTY_TOTALS: UsageTokenTotals = { | |
| 26 | + uncachedInputTokens: 0, | |
| 27 | + cachedInputTokens: 0, | |
| 28 | + cacheCreationTokens: 0, | |
| 29 | + outputTokens: 0, | |
| 30 | + reasoningTokens: 0, | |
| 31 | +}; | |
| 32 | + | |
| 33 | +function int(value: unknown): number { | |
| 34 | + return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0; | |
| 35 | +} | |
| 36 | + | |
| 37 | +function parseTimestampMs(value: unknown): number | null { | |
| 38 | + if (typeof value !== "string") return null; | |
| 39 | + const parsed = Date.parse(value); | |
| 40 | + return Number.isNaN(parsed) ? null : parsed; | |
| 41 | +} | |
| 42 | + | |
| 43 | +export function addTotals(a: UsageTokenTotals, b: UsageTokenTotals): UsageTokenTotals { | |
| 44 | + return { | |
| 45 | + uncachedInputTokens: a.uncachedInputTokens + b.uncachedInputTokens, | |
| 46 | + cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens, | |
| 47 | + cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens, | |
| 48 | + outputTokens: a.outputTokens + b.outputTokens, | |
| 49 | + reasoningTokens: a.reasoningTokens + b.reasoningTokens, | |
| 50 | + }; | |
| 51 | +} | |
| 52 | + | |
| 53 | +export function totalTokens(totals: UsageTokenTotals): number { | |
| 54 | + // reasoningTokens is a subset of outputTokens and must not be added again. | |
| 55 | + return ( | |
| 56 | + totals.uncachedInputTokens + | |
| 57 | + totals.cachedInputTokens + | |
| 58 | + totals.cacheCreationTokens + | |
| 59 | + totals.outputTokens | |
| 60 | + ); | |
| 61 | +} | |
| 62 | + | |
| 63 | +/** | |
| 64 | + * Cheap substring gate applied before `JSON.parse`. | |
| 65 | + * | |
| 66 | + * Transcripts are mostly tool output; only a minority of lines carry usage. On | |
| 67 | + * a 30-day window this skips roughly half the lines outright and is worth about | |
| 68 | + * an order of magnitude. | |
| 69 | + */ | |
| 70 | +export function mightCarryUsage(line: string, provider: UsageProviderKind): boolean { | |
| 71 | + return provider === "claude" ? line.includes('"usage"') : line.includes('"token_count"'); | |
| 72 | +} | |
| 73 | + | |
| 74 | +/* -------------------------------------------------------------------------- */ | |
| 75 | +/* Claude Code */ | |
| 76 | +/* -------------------------------------------------------------------------- */ | |
| 77 | + | |
| 78 | +/** | |
| 79 | + * Parses one line of a Claude Code transcript. | |
| 80 | + * | |
| 81 | + * T3 Code writes one record per assistant *content block*, and every one of | |
| 82 | + * those records repeats the same complete `usage` object for the parent | |
| 83 | + * message. Summing them overcounts by roughly 2.4x on a real workload, so the | |
| 84 | + * caller must drop repeats by `dedupeKey` and keep the first. | |
| 85 | + */ | |
| 86 | +export function parseClaudeLine(line: string): UsageRecord | null { | |
| 87 | + let parsed: unknown; | |
| 88 | + try { | |
| 89 | + parsed = JSON.parse(line); | |
| 90 | + } catch { | |
| 91 | + return null; | |
| 92 | + } | |
| 93 | + if (typeof parsed !== "object" || parsed === null) return null; | |
| 94 | + | |
| 95 | + const record = parsed as Record<string, unknown>; | |
| 96 | + if (record["type"] !== "assistant") return null; | |
| 97 | + | |
| 98 | + const message = record["message"]; | |
| 99 | + if (typeof message !== "object" || message === null) return null; | |
| 100 | + const messageRecord = message as Record<string, unknown>; | |
| 101 | + | |
| 102 | + const usage = messageRecord["usage"]; | |
| 103 | + if (typeof usage !== "object" || usage === null) return null; | |
| 104 | + const usageRecord = usage as Record<string, unknown>; | |
| 105 | + | |
| 106 | + const timestampMs = parseTimestampMs(record["timestamp"]); | |
| 107 | + if (timestampMs === null) return null; | |
| 108 | + | |
| 109 | + const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : ""; | |
| 110 | + if (model.length === 0) return null; | |
| 111 | + | |
| 112 | + const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null; | |
| 113 | + const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null; | |
| 114 | + // Matches ccusage: prefer the message/request pair, fall back to whichever | |
| 115 | + // half exists. Records with neither cannot be de-duplicated. | |
| 116 | + const dedupeKey = | |
| 117 | + messageId === null && requestId === null ? null : `${messageId ?? ""}:${requestId ?? ""}`; | |
| 118 | + | |
| 119 | + const cost = record["costUSD"]; | |
| 120 | + | |
| 121 | + return { | |
| 122 | + provider: "claude", | |
| 123 | + timestampMs, | |
| 124 | + model, | |
| 125 | + sessionId: typeof record["sessionId"] === "string" ? record["sessionId"] : "", | |
| 126 | + totals: { | |
| 127 | + uncachedInputTokens: int(usageRecord["input_tokens"]), | |
| 128 | + cachedInputTokens: int(usageRecord["cache_read_input_tokens"]), | |
| 129 | + cacheCreationTokens: int(usageRecord["cache_creation_input_tokens"]), | |
| 130 | + outputTokens: int(usageRecord["output_tokens"]), | |
| 131 | + // Anthropic folds thinking tokens into output and does not break them out. | |
| 132 | + reasoningTokens: 0, | |
| 133 | + }, | |
| 134 | + reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null, | |
| 135 | + dedupeKey, | |
| 136 | + }; | |
| 137 | +} | |
| 138 | + | |
| 139 | +/* -------------------------------------------------------------------------- */ | |
| 140 | +/* Codex */ | |
| 141 | +/* -------------------------------------------------------------------------- */ | |
| 142 | + | |
| 143 | +/** | |
| 144 | + * Rolling state for a single Codex rollout file. | |
| 145 | + * | |
| 146 | + * Codex `token_count` events carry no model, so the model is carried forward | |
| 147 | + * from the most recent `turn_context`. Sessions that switch models mid-run | |
| 148 | + * attribute correctly from the switch onward. | |
| 149 | + */ | |
| 150 | +export interface CodexScanState { | |
| 151 | + model: string; | |
| 152 | + sessionId: string; | |
| 153 | + lastUsageSignature: string | null; | |
| 154 | +} | |
| 155 | + | |
| 156 | +export function initialCodexScanState(): CodexScanState { | |
| 157 | + return { model: "", sessionId: "", lastUsageSignature: null }; | |
| 158 | +} | |
| 159 | + | |
| 160 | +/** | |
| 161 | + * Feeds one line of a Codex rollout into `state`, returning a record when the | |
| 162 | + * line was a usage event. | |
| 163 | + * | |
| 164 | + * Deltas come from `last_token_usage`. Summing those across a session | |
| 165 | + * reconciles with the session's final `total_token_usage`, provided | |
| 166 | + * consecutive duplicate events are dropped, which this does. | |
| 167 | + */ | |
| 168 | +export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null { | |
| 169 | + let parsed: unknown; | |
| 170 | + try { | |
| 171 | + parsed = JSON.parse(line); | |
| 172 | + } catch { | |
| 173 | + return null; | |
| 174 | + } | |
| 175 | + if (typeof parsed !== "object" || parsed === null) return null; | |
| 176 | + | |
| 177 | + const record = parsed as Record<string, unknown>; | |
| 178 | + const payload = record["payload"]; | |
| 179 | + if (typeof payload !== "object" || payload === null) return null; | |
| 180 | + const payloadRecord = payload as Record<string, unknown>; | |
| 181 | + const payloadType = payloadRecord["type"]; | |
| 182 | + | |
| 183 | + if (record["type"] === "session_meta") { | |
| 184 | + const id = payloadRecord["id"] ?? payloadRecord["session_id"]; | |
| 185 | + if (typeof id === "string") state.sessionId = id; | |
| 186 | + return null; | |
| 187 | + } | |
| 188 | + | |
| 189 | + if (record["type"] === "turn_context") { | |
| 190 | + if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"]; | |
| 191 | + return null; | |
| 192 | + } | |
| 193 | + | |
| 194 | + if (payloadType !== "token_count") return null; | |
| 195 | + | |
| 196 | + const info = payloadRecord["info"]; | |
| 197 | + if (typeof info !== "object" || info === null) return null; | |
| 198 | + const last = (info as Record<string, unknown>)["last_token_usage"]; | |
| 199 | + if (typeof last !== "object" || last === null) return null; | |
| 200 | + const lastRecord = last as Record<string, unknown>; | |
| 201 | + | |
| 202 | + // Only an event that is otherwise eligible may consume the duplicate | |
| 203 | + // signature. A token_count arriving before its turn_context (no model yet) | |
| 204 | + // must not poison it, or the re-emitted copy after the model is known would | |
| 205 | + // be skipped as a duplicate and those tokens never counted. | |
| 206 | + const timestampMs = parseTimestampMs(record["timestamp"]); | |
| 207 | + if (timestampMs === null) return null; | |
| 208 | + if (state.model.length === 0) return null; | |
| 209 | + | |
| 210 | + // Codex re-emits an unchanged token_count on some stream boundaries. Summing | |
| 211 | + // those would double count, so identical consecutive payloads are skipped. | |
| 212 | + const signature = JSON.stringify(lastRecord); | |
| 213 | + if (signature === state.lastUsageSignature) return null; | |
| 214 | + state.lastUsageSignature = signature; | |
| 215 | + | |
| 216 | + const inputTokens = int(lastRecord["input_tokens"]); | |
| 217 | + const cachedInputTokens = int(lastRecord["cached_input_tokens"]); | |
| 218 | + const cacheCreationTokens = int(lastRecord["cache_write_input_tokens"]); | |
| 219 | + const outputTokens = int(lastRecord["output_tokens"]); | |
| 220 | + | |
| 221 | + const totals: UsageTokenTotals = { | |
| 222 | + // Codex reports `input_tokens` inclusive of the cached portion. | |
| 223 | + uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens), | |
| 224 | + cachedInputTokens, | |
| 225 | + cacheCreationTokens, | |
| 226 | + outputTokens, | |
| 227 | + // Reported inside output_tokens, surfaced separately for the token mix. | |
| 228 | + reasoningTokens: Math.min(outputTokens, int(lastRecord["reasoning_output_tokens"])), | |
| 229 | + }; | |
| 230 | + | |
| 231 | + if (totalTokens(totals) === 0) return null; | |
| 232 | + | |
| 233 | + return { | |
| 234 | + provider: "codex", | |
| 235 | + timestampMs, | |
| 236 | + model: state.model, | |
| 237 | + sessionId: state.sessionId, | |
| 238 | + totals, | |
| 239 | + // Codex does not report cost in the rollout. | |
| 240 | + reportedCostUsd: null, | |
| 241 | + // Rollout files are unique per session, so events need no global dedup. | |
| 242 | + dedupeKey: null, | |
| 243 | + }; | |
| 244 | +} | |
| 245 | + | |
| 246 | +export { EMPTY_TOTALS }; | |
| @@ -105,6 +105,7 @@ import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts"; · 104 unmodified lines | ||
| 105 | 105 | import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; |
| 106 | 106 | import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; |
| 107 | 107 | import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; |
| 108 | +import * as UsageService from "./usage/UsageService.ts"; | |
| 108 | 109 | import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; |
| 109 | 110 | import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts"; |
| 110 | 111 | import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; |
| @@ -412,6 +413,7 @@ const makeWsRpcLayer = ( · 301 unmodified lines | ||
| 412 | 413 | const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; |
| 413 | 414 | const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; |
| 414 | 415 | const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry; |
| 416 | + const usage = yield* UsageService.UsageService; | |
| 415 | 417 | const relayClient = yield* RelayClient.RelayClient; |
| 416 | 418 | const authorizationError = (requiredScope: AuthEnvironmentScope) => |
| 417 | 419 | new EnvironmentAuthorizationError({ |
| @@ -1529,6 +1531,10 @@ const makeWsRpcLayer = ( · 1111 unmodified lines | ||
| 1529 | 1531 | "rpc.aggregate": "server", |
| 1530 | 1532 | }, |
| 1531 | 1533 | ), |
| 1534 | + [WS_METHODS.serverGetUsageSummary]: (input) => | |
| 1535 | + observeRpcEffect(WS_METHODS.serverGetUsageSummary, usage.readSummary(input), { | |
| 1536 | + "rpc.aggregate": "server", | |
| 1537 | + }), | |
| 1532 | 1538 | [WS_METHODS.serverRetryResourceTelemetry]: (_input) => |
| 1533 | 1539 | observeRpcEffect(WS_METHODS.serverRetryResourceTelemetry, resourceTelemetry.retry, { |
| 1534 | 1540 | "rpc.aggregate": "server", |
| @@ -11,6 +11,7 @@ import { · 10 unmodified lines | ||
| 11 | 11 | cssFontFamilies, |
| 12 | 12 | resolveDefaultFamilyLabel, |
| 13 | 13 | resolveTerminalFontPreference, |
| 14 | + resolveTerminalFontSizePreference, | |
| 14 | 15 | } from "./appearanceFonts"; |
| 15 | 16 | |
| 16 | 17 | describe("areFontAdvancesMonospace", () => { |
| @@ -97,6 +98,16 @@ describe("resolveTerminalFontPreference", () => { · 80 unmodified lines | ||
| 97 | 98 | }); |
| 98 | 99 | }); |
| 99 | 100 | |
| 101 | +describe("resolveTerminalFontSizePreference", () => { | |
| 102 | + it("inherits the code font size in simple mode", () => { | |
| 103 | + expect(resolveTerminalFontSizePreference({ advanced: false, code: 15, terminal: 12 })).toBe(15); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("keeps code and terminal font sizes independent in advanced mode", () => { | |
| 107 | + expect(resolveTerminalFontSizePreference({ advanced: true, code: 15, terminal: 12 })).toBe(12); | |
| 108 | + }); | |
| 109 | +}); | |
| 110 | + | |
| 100 | 111 | describe("font size clamping", () => { |
| 101 | 112 | it("keeps sizes inside the ranges the UI can absorb", () => { |
| 102 | 113 | expect(clampInterfaceFontSize(16)).toBe(16); |
| @@ -41,6 +41,15 @@ export function resolveTerminalFontPreference(input: { · 40 unmodified lines | ||
| 41 | 41 | return input.code; |
| 42 | 42 | } |
| 43 | 43 | |
| 44 | +export function resolveTerminalFontSizePreference(input: { | |
| 45 | + readonly advanced: boolean; | |
| 46 | + readonly code: number; | |
| 47 | + readonly terminal: number; | |
| 48 | +}): number { | |
| 49 | + if (input.advanced) return input.terminal; | |
| 50 | + return input.code; | |
| 51 | +} | |
| 52 | + | |
| 44 | 53 | function quoteFontFamilyName(name: string): string { |
| 45 | 54 | const bare = name.trim(); |
| 46 | 55 | if (bare.length === 0) return ""; |
| @@ -11,51 +11,6 @@ export function formatAppDisplayName(input: { · 10 unmodified lines | ||
| 11 | 11 | return `${input.baseName} (${input.stageLabel})`; |
| 12 | 12 | } |
| 13 | 13 | |
| 14 | −/** | |
| 15 | − * Whether the sidebar v2 beta is on by default for a build stage. | |
| 16 | − * | |
| 17 | − * Nightly and local dev opt in; Alpha and Latest stay on v1. This is resolved | |
| 18 | − * from the client's own stage label rather than the connected server's version: | |
| 19 | − * v2 only exists in the client, so a stable client on a nightly server has | |
| 20 | − * nothing to turn on. | |
| 21 | − */ | |
| 22 | −export function resolveSidebarV2Default(stageLabel: string): boolean { | |
| 23 | − const stage = stageLabel.trim().toLowerCase(); | |
| 24 | − return stage === "nightly" || stage === "dev"; | |
| 25 | −} | |
| 26 | − | |
| 27 | −/** | |
| 28 | − * Resolved sidebar v2 state: an explicit choice if the user has made one, | |
| 29 | − * otherwise the default for this build stage. | |
| 30 | − * | |
| 31 | − * A stored `enabled: true` counts as an explicit choice even without the | |
| 32 | − * companion flag. `true` was never the schema default, so it can only have come | |
| 33 | − * from the Settings → Beta toggle — settings written before that flag existed | |
| 34 | − * would otherwise lose the opt-in and drop such users back to v1 on production. | |
| 35 | − * Mirrors how `normalizeDesktopSettingsDocument` treats a legacy stored | |
| 36 | − * `updateChannel: "nightly"` as user-configured. | |
| 37 | − * | |
| 38 | − * `settingsHydrated` guards the startup window: client settings load | |
| 39 | − * asynchronously and the pre-hydration snapshot is just the schema defaults, so | |
| 40 | − * resolving against it would mount one sidebar and swap it out a tick later, | |
| 41 | − * remounting the tree. While hydrating, hold v1 — where both paths already | |
| 42 | − * start. | |
| 43 | − */ | |
| 44 | −export function resolveSidebarV2Enabled(input: { | |
| 45 | − readonly enabled: boolean; | |
| 46 | − readonly configuredByUser: boolean; | |
| 47 | − readonly settingsHydrated: boolean; | |
| 48 | − readonly stageLabel: string; | |
| 49 | −}): boolean { | |
| 50 | − if (!input.settingsHydrated) { | |
| 51 | − return false; | |
| 52 | − } | |
| 53 | − | |
| 54 | − return input.configuredByUser || input.enabled | |
| 55 | − ? input.enabled | |
| 56 | − : resolveSidebarV2Default(input.stageLabel); | |
| 57 | −} | |
| 58 | − | |
| 59 | 14 | export function resolveServerBackedAppStageLabel(input: { |
| 60 | 15 | readonly primaryServerVersion: string | null | undefined; |
| 61 | 16 | readonly fallbackStageLabel: string; |
| @@ -2,8 +2,6 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test"; · 1 unmodified line | ||
| 2 | 2 | import { |
| 3 | 3 | resolveServerBackedAppDisplayName, |
| 4 | 4 | resolveServerBackedAppStageLabel, |
| 5 | − resolveSidebarV2Default, | |
| 6 | − resolveSidebarV2Enabled, | |
| 7 | 5 | } from "./branding.logic"; |
| 8 | 6 | |
| 9 | 7 | const originalWindow = globalThis.window; |
| @@ -116,74 +114,3 @@ describe("branding logic", () => { · 106 unmodified lines | ||
| 116 | 114 | ).toBe("T3 Code (Alpha)"); |
| 117 | 115 | }); |
| 118 | 116 | }); |
| 119 | − | |
| 120 | −describe("resolveSidebarV2Default", () => { | |
| 121 | − it.each(["Nightly", "Dev", "nightly", " dev "])("enables the beta for %s builds", (stage) => { | |
| 122 | − expect(resolveSidebarV2Default(stage)).toBe(true); | |
| 123 | − }); | |
| 124 | − | |
| 125 | − it.each(["Alpha", "Latest", ""])("leaves the beta off for %s builds", (stage) => { | |
| 126 | − expect(resolveSidebarV2Default(stage)).toBe(false); | |
| 127 | − }); | |
| 128 | −}); | |
| 129 | − | |
| 130 | −describe("resolveSidebarV2Enabled", () => { | |
| 131 | − const hydrated = { settingsHydrated: true } as const; | |
| 132 | − | |
| 133 | − it.each(["Alpha", "Latest"])( | |
| 134 | − "keeps a legacy opt-in on %s builds even without the companion flag", | |
| 135 | − (stageLabel) => { | |
| 136 | − // `true` was never the schema default, so it can only be an explicit | |
| 137 | − // opt-in from settings written before `sidebarV2ConfiguredByUser` existed. | |
| 138 | − expect( | |
| 139 | − resolveSidebarV2Enabled({ | |
| 140 | − ...hydrated, | |
| 141 | − enabled: true, | |
| 142 | − configuredByUser: false, | |
| 143 | − stageLabel, | |
| 144 | − }), | |
| 145 | − ).toBe(true); | |
| 146 | − }, | |
| 147 | − ); | |
| 148 | − | |
| 149 | − it("applies the stage default when the beta was never enabled or configured", () => { | |
| 150 | − expect( | |
| 151 | − resolveSidebarV2Enabled({ | |
| 152 | − ...hydrated, | |
| 153 | − enabled: false, | |
| 154 | − configuredByUser: false, | |
| 155 | − stageLabel: "Nightly", | |
| 156 | − }), | |
| 157 | − ).toBe(true); | |
| 158 | − expect( | |
| 159 | − resolveSidebarV2Enabled({ | |
| 160 | − ...hydrated, | |
| 161 | − enabled: false, | |
| 162 | − configuredByUser: false, | |
| 163 | − stageLabel: "Latest", | |
| 164 | − }), | |
| 165 | − ).toBe(false); | |
| 166 | − }); | |
| 167 | − | |
| 168 | − it("honors an explicit opt-out over the stage default", () => { | |
| 169 | − expect( | |
| 170 | − resolveSidebarV2Enabled({ | |
| 171 | − ...hydrated, | |
| 172 | − enabled: false, | |
| 173 | − configuredByUser: true, | |
| 174 | − stageLabel: "Nightly", | |
| 175 | − }), | |
| 176 | − ).toBe(false); | |
| 177 | − }); | |
| 178 | − | |
| 179 | − it("holds v1 until settings hydrate so the sidebar does not remount", () => { | |
| 180 | − expect( | |
| 181 | − resolveSidebarV2Enabled({ | |
| 182 | − enabled: true, | |
| 183 | − configuredByUser: true, | |
| 184 | − settingsHydrated: false, | |
| 185 | − stageLabel: "Nightly", | |
| 186 | − }), | |
| 187 | − ).toBe(false); | |
| 188 | − }); | |
| 189 | −}); | |
| @@ -14,9 +14,11 @@ import { getLocalStorageItem } from "../hooks/useLocalStorage"; · 13 unmodified lines | ||
| 14 | 14 | import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; |
| 15 | 15 | import { cn, isMacPlatform } from "../lib/utils"; |
| 16 | 16 | import { primaryServerKeybindingsAtom } from "../state/server"; |
| 17 | −import { useEnvironmentIdentificationMode, useSidebarV2Enabled } from "../hooks/useSettings"; | |
| 17 | +import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings"; | |
| 18 | +import LegacyThreadSidebar from "./LegacySidebar"; | |
| 18 | 19 | import ThreadSidebar from "./Sidebar"; |
| 19 | −import ThreadSidebarV2 from "./SidebarV2"; | |
| 20 | +import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; | |
| 21 | +import { SidebarChromeHeader } from "./sidebar/SidebarChrome"; | |
| 20 | 22 | import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop"; |
| 21 | 23 | import { |
| 22 | 24 | resolveInitialThreadSidebarWidth, |
| @@ -118,13 +120,11 @@ function SidebarControl() { · 95 unmodified lines | ||
| 118 | 120 | |
| 119 | 121 | export function AppSidebarLayout({ children }: { children: ReactNode }) { |
| 120 | 122 | const navigate = useNavigate(); |
| 121 | − const sidebarV2Enabled = useSidebarV2Enabled(); | |
| 122 | − // Settings routes render the settings nav, which lives in the v1 component | |
| 123 | − // and is identical for both sidebars — so v1 stays mounted there. | |
| 123 | + const legacySidebarEnabled = useLegacySidebarEnabled(); | |
| 124 | + // Settings routes show the settings nav in place of whichever thread | |
| 125 | + // sidebar is active. | |
| 124 | 126 | const pathname = useLocation({ select: (location) => location.pathname }); |
| 125 | 127 | const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/"); |
| 126 | − const useSidebarV2 = sidebarV2Enabled && !isOnSettings; | |
| 127 | − const useSidebarV2Theme = useSidebarV2 || isOnSettings; | |
| 128 | 128 | const isMacosDesktop = isElectron && isMacPlatform(navigator.platform); |
| 129 | 129 | const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth); |
| 130 | 130 | // Subscribed rather than read once: the clamp must track live window size, |
| @@ -188,7 +188,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { · 57 unmodified lines | ||
| 188 | 188 | side="left" |
| 189 | 189 | collapsible="offcanvas" |
| 190 | 190 | data-app-sidebar="" |
| 191 | − data-sidebar-version={useSidebarV2Theme ? "v2" : "v1"} | |
| 192 | 191 | className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground" |
| 193 | 192 | resizable={{ |
| 194 | 193 | maxWidth: sidebarMaximumWidth, |
| @@ -200,7 +199,16 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { · 5 unmodified lines | ||
| 200 | 199 | onResize: setSidebarWidth, |
| 201 | 200 | }} |
| 202 | 201 | > |
| 203 | − {useSidebarV2 ? <ThreadSidebarV2 /> : <ThreadSidebar />} | |
| 202 | + {isOnSettings ? ( | |
| 203 | + <> | |
| 204 | + <SidebarChromeHeader isElectron={isElectron} /> | |
| 205 | + <SettingsSidebarNav pathname={pathname} /> | |
| 206 | + </> | |
| 207 | + ) : legacySidebarEnabled ? ( | |
| 208 | + <LegacyThreadSidebar /> | |
| 209 | + ) : ( | |
| 210 | + <ThreadSidebar /> | |
| 211 | + )} | |
| 204 | 212 | <SidebarRail /> |
| 205 | 213 | </Sidebar> |
| 206 | 214 | {children} |
| @@ -126,7 +126,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({ · 125 unmodified lines | ||
| 126 | 126 | |
| 127 | 127 | if (isLocked) { |
| 128 | 128 | return ( |
| 129 | − <span className="inline-flex min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 md:hidden"> | |
| 129 | + <span className="inline-flex h-7 min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 md:hidden"> | |
| 130 | 130 | {triggerContent} |
| 131 | 131 | </span> |
| 132 | 132 | ); |
| @@ -50,7 +50,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe · 49 unmodified lines | ||
| 50 | 50 | |
| 51 | 51 | if (envLocked) { |
| 52 | 52 | return ( |
| 53 | − <span className="inline-flex shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs"> | |
| 53 | + <span className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"> | |
| 54 | 54 | {activeWorktreePath ? ( |
| 55 | 55 | <> |
| 56 | 56 | <FolderGitIcon className="size-3" /> |
| @@ -41,9 +41,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir · 40 unmodified lines | ||
| 41 | 41 | [availableEnvironments], |
| 42 | 42 | ); |
| 43 | 43 | |
| 44 | + // The static label carries the xs control's height (h-7 sm:h-6) as well as | |
| 45 | + // its padding: the composer context strip has no min-height of its own, and | |
| 46 | + // the glass seam joining it to the composer assumes a fixed strip height, so | |
| 47 | + // a shorter label would drag the seam out of line whenever this label is the | |
| 48 | + // only thing in the strip. | |
| 44 | 49 | if (envLocked || onEnvironmentChange === undefined) { |
| 45 | 50 | return ( |
| 46 | − <span className="inline-flex min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs"> | |
| 51 | + <span className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"> | |
| 47 | 52 | {activeEnvironment?.isPrimary ? ( |
| 48 | 53 | <MonitorIcon className="size-3 shrink-0" /> |
| 49 | 54 | ) : ( |
| @@ -6,7 +6,7 @@ import { · 5 unmodified lines | ||
| 6 | 6 | ThreadId, |
| 7 | 7 | TurnId, |
| 8 | 8 | } from "@t3tools/contracts"; |
| 9 | −import { describe, expect, it } from "vite-plus/test"; | |
| 9 | +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; | |
| 10 | 10 | |
| 11 | 11 | import type { Thread, ThreadShell } from "../types"; |
| 12 | 12 | import { |
| @@ -19,13 +19,16 @@ import { · 6 unmodified lines | ||
| 19 | 19 | createLocalDispatchSnapshot, |
| 20 | 20 | deriveComposerSendState, |
| 21 | 21 | dismissBranchMismatchForSession, |
| 22 | + ENVIRONMENT_RECONNECT_WARNING_GRACE_MS, | |
| 22 | 23 | getStartedThreadModelChangeBlockReason, |
| 24 | + hasEnvironmentReconnectWarningGraceElapsed, | |
| 23 | 25 | hasServerAcknowledgedLocalDispatch, |
| 24 | 26 | isBranchMismatchDismissedForSession, |
| 25 | 27 | reconcileMountedTerminalThreadIds, |
| 26 | 28 | reconcileRetainedMountedThreadIds, |
| 27 | 29 | resolveThreadMetadataUpdateForNextTurn, |
| 28 | 30 | resolveSendEnvMode, |
| 31 | + scheduleEnvironmentReconnectWarning, | |
| 29 | 32 | startNewThreadForProject, |
| 30 | 33 | shouldShowBranchMismatchBanner, |
| 31 | 34 | shouldWriteThreadErrorToCurrentServerThread, |
| @@ -36,6 +39,42 @@ const projectId = ProjectId.make("project-1"); · 4 unmodified lines | ||
| 36 | 39 | const threadId = ThreadId.make("thread-1"); |
| 37 | 40 | const now = "2026-03-29T00:00:00.000Z"; |
| 38 | 41 | |
| 42 | +describe("environment reconnect warning grace", () => { | |
| 43 | + afterEach(() => vi.useRealTimers()); | |
| 44 | + | |
| 45 | + it("shows a persistent reconnect after the grace period", () => { | |
| 46 | + vi.useFakeTimers(); | |
| 47 | + const showWarning = vi.fn(); | |
| 48 | + | |
| 49 | + scheduleEnvironmentReconnectWarning(showWarning); | |
| 50 | + vi.advanceTimersByTime(ENVIRONMENT_RECONNECT_WARNING_GRACE_MS - 1); | |
| 51 | + expect(showWarning).not.toHaveBeenCalled(); | |
| 52 | + | |
| 53 | + vi.advanceTimersByTime(1); | |
| 54 | + expect(showWarning).toHaveBeenCalledOnce(); | |
| 55 | + }); | |
| 56 | + | |
| 57 | + it("cancels the warning when the connection recovers during the grace period", () => { | |
| 58 | + vi.useFakeTimers(); | |
| 59 | + const showWarning = vi.fn(); | |
| 60 | + | |
| 61 | + const cancel = scheduleEnvironmentReconnectWarning(showWarning); | |
| 62 | + cancel(); | |
| 63 | + vi.advanceTimersByTime(ENVIRONMENT_RECONNECT_WARNING_GRACE_MS); | |
| 64 | + | |
| 65 | + expect(showWarning).not.toHaveBeenCalled(); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + it("does not reuse elapsed grace from another environment", () => { | |
| 69 | + const anotherEnvironmentId = EnvironmentId.make("environment-remote"); | |
| 70 | + | |
| 71 | + expect(hasEnvironmentReconnectWarningGraceElapsed(environmentId, environmentId)).toBe(true); | |
| 72 | + expect(hasEnvironmentReconnectWarningGraceElapsed(anotherEnvironmentId, environmentId)).toBe( | |
| 73 | + false, | |
| 74 | + ); | |
| 75 | + }); | |
| 76 | +}); | |
| 77 | + | |
| 39 | 78 | function makeThread(overrides: Partial<Thread> = {}): Thread { |
| 40 | 79 | return { |
| 41 | 80 | id: threadId, |
| @@ -25,9 +25,22 @@ import type { DraftThreadEnvMode } from "../composerDraftStore"; · 24 unmodified lines | ||
| 25 | 25 | export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project"; |
| 26 | 26 | export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10; |
| 27 | 27 | export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3; |
| 28 | +export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000; | |
| 28 | 29 | |
| 29 | 30 | export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String); |
| 30 | 31 | |
| 32 | +export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void { | |
| 33 | + const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS); | |
| 34 | + return () => globalThis.clearTimeout(timeoutId); | |
| 35 | +} | |
| 36 | + | |
| 37 | +export function hasEnvironmentReconnectWarningGraceElapsed( | |
| 38 | + activeEnvironmentId: EnvironmentId | null, | |
| 39 | + elapsedEnvironmentId: EnvironmentId | null, | |
| 40 | +): boolean { | |
| 41 | + return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId; | |
| 42 | +} | |
| 43 | + | |
| 31 | 44 | export function startNewThreadForProject( |
| 32 | 45 | projectRef: ScopedProjectRef | null, |
| 33 | 46 | handleNewThread: (projectRef: ScopedProjectRef) => Promise<void>, |
| @@ -283,6 +283,8 @@ import { · 282 unmodified lines | ||
| 283 | 283 | createLocalDispatchSnapshot, |
| 284 | 284 | deriveComposerSendState, |
| 285 | 285 | dismissBranchMismatchForSession, |
| 286 | + hasEnvironmentReconnectWarningGraceElapsed, | |
| 287 | + scheduleEnvironmentReconnectWarning, | |
| 286 | 288 | hasServerAcknowledgedLocalDispatch, |
| 287 | 289 | isBranchMismatchDismissedForSession, |
| 288 | 290 | shouldShowBranchMismatchBanner, |
| @@ -1733,6 +1735,24 @@ function ChatViewContent(props: ChatViewProps) { · 1444 unmodified lines | ||
| 1733 | 1735 | const activeEnvironmentConnectionPhase = activeEnvironment?.connection.phase ?? "available"; |
| 1734 | 1736 | const activeEnvironmentUnavailable = |
| 1735 | 1737 | activeEnvironment !== null && activeEnvironmentConnectionPhase !== "connected"; |
| 1738 | + const activeReconnectingEnvironmentId = | |
| 1739 | + activeEnvironmentConnectionPhase === "connecting" || | |
| 1740 | + activeEnvironmentConnectionPhase === "reconnecting" | |
| 1741 | + ? (activeEnvironment?.environmentId ?? null) | |
| 1742 | + : null; | |
| 1743 | + const [reconnectWarningGraceElapsedEnvironmentId, setReconnectWarningGraceElapsedEnvironmentId] = | |
| 1744 | + useState<EnvironmentId | null>(null); | |
| 1745 | + const reconnectWarningGraceElapsed = hasEnvironmentReconnectWarningGraceElapsed( | |
| 1746 | + activeReconnectingEnvironmentId, | |
| 1747 | + reconnectWarningGraceElapsedEnvironmentId, | |
| 1748 | + ); | |
| 1749 | + useEffect(() => { | |
| 1750 | + setReconnectWarningGraceElapsedEnvironmentId(null); | |
| 1751 | + if (activeReconnectingEnvironmentId === null) return; | |
| 1752 | + return scheduleEnvironmentReconnectWarning(() => | |
| 1753 | + setReconnectWarningGraceElapsedEnvironmentId(activeReconnectingEnvironmentId), | |
| 1754 | + ); | |
| 1755 | + }, [activeReconnectingEnvironmentId]); | |
| 1736 | 1756 | const activeEnvironmentUnavailableLabel = activeEnvironment?.label ?? null; |
| 1737 | 1757 | const activeEnvironmentUnavailableState = useMemo<EnvironmentUnavailableState | null>(() => { |
| 1738 | 1758 | if (!activeEnvironmentUnavailable || !activeEnvironmentUnavailableLabel || !activeEnvironment) { |
| @@ -1965,7 +1985,9 @@ function ChatViewContent(props: ChatViewProps) { · 226 unmodified lines | ||
| 1965 | 1985 | // While an update runs, transient connect blips are expected (the server |
| 1966 | 1986 | // restarts) and the update banner already shows progress. Hard failure |
| 1967 | 1987 | // phases still surface so the Reconnect action stays reachable. |
| 1968 | − const suppressUnavailableBanner = updateRunning && environmentReconnecting; | |
| 1988 | + const suppressUnavailableBanner = | |
| 1989 | + environmentReconnecting && | |
| 1990 | + (updateRunning || (!reconnectingThroughVersionSkew && !reconnectWarningGraceElapsed)); | |
| 1969 | 1991 | if (activeEnvironmentUnavailableState && unavailableConnection && !suppressUnavailableBanner) { |
| 1970 | 1992 | if (reconnectingThroughVersionSkew) { |
| 1971 | 1993 | items.push({ |
| @@ -2093,6 +2115,7 @@ function ChatViewContent(props: ChatViewProps) { · 121 unmodified lines | ||
| 2093 | 2115 | return items; |
| 2094 | 2116 | }, [ |
| 2095 | 2117 | activeEnvironmentUnavailableState, |
| 2118 | + reconnectWarningGraceElapsed, | |
| 2096 | 2119 | handleReconnectActiveEnvironment, |
| 2097 | 2120 | navigate, |
| 2098 | 2121 | setDismissedVersionMismatchKey, |
| @@ -0,0 +1,3627 @@ | ||
| 1 | +import { | |
| 2 | + ArchiveIcon, | |
| 3 | + ArrowUpDownIcon, | |
| 4 | + ChevronRightIcon, | |
| 5 | + CloudIcon, | |
| 6 | + ContainerIcon, | |
| 7 | + FolderPlusIcon, | |
| 8 | + Globe2Icon, | |
| 9 | + LoaderIcon, | |
| 10 | + SearchIcon, | |
| 11 | + SquarePenIcon, | |
| 12 | + TerminalIcon, | |
| 13 | + TriangleAlertIcon, | |
| 14 | +} from "lucide-react"; | |
| 15 | +import { | |
| 16 | + ChangeRequestStatusIcon, | |
| 17 | + prStatusIndicator, | |
| 18 | + PrStatusTooltipContent, | |
| 19 | + resolveThreadPr, | |
| 20 | + terminalStatusFromRunningIds, | |
| 21 | + ThreadStatusLabel, | |
| 22 | + ThreadWorktreeIndicator, | |
| 23 | +} from "./ThreadStatusIndicators"; | |
| 24 | +import { ProjectFavicon } from "./ProjectFavicon"; | |
| 25 | +import { useAtomValue } from "@effect/atom-react"; | |
| 26 | +import { autoAnimate } from "@formkit/auto-animate"; | |
| 27 | +import React, { useCallback, useEffect, memo, useMemo, useRef, useState } from "react"; | |
| 28 | +import { useShallow } from "zustand/react/shallow"; | |
| 29 | +import { | |
| 30 | + DndContext, | |
| 31 | + type DragCancelEvent, | |
| 32 | + type CollisionDetection, | |
| 33 | + PointerSensor, | |
| 34 | + type DragStartEvent, | |
| 35 | + closestCorners, | |
| 36 | + pointerWithin, | |
| 37 | + useSensor, | |
| 38 | + useSensors, | |
| 39 | + type DragEndEvent, | |
| 40 | +} from "@dnd-kit/core"; | |
| 41 | +import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; | |
| 42 | +import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers"; | |
| 43 | +import { CSS } from "@dnd-kit/utilities"; | |
| 44 | +import { | |
| 45 | + type ContextMenuItem, | |
| 46 | + ProjectId, | |
| 47 | + type ScopedThreadRef, | |
| 48 | + type ResolvedKeybindingsConfig, | |
| 49 | + type SidebarProjectGroupingMode, | |
| 50 | + ThreadId, | |
| 51 | +} from "@t3tools/contracts"; | |
| 52 | +import { | |
| 53 | + parseScopedThreadKey, | |
| 54 | + scopedProjectKey, | |
| 55 | + scopedThreadKey, | |
| 56 | + scopeProjectRef, | |
| 57 | + scopeThreadRef, | |
| 58 | +} from "@t3tools/client-runtime/environment"; | |
| 59 | +import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; | |
| 60 | +import { | |
| 61 | + isAtomCommandInterrupted, | |
| 62 | + settlePromise, | |
| 63 | + squashAtomCommandFailure, | |
| 64 | +} from "@t3tools/client-runtime/state/runtime"; | |
| 65 | +import { useNavigate, useParams, useRouter } from "@tanstack/react-router"; | |
| 66 | +import { | |
| 67 | + MAX_SIDEBAR_THREAD_PREVIEW_COUNT, | |
| 68 | + MIN_SIDEBAR_THREAD_PREVIEW_COUNT, | |
| 69 | + type SidebarProjectSortOrder, | |
| 70 | + type SidebarThreadPreviewCount, | |
| 71 | + type SidebarThreadSortOrder, | |
| 72 | +} from "@t3tools/contracts/settings"; | |
| 73 | +import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal"; | |
| 74 | +import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps"; | |
| 75 | +import { isElectron } from "../env"; | |
| 76 | +import { useOpenPrLink } from "../lib/openPullRequestLink"; | |
| 77 | +import { isTerminalFocused } from "../lib/terminalFocus"; | |
| 78 | +import { isMacPlatform } from "../lib/utils"; | |
| 79 | +import { | |
| 80 | + readThreadShell, | |
| 81 | + useProject, | |
| 82 | + useProjects, | |
| 83 | + useThreadShells, | |
| 84 | + useThreadShellsForProjectRefs, | |
| 85 | +} from "../state/entities"; | |
| 86 | +import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; | |
| 87 | +import { useThreadRunningTerminalIds } from "../state/terminalSessions"; | |
| 88 | +import { useThreadDiscoveredPorts } from "../portDiscoveryState"; | |
| 89 | +import { openDiscoveredPort } from "./preview/openDiscoveredPort"; | |
| 90 | +import { useAtomCommand } from "../state/use-atom-command"; | |
| 91 | +import { previewEnvironment } from "../state/preview"; | |
| 92 | +import { | |
| 93 | + legacyProjectCwdPreferenceKey, | |
| 94 | + resolveProjectExpanded, | |
| 95 | + useUiStateStore, | |
| 96 | +} from "../uiStateStore"; | |
| 97 | +import { | |
| 98 | + resolveShortcutCommand, | |
| 99 | + shortcutLabelForCommand, | |
| 100 | + shouldShowThreadJumpHintsForModifiers, | |
| 101 | + threadJumpCommandForIndex, | |
| 102 | + threadJumpIndexFromCommand, | |
| 103 | + threadTraversalDirectionFromCommand, | |
| 104 | +} from "../keybindings"; | |
| 105 | +import { isModelPickerOpen } from "../modelPickerVisibility"; | |
| 106 | +import { useShortcutModifierState } from "../shortcutModifierState"; | |
| 107 | +import { readLocalApi } from "../localApi"; | |
| 108 | +import { useComposerDraftStore } from "../composerDraftStore"; | |
| 109 | +import { useNewThreadHandler } from "../hooks/useHandleNewThread"; | |
| 110 | +import { useDesktopUpdateState } from "../state/desktopUpdate"; | |
| 111 | + | |
| 112 | +import { useThreadActions } from "../hooks/useThreadActions"; | |
| 113 | +import { projectEnvironment } from "../state/projects"; | |
| 114 | +import { useEnvironmentQuery } from "../state/query"; | |
| 115 | +import { threadEnvironment, useEnvironmentThread } from "../state/threads"; | |
| 116 | +import { vcsEnvironment } from "../state/vcs"; | |
| 117 | +import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; | |
| 118 | +import { | |
| 119 | + buildThreadRouteParams, | |
| 120 | + resolveActiveThreadRouteRef, | |
| 121 | + resolveThreadRouteTarget, | |
| 122 | +} from "../threadRoutes"; | |
| 123 | +import { stackedThreadToast, toastManager } from "./ui/toast"; | |
| 124 | +import { formatRelativeTimeLabel } from "../timestampFormat"; | |
| 125 | +import { Kbd } from "./ui/kbd"; | |
| 126 | +import { | |
| 127 | + getArm64IntelBuildWarningDescription, | |
| 128 | + getDesktopUpdateActionError, | |
| 129 | + getDesktopUpdateInstallConfirmationMessage, | |
| 130 | + isDesktopUpdateButtonDisabled, | |
| 131 | + resolveDesktopUpdateButtonAction, | |
| 132 | + shouldShowArm64IntelBuildWarning, | |
| 133 | + shouldToastDesktopUpdateActionResult, | |
| 134 | +} from "./desktopUpdate.logic"; | |
| 135 | +import { showDesktopUpdateDownloadedToast } from "./desktopUpdate.toast"; | |
| 136 | +import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; | |
| 137 | +import { Button } from "./ui/button"; | |
| 138 | +import { | |
| 139 | + Dialog, | |
| 140 | + DialogDescription, | |
| 141 | + DialogFooter, | |
| 142 | + DialogHeader, | |
| 143 | + DialogPanel, | |
| 144 | + DialogPopup, | |
| 145 | + DialogTitle, | |
| 146 | +} from "./ui/dialog"; | |
| 147 | +import { Input } from "./ui/input"; | |
| 148 | +import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; | |
| 149 | +import { | |
| 150 | + NumberField, | |
| 151 | + NumberFieldDecrement, | |
| 152 | + NumberFieldGroup, | |
| 153 | + NumberFieldIncrement, | |
| 154 | + NumberFieldInput, | |
| 155 | +} from "./ui/number-field"; | |
| 156 | +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; | |
| 157 | +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; | |
| 158 | +import { | |
| 159 | + SidebarContent, | |
| 160 | + SidebarGroup, | |
| 161 | + SidebarMenu, | |
| 162 | + SidebarMenuButton, | |
| 163 | + SidebarMenuItem, | |
| 164 | + SidebarMenuSub, | |
| 165 | + SidebarMenuSubButton, | |
| 166 | + SidebarMenuSubItem, | |
| 167 | + useSidebar, | |
| 168 | +} from "./ui/sidebar"; | |
| 169 | +import { useThreadSelectionStore } from "../threadSelectionStore"; | |
| 170 | +import { openCommandPalette } from "../commandPaletteBus"; | |
| 171 | +import { | |
| 172 | + archiveSelectedThreadEntries, | |
| 173 | + buildMultiSelectThreadContextMenuItems, | |
| 174 | + getSidebarThreadIdsToPrewarm, | |
| 175 | + resolveAdjacentThreadId, | |
| 176 | + isContextMenuPointerDown, | |
| 177 | + isTrailingDoubleClick, | |
| 178 | + resolveProjectStatusIndicator, | |
| 179 | + resolveThreadRowClassName, | |
| 180 | + resolveThreadStatusPill, | |
| 181 | + orderItemsByPreferredIds, | |
| 182 | + shouldClearThreadSelectionOnMouseDown, | |
| 183 | + sortProjectsForSidebar, | |
| 184 | + useThreadJumpHintVisibility, | |
| 185 | + ThreadStatusPill, | |
| 186 | +} from "./Sidebar.logic"; | |
| 187 | +import { sortThreads } from "../lib/threadSort"; | |
| 188 | +import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; | |
| 189 | +import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; | |
| 190 | +import { useIsMobile } from "~/hooks/useMediaQuery"; | |
| 191 | +import { CommandDialogTrigger } from "./ui/command"; | |
| 192 | +import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings"; | |
| 193 | +import { primaryServerKeybindingsAtom } from "../state/server"; | |
| 194 | +import { | |
| 195 | + derivePhysicalProjectKey, | |
| 196 | + deriveProjectGroupingOverrideKey, | |
| 197 | + getProjectOrderKey, | |
| 198 | + selectProjectGroupingSettings, | |
| 199 | +} from "../logicalProject"; | |
| 200 | +import type { SidebarThreadSummary } from "../types"; | |
| 201 | +import { | |
| 202 | + buildPhysicalToLogicalProjectKeyMap, | |
| 203 | + buildSidebarProjectSnapshots, | |
| 204 | + type SidebarProjectGroupMember, | |
| 205 | + type SidebarProjectSnapshot, | |
| 206 | +} from "../sidebarProjectGrouping"; | |
| 207 | +const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = { | |
| 208 | + updated_at: "Last user message", | |
| 209 | + created_at: "Created at", | |
| 210 | + manual: "Manual", | |
| 211 | +}; | |
| 212 | +const SIDEBAR_THREAD_SORT_LABELS: Record<SidebarThreadSortOrder, string> = { | |
| 213 | + updated_at: "Last user message", | |
| 214 | + created_at: "Created at", | |
| 215 | +}; | |
| 216 | +const SIDEBAR_LIST_ANIMATION_OPTIONS = { | |
| 217 | + duration: 180, | |
| 218 | + easing: "ease-out", | |
| 219 | +} as const; | |
| 220 | +const EMPTY_THREAD_JUMP_LABELS = new Map<string, string>(); | |
| 221 | +const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = { | |
| 222 | + repository: "Group by repository", | |
| 223 | + repository_path: "Group by repository path", | |
| 224 | + separate: "Keep separate", | |
| 225 | +}; | |
| 226 | +const SIDEBAR_ICON_ACTION_BUTTON_CLASS = | |
| 227 | + "inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-icon-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"; | |
| 228 | + | |
| 229 | +function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: ScopedThreadRef }) { | |
| 230 | + useEnvironmentThread(threadRef.environmentId, threadRef.threadId); | |
| 231 | + return null; | |
| 232 | +} | |
| 233 | + | |
| 234 | +function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount { | |
| 235 | + return Math.min( | |
| 236 | + MAX_SIDEBAR_THREAD_PREVIEW_COUNT, | |
| 237 | + Math.max(MIN_SIDEBAR_THREAD_PREVIEW_COUNT, value), | |
| 238 | + ) as SidebarThreadPreviewCount; | |
| 239 | +} | |
| 240 | + | |
| 241 | +function formatProjectMemberActionLabel( | |
| 242 | + member: SidebarProjectGroupMember, | |
| 243 | + groupedProjectCount: number, | |
| 244 | +): string { | |
| 245 | + if (groupedProjectCount <= 1) { | |
| 246 | + return member.title; | |
| 247 | + } | |
| 248 | + | |
| 249 | + return member.environmentLabel | |
| 250 | + ? `${member.environmentLabel} — ${member.workspaceRoot}` | |
| 251 | + : member.workspaceRoot; | |
| 252 | +} | |
| 253 | + | |
| 254 | +function projectExpansionPreferenceKeys(project: SidebarProjectSnapshot): string[] { | |
| 255 | + return [ | |
| 256 | + project.projectKey, | |
| 257 | + ...project.memberProjects.map((member) => member.physicalProjectKey), | |
| 258 | + ...project.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)), | |
| 259 | + ]; | |
| 260 | +} | |
| 261 | + | |
| 262 | +function projectGroupingModeDescription(mode: SidebarProjectGroupingMode): string { | |
| 263 | + switch (mode) { | |
| 264 | + case "repository": | |
| 265 | + return "Projects from the same repository share one sidebar row."; | |
| 266 | + case "repository_path": | |
| 267 | + return "Projects group only when both the repository and repo-relative path match."; | |
| 268 | + case "separate": | |
| 269 | + return "Every project path gets its own sidebar row."; | |
| 270 | + } | |
| 271 | +} | |
| 272 | + | |
| 273 | +function buildThreadJumpLabelMap(input: { | |
| 274 | + keybindings: ResolvedKeybindingsConfig; | |
| 275 | + platform: string; | |
| 276 | + terminalOpen: boolean; | |
| 277 | + threadJumpCommandByKey: ReadonlyMap< | |
| 278 | + string, | |
| 279 | + NonNullable<ReturnType<typeof threadJumpCommandForIndex>> | |
| 280 | + >; | |
| 281 | +}): ReadonlyMap<string, string> { | |
| 282 | + if (input.threadJumpCommandByKey.size === 0) { | |
| 283 | + return EMPTY_THREAD_JUMP_LABELS; | |
| 284 | + } | |
| 285 | + | |
| 286 | + const shortcutLabelOptions = { | |
| 287 | + platform: input.platform, | |
| 288 | + context: { | |
| 289 | + terminalFocus: false, | |
| 290 | + terminalOpen: input.terminalOpen, | |
| 291 | + }, | |
| 292 | + } as const; | |
| 293 | + const mapping = new Map<string, string>(); | |
| 294 | + for (const [threadKey, command] of input.threadJumpCommandByKey) { | |
| 295 | + const label = shortcutLabelForCommand(input.keybindings, command, shortcutLabelOptions); | |
| 296 | + if (label) { | |
| 297 | + mapping.set(threadKey, label); | |
| 298 | + } | |
| 299 | + } | |
| 300 | + return mapping.size > 0 ? mapping : EMPTY_THREAD_JUMP_LABELS; | |
| 301 | +} | |
| 302 | + | |
| 303 | +interface SidebarThreadRowProps { | |
| 304 | + thread: SidebarThreadSummary; | |
| 305 | + projectCwd: string | null; | |
| 306 | + orderedProjectThreadKeys: readonly string[]; | |
| 307 | + isActive: boolean; | |
| 308 | + jumpLabel: string | null; | |
| 309 | + appSettingsConfirmThreadArchive: boolean; | |
| 310 | + renamingThreadKey: string | null; | |
| 311 | + renamingTitle: string; | |
| 312 | + setRenamingTitle: (title: string) => void; | |
| 313 | + startThreadRename: (threadKey: string, title: string) => void; | |
| 314 | + renamingInputRef: React.RefObject<HTMLInputElement | null>; | |
| 315 | + renamingCommittedRef: React.RefObject<boolean>; | |
| 316 | + confirmingArchiveThreadKey: string | null; | |
| 317 | + setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>; | |
| 318 | + confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>; | |
| 319 | + handleThreadClick: ( | |
| 320 | + event: React.MouseEvent, | |
| 321 | + threadRef: ScopedThreadRef, | |
| 322 | + orderedProjectThreadKeys: readonly string[], | |
| 323 | + ) => void; | |
| 324 | + navigateToThread: (threadRef: ScopedThreadRef) => void; | |
| 325 | + handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise<void>; | |
| 326 | + handleThreadContextMenu: ( | |
| 327 | + threadRef: ScopedThreadRef, | |
| 328 | + position: { x: number; y: number }, | |
| 329 | + ) => Promise<void>; | |
| 330 | + clearSelection: () => void; | |
| 331 | + commitRename: ( | |
| 332 | + threadRef: ScopedThreadRef, | |
| 333 | + newTitle: string, | |
| 334 | + originalTitle: string, | |
| 335 | + ) => Promise<void>; | |
| 336 | + cancelRename: () => void; | |
| 337 | + attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise<void>; | |
| 338 | + openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void; | |
| 339 | +} | |
| 340 | + | |
| 341 | +export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) { | |
| 342 | + const { | |
| 343 | + orderedProjectThreadKeys, | |
| 344 | + isActive, | |
| 345 | + jumpLabel, | |
| 346 | + appSettingsConfirmThreadArchive, | |
| 347 | + renamingThreadKey, | |
| 348 | + renamingTitle, | |
| 349 | + setRenamingTitle, | |
| 350 | + startThreadRename, | |
| 351 | + renamingInputRef, | |
| 352 | + renamingCommittedRef, | |
| 353 | + confirmingArchiveThreadKey, | |
| 354 | + setConfirmingArchiveThreadKey, | |
| 355 | + confirmArchiveButtonRefs, | |
| 356 | + handleThreadClick, | |
| 357 | + navigateToThread, | |
| 358 | + handleMultiSelectContextMenu, | |
| 359 | + handleThreadContextMenu, | |
| 360 | + clearSelection, | |
| 361 | + commitRename, | |
| 362 | + cancelRename, | |
| 363 | + attemptArchiveThread, | |
| 364 | + openPrLink, | |
| 365 | + thread, | |
| 366 | + } = props; | |
| 367 | + const threadRef = scopeThreadRef(thread.environmentId, thread.id); | |
| 368 | + const threadKey = scopedThreadKey(threadRef); | |
| 369 | + const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); | |
| 370 | + const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); | |
| 371 | + const runningTerminalIds = useThreadRunningTerminalIds({ | |
| 372 | + environmentId: thread.environmentId, | |
| 373 | + threadId: thread.id, | |
| 374 | + }); | |
| 375 | + const isMobile = useIsMobile(); | |
| 376 | + const discoveredPorts = useThreadDiscoveredPorts({ | |
| 377 | + environmentId: thread.environmentId, | |
| 378 | + threadId: thread.id, | |
| 379 | + }); | |
| 380 | + const openPreview = useAtomCommand(previewEnvironment.open, { | |
| 381 | + reportFailure: false, | |
| 382 | + }); | |
| 383 | + const environment = useEnvironment(thread.environmentId); | |
| 384 | + const primaryEnvironmentId = usePrimaryEnvironmentId(); | |
| 385 | + const isRemoteThread = | |
| 386 | + primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId; | |
| 387 | + const remoteEnvLabel = environment?.label ?? null; | |
| 388 | + // A desktop-local secondary backend (e.g. the WSL backend) shows up as a | |
| 389 | + // bearer environment whose connection id is prefixed "local:". It runs on the | |
| 390 | + // user's own machine, so the cloud icon is misleading — label it "Local" and | |
| 391 | + // suppress the cloud icon (the project header already shows a container icon | |
| 392 | + // for desktop-local projects, see sidebarProjectGrouping). | |
| 393 | + const isDesktopLocalThread = | |
| 394 | + environment !== null && isDesktopLocalConnectionTarget(environment.entry.target); | |
| 395 | + const threadEnvironmentLabel = isRemoteThread | |
| 396 | + ? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote")) | |
| 397 | + : null; | |
| 398 | + // For grouped projects, the thread may belong to a different environment | |
| 399 | + // than the representative project. Look up the thread's own project cwd | |
| 400 | + // so git status (and thus PR detection) queries the correct path. | |
| 401 | + const threadProject = useProject( | |
| 402 | + useMemo( | |
| 403 | + () => scopeProjectRef(thread.environmentId, thread.projectId), | |
| 404 | + [thread.environmentId, thread.projectId], | |
| 405 | + ), | |
| 406 | + ); | |
| 407 | + const threadProjectCwd = threadProject?.workspaceRoot ?? null; | |
| 408 | + const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd; | |
| 409 | + const gitStatus = useEnvironmentQuery( | |
| 410 | + thread.branch != null && gitCwd !== null | |
| 411 | + ? vcsEnvironment.status({ | |
| 412 | + environmentId: thread.environmentId, | |
| 413 | + input: { cwd: gitCwd }, | |
| 414 | + }) | |
| 415 | + : null, | |
| 416 | + ); | |
| 417 | + const isHighlighted = isActive || isSelected; | |
| 418 | + const handleOpenDiscoveredPort = useCallback( | |
| 419 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 420 | + const port = discoveredPorts[0]; | |
| 421 | + if (!port) return; | |
| 422 | + event.preventDefault(); | |
| 423 | + event.stopPropagation(); | |
| 424 | + navigateToThread(threadRef); | |
| 425 | + void (async () => { | |
| 426 | + const result = await openDiscoveredPort({ threadRef, port, openPreview }); | |
| 427 | + if (result._tag === "Success" || isAtomCommandInterrupted(result)) { | |
| 428 | + return; | |
| 429 | + } | |
| 430 | + const error = squashAtomCommandFailure(result); | |
| 431 | + toastManager.add( | |
| 432 | + stackedThreadToast({ | |
| 433 | + type: "error", | |
| 434 | + title: "Unable to open preview", | |
| 435 | + description: | |
| 436 | + error instanceof Error ? error.message : "The preview could not be opened.", | |
| 437 | + }), | |
| 438 | + ); | |
| 439 | + })(); | |
| 440 | + }, | |
| 441 | + [discoveredPorts, navigateToThread, openPreview, threadRef], | |
| 442 | + ); | |
| 443 | + const isThreadRunning = | |
| 444 | + thread.session?.status === "running" && thread.session.activeTurnId != null; | |
| 445 | + const threadStatus = resolveThreadStatusPill({ | |
| 446 | + thread: { | |
| 447 | + ...thread, | |
| 448 | + lastVisitedAt, | |
| 449 | + }, | |
| 450 | + }); | |
| 451 | + const pr = resolveThreadPr({ | |
| 452 | + threadBranch: thread.branch, | |
| 453 | + gitStatus: gitStatus.data, | |
| 454 | + }); | |
| 455 | + const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider); | |
| 456 | + const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); | |
| 457 | + const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning; | |
| 458 | + const threadMetaClassName = isConfirmingArchive | |
| 459 | + ? "pointer-events-none opacity-0" | |
| 460 | + : !isThreadRunning | |
| 461 | + ? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0" | |
| 462 | + : "pointer-events-none"; | |
| 463 | + const clearConfirmingArchive = useCallback(() => { | |
| 464 | + setConfirmingArchiveThreadKey((current) => (current === threadKey ? null : current)); | |
| 465 | + }, [setConfirmingArchiveThreadKey, threadKey]); | |
| 466 | + const handleMouseLeave = useCallback(() => { | |
| 467 | + clearConfirmingArchive(); | |
| 468 | + }, [clearConfirmingArchive]); | |
| 469 | + const handleBlurCapture = useCallback( | |
| 470 | + (event: React.FocusEvent<HTMLLIElement>) => { | |
| 471 | + const currentTarget = event.currentTarget; | |
| 472 | + requestAnimationFrame(() => { | |
| 473 | + if (currentTarget.contains(document.activeElement)) { | |
| 474 | + return; | |
| 475 | + } | |
| 476 | + clearConfirmingArchive(); | |
| 477 | + }); | |
| 478 | + }, | |
| 479 | + [clearConfirmingArchive], | |
| 480 | + ); | |
| 481 | + const handleRowClick = useCallback( | |
| 482 | + (event: React.MouseEvent) => { | |
| 483 | + handleThreadClick(event, threadRef, orderedProjectThreadKeys); | |
| 484 | + }, | |
| 485 | + [handleThreadClick, orderedProjectThreadKeys, threadRef], | |
| 486 | + ); | |
| 487 | + const handleRowDoubleClick = useCallback( | |
| 488 | + (event: React.MouseEvent) => { | |
| 489 | + // Already renaming this row: a double-click on the row chrome (outside the | |
| 490 | + // input) must not restart and discard the in-progress edit. | |
| 491 | + if (renamingThreadKey === threadKey) return; | |
| 492 | + // On mobile the first tap navigates and closes the sidebar sheet, so the | |
| 493 | + // inline rename can't be shown. Renaming there stays on the context menu. | |
| 494 | + if (isMobile) return; | |
| 495 | + // cmd/ctrl/shift double-clicks are multi-select intent, not rename. | |
| 496 | + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; | |
| 497 | + // Ignore double-clicks bubbling from nested controls (PR status, port, | |
| 498 | + // archive buttons) — only the row body should enter inline rename. | |
| 499 | + if ((event.target as HTMLElement).closest("button, a")) return; | |
| 500 | + event.preventDefault(); | |
| 501 | + startThreadRename(threadKey, thread.title); | |
| 502 | + }, | |
| 503 | + [isMobile, renamingThreadKey, startThreadRename, threadKey, thread.title], | |
| 504 | + ); | |
| 505 | + const handleRowKeyDown = useCallback( | |
| 506 | + (event: React.KeyboardEvent) => { | |
| 507 | + if (event.key !== "Enter" && event.key !== " ") return; | |
| 508 | + event.preventDefault(); | |
| 509 | + navigateToThread(threadRef); | |
| 510 | + }, | |
| 511 | + [navigateToThread, threadRef], | |
| 512 | + ); | |
| 513 | + const handleRowContextMenu = useCallback( | |
| 514 | + (event: React.MouseEvent) => { | |
| 515 | + event.preventDefault(); | |
| 516 | + const hasSelection = useThreadSelectionStore.getState().hasSelection(); | |
| 517 | + if (hasSelection && isSelected) { | |
| 518 | + void (async () => { | |
| 519 | + const result = await settlePromise(() => | |
| 520 | + handleMultiSelectContextMenu({ | |
| 521 | + x: event.clientX, | |
| 522 | + y: event.clientY, | |
| 523 | + }), | |
| 524 | + ); | |
| 525 | + if (result._tag === "Failure") { | |
| 526 | + const error = squashAtomCommandFailure(result); | |
| 527 | + toastManager.add( | |
| 528 | + stackedThreadToast({ | |
| 529 | + type: "error", | |
| 530 | + title: "Thread action failed", | |
| 531 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 532 | + }), | |
| 533 | + ); | |
| 534 | + } | |
| 535 | + })(); | |
| 536 | + return; | |
| 537 | + } | |
| 538 | + | |
| 539 | + if (hasSelection) { | |
| 540 | + clearSelection(); | |
| 541 | + } | |
| 542 | + void (async () => { | |
| 543 | + const result = await settlePromise(() => | |
| 544 | + handleThreadContextMenu(threadRef, { | |
| 545 | + x: event.clientX, | |
| 546 | + y: event.clientY, | |
| 547 | + }), | |
| 548 | + ); | |
| 549 | + if (result._tag === "Failure") { | |
| 550 | + const error = squashAtomCommandFailure(result); | |
| 551 | + toastManager.add( | |
| 552 | + stackedThreadToast({ | |
| 553 | + type: "error", | |
| 554 | + title: "Thread action failed", | |
| 555 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 556 | + }), | |
| 557 | + ); | |
| 558 | + } | |
| 559 | + })(); | |
| 560 | + }, | |
| 561 | + [clearSelection, handleMultiSelectContextMenu, handleThreadContextMenu, isSelected, threadRef], | |
| 562 | + ); | |
| 563 | + const handlePrClick = useCallback( | |
| 564 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 565 | + if (!prStatus) return; | |
| 566 | + openPrLink(event, prStatus.url); | |
| 567 | + }, | |
| 568 | + [openPrLink, prStatus], | |
| 569 | + ); | |
| 570 | + const handleRenameInputRef = useCallback( | |
| 571 | + (element: HTMLInputElement | null) => { | |
| 572 | + if (element && renamingInputRef.current !== element) { | |
| 573 | + renamingInputRef.current = element; | |
| 574 | + element.focus(); | |
| 575 | + element.select(); | |
| 576 | + } | |
| 577 | + }, | |
| 578 | + [renamingInputRef], | |
| 579 | + ); | |
| 580 | + const handleRenameInputChange = useCallback( | |
| 581 | + (event: React.ChangeEvent<HTMLInputElement>) => { | |
| 582 | + setRenamingTitle(event.target.value); | |
| 583 | + }, | |
| 584 | + [setRenamingTitle], | |
| 585 | + ); | |
| 586 | + const handleRenameInputKeyDown = useCallback( | |
| 587 | + (event: React.KeyboardEvent<HTMLInputElement>) => { | |
| 588 | + event.stopPropagation(); | |
| 589 | + if (event.key === "Enter") { | |
| 590 | + event.preventDefault(); | |
| 591 | + renamingCommittedRef.current = true; | |
| 592 | + void commitRename(threadRef, renamingTitle, thread.title); | |
| 593 | + } else if (event.key === "Escape") { | |
| 594 | + event.preventDefault(); | |
| 595 | + renamingCommittedRef.current = true; | |
| 596 | + cancelRename(); | |
| 597 | + } | |
| 598 | + }, | |
| 599 | + [cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef], | |
| 600 | + ); | |
| 601 | + const handleRenameInputBlur = useCallback(() => { | |
| 602 | + if (!renamingCommittedRef.current) { | |
| 603 | + void commitRename(threadRef, renamingTitle, thread.title); | |
| 604 | + } | |
| 605 | + }, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]); | |
| 606 | + // Keep clicks/double-clicks inside the rename input from bubbling to the row. | |
| 607 | + // Without stopping `dblclick`, double-clicking to select a word would re-fire | |
| 608 | + // the row's rename handler and reset the in-progress edit back to the title. | |
| 609 | + const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => { | |
| 610 | + event.stopPropagation(); | |
| 611 | + }, []); | |
| 612 | + const handleConfirmArchiveRef = useCallback( | |
| 613 | + (element: HTMLButtonElement | null) => { | |
| 614 | + if (element) { | |
| 615 | + confirmArchiveButtonRefs.current.set(threadKey, element); | |
| 616 | + } else { | |
| 617 | + confirmArchiveButtonRefs.current.delete(threadKey); | |
| 618 | + } | |
| 619 | + }, | |
| 620 | + [confirmArchiveButtonRefs, threadKey], | |
| 621 | + ); | |
| 622 | + const stopPropagationOnPointerDown = useCallback( | |
| 623 | + (event: React.PointerEvent<HTMLButtonElement>) => { | |
| 624 | + event.stopPropagation(); | |
| 625 | + }, | |
| 626 | + [], | |
| 627 | + ); | |
| 628 | + const handleConfirmArchiveClick = useCallback( | |
| 629 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 630 | + event.preventDefault(); | |
| 631 | + event.stopPropagation(); | |
| 632 | + clearConfirmingArchive(); | |
| 633 | + void attemptArchiveThread(threadRef); | |
| 634 | + }, | |
| 635 | + [attemptArchiveThread, clearConfirmingArchive, threadRef], | |
| 636 | + ); | |
| 637 | + const handleStartArchiveConfirmation = useCallback( | |
| 638 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 639 | + event.preventDefault(); | |
| 640 | + event.stopPropagation(); | |
| 641 | + setConfirmingArchiveThreadKey(threadKey); | |
| 642 | + requestAnimationFrame(() => { | |
| 643 | + confirmArchiveButtonRefs.current.get(threadKey)?.focus(); | |
| 644 | + }); | |
| 645 | + }, | |
| 646 | + [confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey], | |
| 647 | + ); | |
| 648 | + const handleArchiveImmediateClick = useCallback( | |
| 649 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 650 | + event.preventDefault(); | |
| 651 | + event.stopPropagation(); | |
| 652 | + void attemptArchiveThread(threadRef); | |
| 653 | + }, | |
| 654 | + [attemptArchiveThread, threadRef], | |
| 655 | + ); | |
| 656 | + const rowButtonRender = useMemo(() => <div role="button" tabIndex={0} />, []); | |
| 657 | + | |
| 658 | + return ( | |
| 659 | + <SidebarMenuSubItem | |
| 660 | + className="w-full" | |
| 661 | + data-thread-item | |
| 662 | + onMouseLeave={handleMouseLeave} | |
| 663 | + onBlurCapture={handleBlurCapture} | |
| 664 | + > | |
| 665 | + <SidebarMenuSubButton | |
| 666 | + render={rowButtonRender} | |
| 667 | + size="sm" | |
| 668 | + isActive={isActive} | |
| 669 | + data-testid={`thread-row-${thread.id}`} | |
| 670 | + className={`${resolveThreadRowClassName({ | |
| 671 | + isActive, | |
| 672 | + isSelected, | |
| 673 | + })} relative isolate`} | |
| 674 | + onClick={handleRowClick} | |
| 675 | + onDoubleClick={handleRowDoubleClick} | |
| 676 | + onKeyDown={handleRowKeyDown} | |
| 677 | + onContextMenu={handleRowContextMenu} | |
| 678 | + > | |
| 679 | + <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left"> | |
| 680 | + {prStatus && ( | |
| 681 | + <Tooltip> | |
| 682 | + <TooltipTrigger | |
| 683 | + render={ | |
| 684 | + <button | |
| 685 | + type="button" | |
| 686 | + aria-label={prStatus.tooltip} | |
| 687 | + className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`} | |
| 688 | + onClick={handlePrClick} | |
| 689 | + > | |
| 690 | + <ChangeRequestStatusIcon className="size-3" /> | |
| 691 | + </button> | |
| 692 | + } | |
| 693 | + /> | |
| 694 | + <TooltipPopup side="top"> | |
| 695 | + <PrStatusTooltipContent status={prStatus} /> | |
| 696 | + </TooltipPopup> | |
| 697 | + </Tooltip> | |
| 698 | + )} | |
| 699 | + {threadStatus && <ThreadStatusLabel status={threadStatus} />} | |
| 700 | + {renamingThreadKey === threadKey ? ( | |
| 701 | + <input | |
| 702 | + ref={handleRenameInputRef} | |
| 703 | + className="min-w-0 flex-1 truncate rounded border border-ring bg-transparent px-0.5 text-sm outline-none" | |
| 704 | + value={renamingTitle} | |
| 705 | + onChange={handleRenameInputChange} | |
| 706 | + onKeyDown={handleRenameInputKeyDown} | |
| 707 | + onBlur={handleRenameInputBlur} | |
| 708 | + onClick={handleRenameInputClick} | |
| 709 | + onDoubleClick={handleRenameInputClick} | |
| 710 | + /> | |
| 711 | + ) : ( | |
| 712 | + <Tooltip> | |
| 713 | + <TooltipTrigger | |
| 714 | + render={ | |
| 715 | + <span | |
| 716 | + className="min-w-0 flex-1 truncate text-sm" | |
| 717 | + data-testid={`thread-title-${thread.id}`} | |
| 718 | + > | |
| 719 | + {thread.title} | |
| 720 | + </span> | |
| 721 | + } | |
| 722 | + /> | |
| 723 | + <TooltipPopup side="top" className="max-w-80 whitespace-normal leading-tight"> | |
| 724 | + {thread.title} | |
| 725 | + </TooltipPopup> | |
| 726 | + </Tooltip> | |
| 727 | + )} | |
| 728 | + </div> | |
| 729 | + <div className="ml-auto flex shrink-0 items-center gap-1.5"> | |
| 730 | + {discoveredPorts.length > 0 && ( | |
| 731 | + <Tooltip> | |
| 732 | + <TooltipTrigger | |
| 733 | + render={ | |
| 734 | + <button | |
| 735 | + type="button" | |
| 736 | + aria-label={`Open localhost:${discoveredPorts[0]?.port ?? ""}`} | |
| 737 | + className="inline-flex cursor-pointer items-center justify-center text-emerald-600 outline-hidden focus-visible:ring-1 focus-visible:ring-ring dark:text-emerald-400" | |
| 738 | + onClick={handleOpenDiscoveredPort} | |
| 739 | + /> | |
| 740 | + } | |
| 741 | + > | |
| 742 | + <Globe2Icon className="size-3" /> | |
| 743 | + </TooltipTrigger> | |
| 744 | + <TooltipPopup side="top"> | |
| 745 | + Open localhost:{discoveredPorts[0]?.port} | |
| 746 | + {discoveredPorts.length > 1 ? ` (+${discoveredPorts.length - 1})` : ""} | |
| 747 | + </TooltipPopup> | |
| 748 | + </Tooltip> | |
| 749 | + )} | |
| 750 | + <ThreadWorktreeIndicator thread={thread} /> | |
| 751 | + {terminalStatus && ( | |
| 752 | + <Tooltip> | |
| 753 | + <TooltipTrigger | |
| 754 | + render={ | |
| 755 | + <span | |
| 756 | + role="img" | |
| 757 | + aria-label={terminalStatus.label} | |
| 758 | + className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`} | |
| 759 | + /> | |
| 760 | + } | |
| 761 | + > | |
| 762 | + <TerminalIcon | |
| 763 | + className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`} | |
| 764 | + /> | |
| 765 | + </TooltipTrigger> | |
| 766 | + <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup> | |
| 767 | + </Tooltip> | |
| 768 | + )} | |
| 769 | + <div | |
| 770 | + className={`flex min-w-12 justify-end ${ | |
| 771 | + isRemoteThread ? "max-sm:min-w-24" : "max-sm:min-w-20" | |
| 772 | + }`} | |
| 773 | + > | |
| 774 | + {isConfirmingArchive ? ( | |
| 775 | + <button | |
| 776 | + ref={handleConfirmArchiveRef} | |
| 777 | + type="button" | |
| 778 | + data-thread-selection-safe | |
| 779 | + data-testid={`thread-archive-confirm-${thread.id}`} | |
| 780 | + aria-label={`Confirm archive ${thread.title}`} | |
| 781 | + className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-md bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40" | |
| 782 | + onPointerDown={stopPropagationOnPointerDown} | |
| 783 | + onClick={handleConfirmArchiveClick} | |
| 784 | + > | |
| 785 | + Confirm | |
| 786 | + </button> | |
| 787 | + ) : !isThreadRunning ? ( | |
| 788 | + appSettingsConfirmThreadArchive ? ( | |
| 789 | + <div className="pointer-events-none absolute top-1/2 right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100"> | |
| 790 | + <button | |
| 791 | + type="button" | |
| 792 | + data-thread-selection-safe | |
| 793 | + data-testid={`thread-archive-${thread.id}`} | |
| 794 | + aria-label={`Archive ${thread.title}`} | |
| 795 | + className={SIDEBAR_ICON_ACTION_BUTTON_CLASS} | |
| 796 | + onPointerDown={stopPropagationOnPointerDown} | |
| 797 | + onClick={handleStartArchiveConfirmation} | |
| 798 | + > | |
| 799 | + <ArchiveIcon className="size-3.5" /> | |
| 800 | + </button> | |
| 801 | + </div> | |
| 802 | + ) : ( | |
| 803 | + <Tooltip> | |
| 804 | + <TooltipTrigger | |
| 805 | + render={ | |
| 806 | + <div className="pointer-events-none absolute top-1/2 right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100"> | |
| 807 | + <button | |
| 808 | + type="button" | |
| 809 | + data-thread-selection-safe | |
| 810 | + data-testid={`thread-archive-${thread.id}`} | |
| 811 | + aria-label={`Archive ${thread.title}`} | |
| 812 | + className={SIDEBAR_ICON_ACTION_BUTTON_CLASS} | |
| 813 | + onPointerDown={stopPropagationOnPointerDown} | |
| 814 | + onClick={handleArchiveImmediateClick} | |
| 815 | + > | |
| 816 | + <ArchiveIcon className="size-3.5" /> | |
| 817 | + </button> | |
| 818 | + </div> | |
| 819 | + } | |
| 820 | + /> | |
| 821 | + <TooltipPopup side="top">Archive</TooltipPopup> | |
| 822 | + </Tooltip> | |
| 823 | + ) | |
| 824 | + ) : null} | |
| 825 | + <span className={threadMetaClassName}> | |
| 826 | + <span className="inline-flex items-center gap-1"> | |
| 827 | + {isRemoteThread && !isDesktopLocalThread && ( | |
| 828 | + <Tooltip> | |
| 829 | + <TooltipTrigger | |
| 830 | + render={ | |
| 831 | + <span | |
| 832 | + aria-label={threadEnvironmentLabel ?? "Remote"} | |
| 833 | + className="inline-flex items-center justify-center" | |
| 834 | + /> | |
| 835 | + } | |
| 836 | + > | |
| 837 | + <CloudIcon className="size-3 text-muted-foreground/40" /> | |
| 838 | + </TooltipTrigger> | |
| 839 | + <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup> | |
| 840 | + </Tooltip> | |
| 841 | + )} | |
| 842 | + {jumpLabel ? ( | |
| 843 | + <Tooltip> | |
| 844 | + <TooltipTrigger | |
| 845 | + render={ | |
| 846 | + <span | |
| 847 | + aria-label={jumpLabel} | |
| 848 | + className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm" | |
| 849 | + /> | |
| 850 | + } | |
| 851 | + > | |
| 852 | + {jumpLabel} | |
| 853 | + </TooltipTrigger> | |
| 854 | + <TooltipPopup side="top">{jumpLabel}</TooltipPopup> | |
| 855 | + </Tooltip> | |
| 856 | + ) : ( | |
| 857 | + <span | |
| 858 | + className={`text-[10px] tabular-nums ${ | |
| 859 | + isHighlighted ? "text-foreground" : "text-secondary-label" | |
| 860 | + }`} | |
| 861 | + > | |
| 862 | + {formatRelativeTimeLabel( | |
| 863 | + thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt, | |
| 864 | + )} | |
| 865 | + </span> | |
| 866 | + )} | |
| 867 | + </span> | |
| 868 | + </span> | |
| 869 | + </div> | |
| 870 | + </div> | |
| 871 | + </SidebarMenuSubButton> | |
| 872 | + </SidebarMenuSubItem> | |
| 873 | + ); | |
| 874 | +}); | |
| 875 | + | |
| 876 | +interface SidebarProjectThreadListProps { | |
| 877 | + projectKey: string; | |
| 878 | + projectExpanded: boolean; | |
| 879 | + hasOverflowingThreads: boolean; | |
| 880 | + hiddenThreadStatus: ThreadStatusPill | null; | |
| 881 | + orderedProjectThreadKeys: readonly string[]; | |
| 882 | + renderedThreads: readonly SidebarThreadSummary[]; | |
| 883 | + showEmptyThreadState: boolean; | |
| 884 | + shouldShowThreadPanel: boolean; | |
| 885 | + isThreadListExpanded: boolean; | |
| 886 | + projectCwd: string; | |
| 887 | + activeRouteThreadKey: string | null; | |
| 888 | + threadJumpLabelByKey: ReadonlyMap<string, string>; | |
| 889 | + appSettingsConfirmThreadArchive: boolean; | |
| 890 | + renamingThreadKey: string | null; | |
| 891 | + renamingTitle: string; | |
| 892 | + setRenamingTitle: (title: string) => void; | |
| 893 | + startThreadRename: (threadKey: string, title: string) => void; | |
| 894 | + renamingInputRef: React.RefObject<HTMLInputElement | null>; | |
| 895 | + renamingCommittedRef: React.RefObject<boolean>; | |
| 896 | + confirmingArchiveThreadKey: string | null; | |
| 897 | + setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>; | |
| 898 | + confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>; | |
| 899 | + attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; | |
| 900 | + handleThreadClick: ( | |
| 901 | + event: React.MouseEvent, | |
| 902 | + threadRef: ScopedThreadRef, | |
| 903 | + orderedProjectThreadKeys: readonly string[], | |
| 904 | + ) => void; | |
| 905 | + navigateToThread: (threadRef: ScopedThreadRef) => void; | |
| 906 | + handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise<void>; | |
| 907 | + handleThreadContextMenu: ( | |
| 908 | + threadRef: ScopedThreadRef, | |
| 909 | + position: { x: number; y: number }, | |
| 910 | + ) => Promise<void>; | |
| 911 | + clearSelection: () => void; | |
| 912 | + commitRename: ( | |
| 913 | + threadRef: ScopedThreadRef, | |
| 914 | + newTitle: string, | |
| 915 | + originalTitle: string, | |
| 916 | + ) => Promise<void>; | |
| 917 | + cancelRename: () => void; | |
| 918 | + attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise<void>; | |
| 919 | + openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void; | |
| 920 | + expandThreadListForProject: (projectKey: string) => void; | |
| 921 | + collapseThreadListForProject: (projectKey: string) => void; | |
| 922 | +} | |
| 923 | + | |
| 924 | +const SidebarProjectThreadList = memo(function SidebarProjectThreadList( | |
| 925 | + props: SidebarProjectThreadListProps, | |
| 926 | +) { | |
| 927 | + const { | |
| 928 | + projectKey, | |
| 929 | + projectExpanded, | |
| 930 | + hasOverflowingThreads, | |
| 931 | + hiddenThreadStatus, | |
| 932 | + orderedProjectThreadKeys, | |
| 933 | + renderedThreads, | |
| 934 | + showEmptyThreadState, | |
| 935 | + shouldShowThreadPanel, | |
| 936 | + isThreadListExpanded, | |
| 937 | + projectCwd, | |
| 938 | + activeRouteThreadKey, | |
| 939 | + threadJumpLabelByKey, | |
| 940 | + appSettingsConfirmThreadArchive, | |
| 941 | + renamingThreadKey, | |
| 942 | + renamingTitle, | |
| 943 | + setRenamingTitle, | |
| 944 | + startThreadRename, | |
| 945 | + renamingInputRef, | |
| 946 | + renamingCommittedRef, | |
| 947 | + confirmingArchiveThreadKey, | |
| 948 | + setConfirmingArchiveThreadKey, | |
| 949 | + confirmArchiveButtonRefs, | |
| 950 | + attachThreadListAutoAnimateRef, | |
| 951 | + handleThreadClick, | |
| 952 | + navigateToThread, | |
| 953 | + handleMultiSelectContextMenu, | |
| 954 | + handleThreadContextMenu, | |
| 955 | + clearSelection, | |
| 956 | + commitRename, | |
| 957 | + cancelRename, | |
| 958 | + attemptArchiveThread, | |
| 959 | + openPrLink, | |
| 960 | + expandThreadListForProject, | |
| 961 | + collapseThreadListForProject, | |
| 962 | + } = props; | |
| 963 | + const showMoreButtonRender = useMemo(() => <button type="button" />, []); | |
| 964 | + const showLessButtonRender = useMemo(() => <button type="button" />, []); | |
| 965 | + | |
| 966 | + return ( | |
| 967 | + <SidebarMenuSub | |
| 968 | + ref={attachThreadListAutoAnimateRef} | |
| 969 | + className="mx-0.5 my-0 w-full translate-x-0 gap-0.5 overflow-hidden border-l-0 px-1 py-0 sm:mx-1 sm:px-1.5" | |
| 970 | + > | |
| 971 | + {shouldShowThreadPanel && showEmptyThreadState ? ( | |
| 972 | + <SidebarMenuSubItem className="w-full" data-thread-selection-safe> | |
| 973 | + <div | |
| 974 | + data-thread-selection-safe | |
| 975 | + className="flex h-8 w-full translate-x-0 items-center px-2 text-left text-xs text-sidebar-muted-foreground/75" | |
| 976 | + > | |
| 977 | + <span>No threads yet</span> | |
| 978 | + </div> | |
| 979 | + </SidebarMenuSubItem> | |
| 980 | + ) : null} | |
| 981 | + {shouldShowThreadPanel && | |
| 982 | + renderedThreads.map((thread) => { | |
| 983 | + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); | |
| 984 | + return ( | |
| 985 | + <SidebarThreadRow | |
| 986 | + key={threadKey} | |
| 987 | + thread={thread} | |
| 988 | + projectCwd={projectCwd} | |
| 989 | + orderedProjectThreadKeys={orderedProjectThreadKeys} | |
| 990 | + isActive={activeRouteThreadKey === threadKey} | |
| 991 | + jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null} | |
| 992 | + appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive} | |
| 993 | + renamingThreadKey={renamingThreadKey} | |
| 994 | + renamingTitle={renamingTitle} | |
| 995 | + setRenamingTitle={setRenamingTitle} | |
| 996 | + startThreadRename={startThreadRename} | |
| 997 | + renamingInputRef={renamingInputRef} | |
| 998 | + renamingCommittedRef={renamingCommittedRef} | |
| 999 | + confirmingArchiveThreadKey={confirmingArchiveThreadKey} | |
| 1000 | + setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey} | |
| 1001 | + confirmArchiveButtonRefs={confirmArchiveButtonRefs} | |
| 1002 | + handleThreadClick={handleThreadClick} | |
| 1003 | + navigateToThread={navigateToThread} | |
| 1004 | + handleMultiSelectContextMenu={handleMultiSelectContextMenu} | |
| 1005 | + handleThreadContextMenu={handleThreadContextMenu} | |
| 1006 | + clearSelection={clearSelection} | |
| 1007 | + commitRename={commitRename} | |
| 1008 | + cancelRename={cancelRename} | |
| 1009 | + attemptArchiveThread={attemptArchiveThread} | |
| 1010 | + openPrLink={openPrLink} | |
| 1011 | + /> | |
| 1012 | + ); | |
| 1013 | + })} | |
| 1014 | + | |
| 1015 | + {projectExpanded && hasOverflowingThreads && !isThreadListExpanded && ( | |
| 1016 | + <SidebarMenuSubItem className="w-full"> | |
| 1017 | + <SidebarMenuSubButton | |
| 1018 | + render={showMoreButtonRender} | |
| 1019 | + data-thread-selection-safe | |
| 1020 | + size="sm" | |
| 1021 | + className="h-8 w-full translate-x-0 justify-start px-2 text-left text-xs text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 1022 | + onClick={() => { | |
| 1023 | + expandThreadListForProject(projectKey); | |
| 1024 | + }} | |
| 1025 | + > | |
| 1026 | + <span className="flex min-w-0 flex-1 items-center gap-2"> | |
| 1027 | + {hiddenThreadStatus && <ThreadStatusLabel status={hiddenThreadStatus} compact />} | |
| 1028 | + <span>Show more</span> | |
| 1029 | + </span> | |
| 1030 | + </SidebarMenuSubButton> | |
| 1031 | + </SidebarMenuSubItem> | |
| 1032 | + )} | |
| 1033 | + {projectExpanded && hasOverflowingThreads && isThreadListExpanded && ( | |
| 1034 | + <SidebarMenuSubItem className="w-full"> | |
| 1035 | + <SidebarMenuSubButton | |
| 1036 | + render={showLessButtonRender} | |
| 1037 | + data-thread-selection-safe | |
| 1038 | + size="sm" | |
| 1039 | + className="h-8 w-full translate-x-0 justify-start px-2 text-left text-xs text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 1040 | + onClick={() => { | |
| 1041 | + collapseThreadListForProject(projectKey); | |
| 1042 | + }} | |
| 1043 | + > | |
| 1044 | + <span>Show less</span> | |
| 1045 | + </SidebarMenuSubButton> | |
| 1046 | + </SidebarMenuSubItem> | |
| 1047 | + )} | |
| 1048 | + </SidebarMenuSub> | |
| 1049 | + ); | |
| 1050 | +}); | |
| 1051 | + | |
| 1052 | +interface SidebarProjectItemProps { | |
| 1053 | + project: SidebarProjectSnapshot; | |
| 1054 | + isThreadListExpanded: boolean; | |
| 1055 | + activeRouteThreadKey: string | null; | |
| 1056 | + newThreadShortcutLabel: string | null; | |
| 1057 | + handleNewThread: ReturnType<typeof useNewThreadHandler>; | |
| 1058 | + archiveThread: ReturnType<typeof useThreadActions>["archiveThread"]; | |
| 1059 | + deleteThread: ReturnType<typeof useThreadActions>["deleteThread"]; | |
| 1060 | + threadJumpLabelByKey: ReadonlyMap<string, string>; | |
| 1061 | + attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; | |
| 1062 | + expandThreadListForProject: (projectKey: string) => void; | |
| 1063 | + collapseThreadListForProject: (projectKey: string) => void; | |
| 1064 | + dragInProgressRef: React.RefObject<boolean>; | |
| 1065 | + suppressProjectClickAfterDragRef: React.RefObject<boolean>; | |
| 1066 | + suppressProjectClickForContextMenuRef: React.RefObject<boolean>; | |
| 1067 | + isManualProjectSorting: boolean; | |
| 1068 | + dragHandleProps: SortableProjectHandleProps | null; | |
| 1069 | +} | |
| 1070 | + | |
| 1071 | +const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjectItemProps) { | |
| 1072 | + const { | |
| 1073 | + project, | |
| 1074 | + isThreadListExpanded, | |
| 1075 | + activeRouteThreadKey, | |
| 1076 | + newThreadShortcutLabel, | |
| 1077 | + handleNewThread, | |
| 1078 | + archiveThread, | |
| 1079 | + deleteThread, | |
| 1080 | + threadJumpLabelByKey, | |
| 1081 | + attachThreadListAutoAnimateRef, | |
| 1082 | + expandThreadListForProject, | |
| 1083 | + collapseThreadListForProject, | |
| 1084 | + dragInProgressRef, | |
| 1085 | + suppressProjectClickAfterDragRef, | |
| 1086 | + suppressProjectClickForContextMenuRef, | |
| 1087 | + isManualProjectSorting, | |
| 1088 | + dragHandleProps, | |
| 1089 | + } = props; | |
| 1090 | + const threadSortOrder = useClientSettings<SidebarThreadSortOrder>( | |
| 1091 | + (settings) => settings.sidebarThreadSortOrder, | |
| 1092 | + ); | |
| 1093 | + const appSettingsConfirmThreadDelete = useClientSettings<boolean>( | |
| 1094 | + (settings) => settings.confirmThreadDelete, | |
| 1095 | + ); | |
| 1096 | + const appSettingsConfirmThreadArchive = useClientSettings<boolean>( | |
| 1097 | + (settings) => settings.confirmThreadArchive, | |
| 1098 | + ); | |
| 1099 | + const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); | |
| 1100 | + const deleteProject = useAtomCommand(projectEnvironment.delete, { | |
| 1101 | + reportFailure: false, | |
| 1102 | + }); | |
| 1103 | + const updateProject = useAtomCommand(projectEnvironment.update, { | |
| 1104 | + reportFailure: false, | |
| 1105 | + }); | |
| 1106 | + const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { | |
| 1107 | + reportFailure: false, | |
| 1108 | + }); | |
| 1109 | + const updateSettings = useUpdateClientSettings(); | |
| 1110 | + const sidebarThreadPreviewCount = useClientSettings<SidebarThreadPreviewCount>( | |
| 1111 | + (settings) => settings.sidebarThreadPreviewCount, | |
| 1112 | + ); | |
| 1113 | + const router = useRouter(); | |
| 1114 | + const { isMobile, setOpenMobile } = useSidebar(); | |
| 1115 | + const markThreadUnread = useUiStateStore((state) => state.markThreadUnread); | |
| 1116 | + const setProjectExpanded = useUiStateStore((state) => state.setProjectExpanded); | |
| 1117 | + const toggleThreadSelection = useThreadSelectionStore((state) => state.toggleThread); | |
| 1118 | + const rangeSelectTo = useThreadSelectionStore((state) => state.rangeSelectTo); | |
| 1119 | + const clearSelection = useThreadSelectionStore((state) => state.clearSelection); | |
| 1120 | + const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection); | |
| 1121 | + const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor); | |
| 1122 | + const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ | |
| 1123 | + threadId: ThreadId; | |
| 1124 | + }>({ | |
| 1125 | + onCopy: (ctx) => { | |
| 1126 | + toastManager.add({ | |
| 1127 | + type: "success", | |
| 1128 | + title: "Thread ID copied", | |
| 1129 | + description: ctx.threadId, | |
| 1130 | + }); | |
| 1131 | + }, | |
| 1132 | + onError: (error) => { | |
| 1133 | + toastManager.add( | |
| 1134 | + stackedThreadToast({ | |
| 1135 | + type: "error", | |
| 1136 | + title: "Failed to copy thread ID", | |
| 1137 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1138 | + }), | |
| 1139 | + ); | |
| 1140 | + }, | |
| 1141 | + }); | |
| 1142 | + const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ | |
| 1143 | + path: string; | |
| 1144 | + }>({ | |
| 1145 | + onCopy: (ctx) => { | |
| 1146 | + toastManager.add({ | |
| 1147 | + type: "success", | |
| 1148 | + title: "Path copied", | |
| 1149 | + description: ctx.path, | |
| 1150 | + }); | |
| 1151 | + }, | |
| 1152 | + onError: (error) => { | |
| 1153 | + toastManager.add( | |
| 1154 | + stackedThreadToast({ | |
| 1155 | + type: "error", | |
| 1156 | + title: "Failed to copy path", | |
| 1157 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1158 | + }), | |
| 1159 | + ); | |
| 1160 | + }, | |
| 1161 | + }); | |
| 1162 | + const openPrLink = useOpenPrLink(); | |
| 1163 | + const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs); | |
| 1164 | + const sidebarThreadByKey = useMemo( | |
| 1165 | + () => | |
| 1166 | + new Map( | |
| 1167 | + sidebarThreads.map( | |
| 1168 | + (thread) => | |
| 1169 | + [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, | |
| 1170 | + ), | |
| 1171 | + ), | |
| 1172 | + [sidebarThreads], | |
| 1173 | + ); | |
| 1174 | + // Keep a ref so callbacks can read the latest map without appearing in | |
| 1175 | + // dependency arrays (avoids invalidating every thread-row memo on each | |
| 1176 | + // thread-list change). | |
| 1177 | + const sidebarThreadByKeyRef = useRef(sidebarThreadByKey); | |
| 1178 | + sidebarThreadByKeyRef.current = sidebarThreadByKey; | |
| 1179 | + const projectThreads = sidebarThreads; | |
| 1180 | + const projectPreferenceKeys = useMemo(() => projectExpansionPreferenceKeys(project), [project]); | |
| 1181 | + const projectExpanded = useUiStateStore((state) => | |
| 1182 | + resolveProjectExpanded(state.projectExpandedById, projectPreferenceKeys), | |
| 1183 | + ); | |
| 1184 | + const threadLastVisitedAts = useUiStateStore( | |
| 1185 | + useShallow((state) => | |
| 1186 | + projectThreads.map( | |
| 1187 | + (thread) => | |
| 1188 | + state.threadLastVisitedAtById[ | |
| 1189 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) | |
| 1190 | + ] ?? null, | |
| 1191 | + ), | |
| 1192 | + ), | |
| 1193 | + ); | |
| 1194 | + const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null); | |
| 1195 | + const [renamingTitle, setRenamingTitle] = useState(""); | |
| 1196 | + const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null); | |
| 1197 | + const [projectRenameTarget, setProjectRenameTarget] = useState<SidebarProjectGroupMember | null>( | |
| 1198 | + null, | |
| 1199 | + ); | |
| 1200 | + const [projectRenameTitle, setProjectRenameTitle] = useState(""); | |
| 1201 | + const [projectGroupingTarget, setProjectGroupingTarget] = | |
| 1202 | + useState<SidebarProjectGroupMember | null>(null); | |
| 1203 | + const [projectGroupingSelection, setProjectGroupingSelection] = useState< | |
| 1204 | + SidebarProjectGroupingMode | "inherit" | |
| 1205 | + >("inherit"); | |
| 1206 | + const renamingCommittedRef = useRef(false); | |
| 1207 | + const renamingInputRef = useRef<HTMLInputElement | null>(null); | |
| 1208 | + const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>()); | |
| 1209 | + const memberProjectByScopedKey = useMemo( | |
| 1210 | + () => | |
| 1211 | + new Map( | |
| 1212 | + project.memberProjects.map((member) => [ | |
| 1213 | + scopedProjectKey(scopeProjectRef(member.environmentId, member.id)), | |
| 1214 | + member, | |
| 1215 | + ]), | |
| 1216 | + ), | |
| 1217 | + [project.memberProjects], | |
| 1218 | + ); | |
| 1219 | + const memberThreadCountByPhysicalKey = useMemo(() => { | |
| 1220 | + const counts = new Map<string, number>( | |
| 1221 | + project.memberProjects.map((member) => [member.physicalProjectKey, 0] as const), | |
| 1222 | + ); | |
| 1223 | + for (const thread of projectThreads) { | |
| 1224 | + const member = memberProjectByScopedKey.get( | |
| 1225 | + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), | |
| 1226 | + ); | |
| 1227 | + if (!member) { | |
| 1228 | + continue; | |
| 1229 | + } | |
| 1230 | + counts.set(member.physicalProjectKey, (counts.get(member.physicalProjectKey) ?? 0) + 1); | |
| 1231 | + } | |
| 1232 | + return counts; | |
| 1233 | + }, [memberProjectByScopedKey, project.memberProjects, projectThreads]); | |
| 1234 | + | |
| 1235 | + const { projectStatus, visibleProjectThreads, orderedProjectThreadKeys } = useMemo(() => { | |
| 1236 | + const lastVisitedAtByThreadKey = new Map( | |
| 1237 | + projectThreads.map((thread, index) => [ | |
| 1238 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1239 | + threadLastVisitedAts[index] ?? null, | |
| 1240 | + ]), | |
| 1241 | + ); | |
| 1242 | + const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => { | |
| 1243 | + const lastVisitedAt = lastVisitedAtByThreadKey.get( | |
| 1244 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1245 | + ); | |
| 1246 | + return resolveThreadStatusPill({ | |
| 1247 | + thread: { | |
| 1248 | + ...thread, | |
| 1249 | + ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}), | |
| 1250 | + }, | |
| 1251 | + }); | |
| 1252 | + }; | |
| 1253 | + const visibleProjectThreads = sortThreads( | |
| 1254 | + projectThreads.filter((thread) => thread.archivedAt === null), | |
| 1255 | + threadSortOrder, | |
| 1256 | + ); | |
| 1257 | + const projectStatus = resolveProjectStatusIndicator( | |
| 1258 | + visibleProjectThreads.map((thread) => resolveProjectThreadStatus(thread)), | |
| 1259 | + ); | |
| 1260 | + return { | |
| 1261 | + orderedProjectThreadKeys: visibleProjectThreads.map((thread) => | |
| 1262 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1263 | + ), | |
| 1264 | + projectStatus, | |
| 1265 | + visibleProjectThreads, | |
| 1266 | + }; | |
| 1267 | + }, [projectThreads, threadLastVisitedAts, threadSortOrder]); | |
| 1268 | + const pinnedCollapsedThread = useMemo(() => { | |
| 1269 | + const activeThreadKey = activeRouteThreadKey ?? undefined; | |
| 1270 | + if (!activeThreadKey || projectExpanded) { | |
| 1271 | + return null; | |
| 1272 | + } | |
| 1273 | + return ( | |
| 1274 | + visibleProjectThreads.find( | |
| 1275 | + (thread) => | |
| 1276 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey, | |
| 1277 | + ) ?? null | |
| 1278 | + ); | |
| 1279 | + }, [activeRouteThreadKey, projectExpanded, visibleProjectThreads]); | |
| 1280 | + | |
| 1281 | + const { | |
| 1282 | + hasOverflowingThreads, | |
| 1283 | + hiddenThreadStatus, | |
| 1284 | + renderedThreads, | |
| 1285 | + showEmptyThreadState, | |
| 1286 | + shouldShowThreadPanel, | |
| 1287 | + } = useMemo(() => { | |
| 1288 | + const lastVisitedAtByThreadKey = new Map( | |
| 1289 | + projectThreads.map((thread, index) => [ | |
| 1290 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1291 | + threadLastVisitedAts[index] ?? null, | |
| 1292 | + ]), | |
| 1293 | + ); | |
| 1294 | + const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => { | |
| 1295 | + const lastVisitedAt = lastVisitedAtByThreadKey.get( | |
| 1296 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1297 | + ); | |
| 1298 | + return resolveThreadStatusPill({ | |
| 1299 | + thread: { | |
| 1300 | + ...thread, | |
| 1301 | + ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}), | |
| 1302 | + }, | |
| 1303 | + }); | |
| 1304 | + }; | |
| 1305 | + const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount; | |
| 1306 | + const previewThreads = | |
| 1307 | + isThreadListExpanded || !hasOverflowingThreads | |
| 1308 | + ? visibleProjectThreads | |
| 1309 | + : visibleProjectThreads.slice(0, sidebarThreadPreviewCount); | |
| 1310 | + const visibleThreadKeys = new Set( | |
| 1311 | + [...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map((thread) => | |
| 1312 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1313 | + ), | |
| 1314 | + ); | |
| 1315 | + const renderedThreads = pinnedCollapsedThread | |
| 1316 | + ? [pinnedCollapsedThread] | |
| 1317 | + : visibleProjectThreads.filter((thread) => | |
| 1318 | + visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 1319 | + ); | |
| 1320 | + const hiddenThreads = visibleProjectThreads.filter( | |
| 1321 | + (thread) => | |
| 1322 | + !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 1323 | + ); | |
| 1324 | + return { | |
| 1325 | + hasOverflowingThreads, | |
| 1326 | + hiddenThreadStatus: resolveProjectStatusIndicator( | |
| 1327 | + hiddenThreads.map((thread) => resolveProjectThreadStatus(thread)), | |
| 1328 | + ), | |
| 1329 | + renderedThreads, | |
| 1330 | + showEmptyThreadState: projectExpanded && visibleProjectThreads.length === 0, | |
| 1331 | + shouldShowThreadPanel: projectExpanded || pinnedCollapsedThread !== null, | |
| 1332 | + }; | |
| 1333 | + }, [ | |
| 1334 | + isThreadListExpanded, | |
| 1335 | + pinnedCollapsedThread, | |
| 1336 | + projectExpanded, | |
| 1337 | + projectThreads, | |
| 1338 | + sidebarThreadPreviewCount, | |
| 1339 | + threadLastVisitedAts, | |
| 1340 | + visibleProjectThreads, | |
| 1341 | + ]); | |
| 1342 | + | |
| 1343 | + const handleProjectButtonClick = useCallback( | |
| 1344 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 1345 | + if (suppressProjectClickForContextMenuRef.current) { | |
| 1346 | + suppressProjectClickForContextMenuRef.current = false; | |
| 1347 | + event.preventDefault(); | |
| 1348 | + event.stopPropagation(); | |
| 1349 | + return; | |
| 1350 | + } | |
| 1351 | + if (dragInProgressRef.current) { | |
| 1352 | + event.preventDefault(); | |
| 1353 | + event.stopPropagation(); | |
| 1354 | + return; | |
| 1355 | + } | |
| 1356 | + if (suppressProjectClickAfterDragRef.current) { | |
| 1357 | + suppressProjectClickAfterDragRef.current = false; | |
| 1358 | + event.preventDefault(); | |
| 1359 | + event.stopPropagation(); | |
| 1360 | + return; | |
| 1361 | + } | |
| 1362 | + if (useThreadSelectionStore.getState().hasSelection()) { | |
| 1363 | + clearSelection(); | |
| 1364 | + } | |
| 1365 | + setProjectExpanded(projectPreferenceKeys, !projectExpanded); | |
| 1366 | + }, | |
| 1367 | + [ | |
| 1368 | + clearSelection, | |
| 1369 | + dragInProgressRef, | |
| 1370 | + projectExpanded, | |
| 1371 | + projectPreferenceKeys, | |
| 1372 | + setProjectExpanded, | |
| 1373 | + suppressProjectClickAfterDragRef, | |
| 1374 | + suppressProjectClickForContextMenuRef, | |
| 1375 | + ], | |
| 1376 | + ); | |
| 1377 | + | |
| 1378 | + const handleProjectButtonKeyDown = useCallback( | |
| 1379 | + (event: React.KeyboardEvent<HTMLButtonElement>) => { | |
| 1380 | + if (event.key !== "Enter" && event.key !== " ") return; | |
| 1381 | + event.preventDefault(); | |
| 1382 | + if (dragInProgressRef.current) { | |
| 1383 | + return; | |
| 1384 | + } | |
| 1385 | + setProjectExpanded(projectPreferenceKeys, !projectExpanded); | |
| 1386 | + }, | |
| 1387 | + [dragInProgressRef, projectExpanded, projectPreferenceKeys, setProjectExpanded], | |
| 1388 | + ); | |
| 1389 | + | |
| 1390 | + const handleProjectButtonPointerDownCapture = useCallback( | |
| 1391 | + (event: React.PointerEvent<HTMLButtonElement>) => { | |
| 1392 | + suppressProjectClickForContextMenuRef.current = false; | |
| 1393 | + if ( | |
| 1394 | + isContextMenuPointerDown({ | |
| 1395 | + button: event.button, | |
| 1396 | + ctrlKey: event.ctrlKey, | |
| 1397 | + isMac: isMacPlatform(navigator.platform), | |
| 1398 | + }) | |
| 1399 | + ) { | |
| 1400 | + event.stopPropagation(); | |
| 1401 | + } | |
| 1402 | + | |
| 1403 | + suppressProjectClickAfterDragRef.current = false; | |
| 1404 | + }, | |
| 1405 | + [suppressProjectClickAfterDragRef, suppressProjectClickForContextMenuRef], | |
| 1406 | + ); | |
| 1407 | + | |
| 1408 | + const openProjectRenameDialog = useCallback((member: SidebarProjectGroupMember) => { | |
| 1409 | + setProjectRenameTarget(member); | |
| 1410 | + setProjectRenameTitle(member.title); | |
| 1411 | + }, []); | |
| 1412 | + | |
| 1413 | + const openProjectGroupingDialog = useCallback( | |
| 1414 | + (member: SidebarProjectGroupMember) => { | |
| 1415 | + const overrideKey = deriveProjectGroupingOverrideKey(member); | |
| 1416 | + setProjectGroupingTarget(member); | |
| 1417 | + setProjectGroupingSelection( | |
| 1418 | + projectGroupingSettings.sidebarProjectGroupingOverrides?.[overrideKey] ?? "inherit", | |
| 1419 | + ); | |
| 1420 | + }, | |
| 1421 | + [projectGroupingSettings.sidebarProjectGroupingOverrides], | |
| 1422 | + ); | |
| 1423 | + | |
| 1424 | + const removeProject = useCallback( | |
| 1425 | + async (member: SidebarProjectGroupMember, options: { force?: boolean } = {}) => { | |
| 1426 | + const memberProjectRef = scopeProjectRef(member.environmentId, member.id); | |
| 1427 | + const result = await deleteProject({ | |
| 1428 | + environmentId: member.environmentId, | |
| 1429 | + input: { | |
| 1430 | + projectId: member.id, | |
| 1431 | + ...(options.force === true ? { force: true } : {}), | |
| 1432 | + }, | |
| 1433 | + }); | |
| 1434 | + if (result._tag === "Failure") { | |
| 1435 | + return result; | |
| 1436 | + } | |
| 1437 | + const draftStore = useComposerDraftStore.getState(); | |
| 1438 | + const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef); | |
| 1439 | + if (projectDraftThread) { | |
| 1440 | + draftStore.clearDraftThread(projectDraftThread.draftId); | |
| 1441 | + } | |
| 1442 | + draftStore.clearProjectDraftThreadId(memberProjectRef); | |
| 1443 | + return result; | |
| 1444 | + }, | |
| 1445 | + [deleteProject], | |
| 1446 | + ); | |
| 1447 | + | |
| 1448 | + const handleRemoveProject = useCallback( | |
| 1449 | + async (member: SidebarProjectGroupMember) => { | |
| 1450 | + const api = readLocalApi(); | |
| 1451 | + if (!api) { | |
| 1452 | + return; | |
| 1453 | + } | |
| 1454 | + | |
| 1455 | + const memberProjectRef = scopeProjectRef(member.environmentId, member.id); | |
| 1456 | + const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0; | |
| 1457 | + if (memberThreadCount > 0) { | |
| 1458 | + const warningToastId = toastManager.add( | |
| 1459 | + stackedThreadToast({ | |
| 1460 | + type: "warning", | |
| 1461 | + title: "Project is not empty", | |
| 1462 | + description: "Delete all threads in this project before removing it.", | |
| 1463 | + actionVariant: "destructive", | |
| 1464 | + actionProps: { | |
| 1465 | + children: "Delete anyway", | |
| 1466 | + onClick: () => { | |
| 1467 | + void (async () => { | |
| 1468 | + toastManager.close(warningToastId); | |
| 1469 | + await new Promise<void>((resolve) => { | |
| 1470 | + window.setTimeout(resolve, 180); | |
| 1471 | + }); | |
| 1472 | + | |
| 1473 | + const latestProjectThreads = Array.from( | |
| 1474 | + sidebarThreadByKeyRef.current.values(), | |
| 1475 | + ).filter( | |
| 1476 | + (thread) => | |
| 1477 | + thread.environmentId === memberProjectRef.environmentId && | |
| 1478 | + thread.projectId === memberProjectRef.projectId, | |
| 1479 | + ); | |
| 1480 | + const confirmed = await api.dialogs.confirm( | |
| 1481 | + latestProjectThreads.length > 0 | |
| 1482 | + ? [ | |
| 1483 | + `Remove project "${member.title}" and delete its ${latestProjectThreads.length} thread${ | |
| 1484 | + latestProjectThreads.length === 1 ? "" : "s" | |
| 1485 | + }?`, | |
| 1486 | + `Path: ${member.workspaceRoot}`, | |
| 1487 | + ...(member.environmentLabel | |
| 1488 | + ? [`Environment: ${member.environmentLabel}`] | |
| 1489 | + : []), | |
| 1490 | + "This permanently clears conversation history for those threads.", | |
| 1491 | + "This removes only this project entry.", | |
| 1492 | + "This action cannot be undone.", | |
| 1493 | + ].join("\n") | |
| 1494 | + : [ | |
| 1495 | + `Remove project "${member.title}"?`, | |
| 1496 | + `Path: ${member.workspaceRoot}`, | |
| 1497 | + ...(member.environmentLabel | |
| 1498 | + ? [`Environment: ${member.environmentLabel}`] | |
| 1499 | + : []), | |
| 1500 | + "This removes only this project entry.", | |
| 1501 | + ].join("\n"), | |
| 1502 | + ); | |
| 1503 | + if (!confirmed) { | |
| 1504 | + return; | |
| 1505 | + } | |
| 1506 | + | |
| 1507 | + const result = await removeProject(member, { force: true }); | |
| 1508 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 1509 | + const error = squashAtomCommandFailure(result); | |
| 1510 | + toastManager.add( | |
| 1511 | + stackedThreadToast({ | |
| 1512 | + type: "error", | |
| 1513 | + title: `Failed to remove "${member.title}"`, | |
| 1514 | + description: | |
| 1515 | + error instanceof Error | |
| 1516 | + ? error.message | |
| 1517 | + : "Unknown error removing project.", | |
| 1518 | + }), | |
| 1519 | + ); | |
| 1520 | + } | |
| 1521 | + })().catch((error) => { | |
| 1522 | + const message = | |
| 1523 | + error instanceof Error ? error.message : "Unknown error removing project."; | |
| 1524 | + console.error("Failed to remove project", { | |
| 1525 | + projectId: member.id, | |
| 1526 | + environmentId: member.environmentId, | |
| 1527 | + ...safeErrorLogAttributes(error), | |
| 1528 | + }); | |
| 1529 | + toastManager.add( | |
| 1530 | + stackedThreadToast({ | |
| 1531 | + type: "error", | |
| 1532 | + title: `Failed to remove "${member.title}"`, | |
| 1533 | + description: message, | |
| 1534 | + }), | |
| 1535 | + ); | |
| 1536 | + }); | |
| 1537 | + }, | |
| 1538 | + }, | |
| 1539 | + }), | |
| 1540 | + ); | |
| 1541 | + return; | |
| 1542 | + } | |
| 1543 | + | |
| 1544 | + const message = [ | |
| 1545 | + `Remove project "${member.title}"?`, | |
| 1546 | + `Path: ${member.workspaceRoot}`, | |
| 1547 | + ...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []), | |
| 1548 | + "This removes only this project entry.", | |
| 1549 | + ].join("\n"); | |
| 1550 | + const confirmed = await api.dialogs.confirm(message); | |
| 1551 | + if (!confirmed) { | |
| 1552 | + return; | |
| 1553 | + } | |
| 1554 | + | |
| 1555 | + const result = await removeProject(member); | |
| 1556 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 1557 | + const error = squashAtomCommandFailure(result); | |
| 1558 | + const message = error instanceof Error ? error.message : "Unknown error removing project."; | |
| 1559 | + console.error("Failed to remove project", { | |
| 1560 | + projectId: member.id, | |
| 1561 | + environmentId: member.environmentId, | |
| 1562 | + ...safeErrorLogAttributes(error), | |
| 1563 | + }); | |
| 1564 | + toastManager.add( | |
| 1565 | + stackedThreadToast({ | |
| 1566 | + type: "error", | |
| 1567 | + title: `Failed to remove "${member.title}"`, | |
| 1568 | + description: message, | |
| 1569 | + }), | |
| 1570 | + ); | |
| 1571 | + } | |
| 1572 | + }, | |
| 1573 | + [memberThreadCountByPhysicalKey, removeProject], | |
| 1574 | + ); | |
| 1575 | + | |
| 1576 | + const handleProjectButtonContextMenu = useCallback( | |
| 1577 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 1578 | + event.preventDefault(); | |
| 1579 | + suppressProjectClickForContextMenuRef.current = true; | |
| 1580 | + void (async () => { | |
| 1581 | + const api = readLocalApi(); | |
| 1582 | + if (!api) return; | |
| 1583 | + | |
| 1584 | + const actionHandlers = new Map<string, () => Promise<void> | void>(); | |
| 1585 | + const makeLeaf = ( | |
| 1586 | + action: "rename" | "grouping" | "copy-path" | "delete", | |
| 1587 | + member: SidebarProjectGroupMember, | |
| 1588 | + options?: { | |
| 1589 | + destructive?: boolean; | |
| 1590 | + disabled?: boolean; | |
| 1591 | + }, | |
| 1592 | + ): ContextMenuItem<string> => { | |
| 1593 | + const id = `${action}:${member.physicalProjectKey}`; | |
| 1594 | + actionHandlers.set(id, () => { | |
| 1595 | + switch (action) { | |
| 1596 | + case "rename": | |
| 1597 | + openProjectRenameDialog(member); | |
| 1598 | + return; | |
| 1599 | + case "grouping": | |
| 1600 | + openProjectGroupingDialog(member); | |
| 1601 | + return; | |
| 1602 | + case "copy-path": | |
| 1603 | + copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot }); | |
| 1604 | + return; | |
| 1605 | + case "delete": | |
| 1606 | + return handleRemoveProject(member); | |
| 1607 | + } | |
| 1608 | + }); | |
| 1609 | + | |
| 1610 | + return { | |
| 1611 | + id, | |
| 1612 | + label: formatProjectMemberActionLabel(member, project.groupedProjectCount), | |
| 1613 | + ...(options?.destructive ? { destructive: true } : {}), | |
| 1614 | + ...(options?.disabled ? { disabled: true } : {}), | |
| 1615 | + }; | |
| 1616 | + }; | |
| 1617 | + | |
| 1618 | + const buildTargetedItem = ( | |
| 1619 | + action: "rename" | "grouping" | "copy-path" | "delete", | |
| 1620 | + label: string, | |
| 1621 | + options?: { | |
| 1622 | + destructive?: boolean; | |
| 1623 | + isDisabled?: (member: SidebarProjectGroupMember) => boolean; | |
| 1624 | + }, | |
| 1625 | + ): ContextMenuItem<string> => { | |
| 1626 | + if (project.memberProjects.length === 1) { | |
| 1627 | + const singleMember = project.memberProjects[0]!; | |
| 1628 | + return { | |
| 1629 | + ...makeLeaf(action, singleMember, { | |
| 1630 | + ...(options?.destructive ? { destructive: true } : {}), | |
| 1631 | + ...(options?.isDisabled?.(singleMember) ? { disabled: true } : {}), | |
| 1632 | + }), | |
| 1633 | + label, | |
| 1634 | + ...(action === "delete" ? { icon: "trash" } : {}), | |
| 1635 | + }; | |
| 1636 | + } | |
| 1637 | + | |
| 1638 | + return { | |
| 1639 | + id: `${action}:submenu`, | |
| 1640 | + label, | |
| 1641 | + ...(action === "delete" ? { icon: "trash" } : {}), | |
| 1642 | + children: project.memberProjects.map((member) => | |
| 1643 | + makeLeaf(action, member, { | |
| 1644 | + ...(options?.destructive ? { destructive: true } : {}), | |
| 1645 | + ...(options?.isDisabled?.(member) ? { disabled: true } : {}), | |
| 1646 | + }), | |
| 1647 | + ), | |
| 1648 | + }; | |
| 1649 | + }; | |
| 1650 | + | |
| 1651 | + const clicked = await api.contextMenu.show( | |
| 1652 | + [ | |
| 1653 | + buildTargetedItem("rename", "Rename"), | |
| 1654 | + buildTargetedItem("grouping", "Group into..."), | |
| 1655 | + buildTargetedItem("copy-path", "Copy Path"), | |
| 1656 | + buildTargetedItem("delete", "Remove", { | |
| 1657 | + destructive: true, | |
| 1658 | + }), | |
| 1659 | + ], | |
| 1660 | + { | |
| 1661 | + x: event.clientX, | |
| 1662 | + y: event.clientY, | |
| 1663 | + }, | |
| 1664 | + ); | |
| 1665 | + | |
| 1666 | + if (!clicked) { | |
| 1667 | + return; | |
| 1668 | + } | |
| 1669 | + | |
| 1670 | + await actionHandlers.get(clicked)?.(); | |
| 1671 | + })(); | |
| 1672 | + }, | |
| 1673 | + [ | |
| 1674 | + copyPathToClipboard, | |
| 1675 | + handleRemoveProject, | |
| 1676 | + openProjectGroupingDialog, | |
| 1677 | + openProjectRenameDialog, | |
| 1678 | + project.groupedProjectCount, | |
| 1679 | + project.memberProjects, | |
| 1680 | + suppressProjectClickForContextMenuRef, | |
| 1681 | + ], | |
| 1682 | + ); | |
| 1683 | + | |
| 1684 | + const navigateToThread = useCallback( | |
| 1685 | + (threadRef: ScopedThreadRef) => { | |
| 1686 | + if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { | |
| 1687 | + clearSelection(); | |
| 1688 | + } | |
| 1689 | + setSelectionAnchor(scopedThreadKey(threadRef)); | |
| 1690 | + if (isMobile) { | |
| 1691 | + setOpenMobile(false); | |
| 1692 | + } | |
| 1693 | + void router.navigate({ | |
| 1694 | + to: "/$environmentId/$threadId", | |
| 1695 | + params: buildThreadRouteParams(threadRef), | |
| 1696 | + }); | |
| 1697 | + }, | |
| 1698 | + [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor], | |
| 1699 | + ); | |
| 1700 | + | |
| 1701 | + const handleThreadClick = useCallback( | |
| 1702 | + ( | |
| 1703 | + event: React.MouseEvent, | |
| 1704 | + threadRef: ScopedThreadRef, | |
| 1705 | + orderedProjectThreadKeys: readonly string[], | |
| 1706 | + ) => { | |
| 1707 | + const isMac = isMacPlatform(navigator.platform); | |
| 1708 | + const isModClick = isMac ? event.metaKey : event.ctrlKey; | |
| 1709 | + const isShiftClick = event.shiftKey; | |
| 1710 | + const threadKey = scopedThreadKey(threadRef); | |
| 1711 | + const currentSelectionCount = useThreadSelectionStore.getState().selectedThreadKeys.size; | |
| 1712 | + | |
| 1713 | + if (isModClick) { | |
| 1714 | + event.preventDefault(); | |
| 1715 | + toggleThreadSelection(threadKey); | |
| 1716 | + return; | |
| 1717 | + } | |
| 1718 | + | |
| 1719 | + if (isShiftClick) { | |
| 1720 | + event.preventDefault(); | |
| 1721 | + rangeSelectTo(threadKey, orderedProjectThreadKeys); | |
| 1722 | + return; | |
| 1723 | + } | |
| 1724 | + | |
| 1725 | + // Ignore the trailing click of a plain double-click so it doesn't navigate | |
| 1726 | + // while a double-click is starting an inline rename. Placed after the | |
| 1727 | + // modifier branches so cmd/shift selection still processes every click. | |
| 1728 | + if (isTrailingDoubleClick(event.detail)) { | |
| 1729 | + return; | |
| 1730 | + } | |
| 1731 | + | |
| 1732 | + if (currentSelectionCount > 0) { | |
| 1733 | + clearSelection(); | |
| 1734 | + } | |
| 1735 | + setSelectionAnchor(threadKey); | |
| 1736 | + if (isMobile) { | |
| 1737 | + setOpenMobile(false); | |
| 1738 | + } | |
| 1739 | + void router.navigate({ | |
| 1740 | + to: "/$environmentId/$threadId", | |
| 1741 | + params: buildThreadRouteParams(threadRef), | |
| 1742 | + }); | |
| 1743 | + }, | |
| 1744 | + [ | |
| 1745 | + clearSelection, | |
| 1746 | + isMobile, | |
| 1747 | + rangeSelectTo, | |
| 1748 | + router, | |
| 1749 | + setOpenMobile, | |
| 1750 | + setSelectionAnchor, | |
| 1751 | + toggleThreadSelection, | |
| 1752 | + ], | |
| 1753 | + ); | |
| 1754 | + | |
| 1755 | + const handleMultiSelectContextMenu = useCallback( | |
| 1756 | + async (position: { x: number; y: number }) => { | |
| 1757 | + const api = readLocalApi(); | |
| 1758 | + if (!api) return; | |
| 1759 | + const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys]; | |
| 1760 | + if (threadKeys.length === 0) return; | |
| 1761 | + const count = threadKeys.length; | |
| 1762 | + const selectedThreadEntries = threadKeys.flatMap((threadKey) => { | |
| 1763 | + const threadRef = parseScopedThreadKey(threadKey); | |
| 1764 | + const thread = threadRef ? readThreadShell(threadRef) : null; | |
| 1765 | + return threadRef && thread ? [{ threadKey, threadRef, thread }] : []; | |
| 1766 | + }); | |
| 1767 | + const hasRunningThread = selectedThreadEntries.some( | |
| 1768 | + ({ thread }) => thread.session?.status === "running" && thread.session.activeTurnId != null, | |
| 1769 | + ); | |
| 1770 | + | |
| 1771 | + const clicked = await api.contextMenu.show( | |
| 1772 | + buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }), | |
| 1773 | + position, | |
| 1774 | + ); | |
| 1775 | + | |
| 1776 | + if (clicked === "mark-unread") { | |
| 1777 | + for (const { threadKey, thread } of selectedThreadEntries) { | |
| 1778 | + markThreadUnread(threadKey, thread.latestTurn?.completedAt); | |
| 1779 | + } | |
| 1780 | + clearSelection(); | |
| 1781 | + return; | |
| 1782 | + } | |
| 1783 | + | |
| 1784 | + if (clicked === "archive") { | |
| 1785 | + if (appSettingsConfirmThreadArchive) { | |
| 1786 | + const confirmed = await api.dialogs.confirm( | |
| 1787 | + `Archive ${count} thread${count === 1 ? "" : "s"}?`, | |
| 1788 | + ); | |
| 1789 | + if (!confirmed) return; | |
| 1790 | + } | |
| 1791 | + | |
| 1792 | + const archiveOutcome = await archiveSelectedThreadEntries({ | |
| 1793 | + entries: selectedThreadEntries, | |
| 1794 | + archive: ({ threadRef }, onArchived) => archiveThread(threadRef, { onArchived }), | |
| 1795 | + }); | |
| 1796 | + for (const failure of archiveOutcome.followupFailures) { | |
| 1797 | + if (isAtomCommandInterrupted(failure)) continue; | |
| 1798 | + const error = squashAtomCommandFailure(failure); | |
| 1799 | + toastManager.add( | |
| 1800 | + stackedThreadToast({ | |
| 1801 | + type: "error", | |
| 1802 | + title: "Thread archived, but navigation failed", | |
| 1803 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1804 | + }), | |
| 1805 | + ); | |
| 1806 | + } | |
| 1807 | + if (archiveOutcome.mutationFailure) { | |
| 1808 | + removeFromSelection(archiveOutcome.archivedThreadKeys); | |
| 1809 | + if (!isAtomCommandInterrupted(archiveOutcome.mutationFailure)) { | |
| 1810 | + const error = squashAtomCommandFailure(archiveOutcome.mutationFailure); | |
| 1811 | + toastManager.add( | |
| 1812 | + stackedThreadToast({ | |
| 1813 | + type: "error", | |
| 1814 | + title: "Failed to archive threads", | |
| 1815 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1816 | + }), | |
| 1817 | + ); | |
| 1818 | + } | |
| 1819 | + return; | |
| 1820 | + } | |
| 1821 | + removeFromSelection(threadKeys); | |
| 1822 | + return; | |
| 1823 | + } | |
| 1824 | + | |
| 1825 | + if (clicked !== "delete") return; | |
| 1826 | + | |
| 1827 | + if (appSettingsConfirmThreadDelete) { | |
| 1828 | + const confirmed = await api.dialogs.confirm( | |
| 1829 | + [ | |
| 1830 | + `Delete ${count} thread${count === 1 ? "" : "s"}?`, | |
| 1831 | + "This permanently clears conversation history for these threads.", | |
| 1832 | + ].join("\n"), | |
| 1833 | + ); | |
| 1834 | + if (!confirmed) return; | |
| 1835 | + } | |
| 1836 | + | |
| 1837 | + const deletedThreadKeys = new Set(threadKeys); | |
| 1838 | + for (const { threadRef } of selectedThreadEntries) { | |
| 1839 | + const result = await deleteThread(threadRef, { | |
| 1840 | + deletedThreadKeys, | |
| 1841 | + }); | |
| 1842 | + if (result._tag === "Failure") { | |
| 1843 | + if (!isAtomCommandInterrupted(result)) { | |
| 1844 | + const error = squashAtomCommandFailure(result); | |
| 1845 | + toastManager.add( | |
| 1846 | + stackedThreadToast({ | |
| 1847 | + type: "error", | |
| 1848 | + title: "Failed to delete threads", | |
| 1849 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1850 | + }), | |
| 1851 | + ); | |
| 1852 | + } | |
| 1853 | + return; | |
| 1854 | + } | |
| 1855 | + } | |
| 1856 | + removeFromSelection(threadKeys); | |
| 1857 | + }, | |
| 1858 | + [ | |
| 1859 | + appSettingsConfirmThreadArchive, | |
| 1860 | + appSettingsConfirmThreadDelete, | |
| 1861 | + archiveThread, | |
| 1862 | + clearSelection, | |
| 1863 | + deleteThread, | |
| 1864 | + markThreadUnread, | |
| 1865 | + removeFromSelection, | |
| 1866 | + ], | |
| 1867 | + ); | |
| 1868 | + | |
| 1869 | + const createThreadForProjectMember = useCallback( | |
| 1870 | + (member: SidebarProjectGroupMember) => { | |
| 1871 | + if (isMobile) { | |
| 1872 | + setOpenMobile(false); | |
| 1873 | + } | |
| 1874 | + void (async () => { | |
| 1875 | + // No options: branch, worktree, and env mode come from the user's | |
| 1876 | + // configured defaults, never from the currently viewed thread. | |
| 1877 | + const result = await settlePromise(() => | |
| 1878 | + handleNewThread(scopeProjectRef(member.environmentId, member.id)), | |
| 1879 | + ); | |
| 1880 | + if (result._tag === "Failure") { | |
| 1881 | + const error = squashAtomCommandFailure(result); | |
| 1882 | + toastManager.add( | |
| 1883 | + stackedThreadToast({ | |
| 1884 | + type: "error", | |
| 1885 | + title: "Could not create thread", | |
| 1886 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1887 | + }), | |
| 1888 | + ); | |
| 1889 | + } | |
| 1890 | + })(); | |
| 1891 | + }, | |
| 1892 | + [handleNewThread, isMobile, setOpenMobile], | |
| 1893 | + ); | |
| 1894 | + | |
| 1895 | + const handleCreateThreadClick = useCallback( | |
| 1896 | + (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 1897 | + event.preventDefault(); | |
| 1898 | + event.stopPropagation(); | |
| 1899 | + | |
| 1900 | + if (project.memberProjects.length === 1) { | |
| 1901 | + createThreadForProjectMember(project.memberProjects[0]!); | |
| 1902 | + return; | |
| 1903 | + } | |
| 1904 | + | |
| 1905 | + void (async () => { | |
| 1906 | + const api = readLocalApi(); | |
| 1907 | + if (!api) { | |
| 1908 | + return; | |
| 1909 | + } | |
| 1910 | + const clickedResult = await settlePromise(() => | |
| 1911 | + api.contextMenu.show( | |
| 1912 | + project.memberProjects.map((member) => ({ | |
| 1913 | + id: member.physicalProjectKey, | |
| 1914 | + label: formatProjectMemberActionLabel(member, project.groupedProjectCount), | |
| 1915 | + })), | |
| 1916 | + { | |
| 1917 | + x: event.clientX, | |
| 1918 | + y: event.clientY, | |
| 1919 | + }, | |
| 1920 | + ), | |
| 1921 | + ); | |
| 1922 | + if (clickedResult._tag === "Failure") { | |
| 1923 | + const error = squashAtomCommandFailure(clickedResult); | |
| 1924 | + toastManager.add( | |
| 1925 | + stackedThreadToast({ | |
| 1926 | + type: "error", | |
| 1927 | + title: "Could not choose environment", | |
| 1928 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1929 | + }), | |
| 1930 | + ); | |
| 1931 | + return; | |
| 1932 | + } | |
| 1933 | + const clicked = clickedResult.value; | |
| 1934 | + if (!clicked) { | |
| 1935 | + return; | |
| 1936 | + } | |
| 1937 | + const targetMember = project.memberProjects.find( | |
| 1938 | + (member) => member.physicalProjectKey === clicked, | |
| 1939 | + ); | |
| 1940 | + if (!targetMember) { | |
| 1941 | + return; | |
| 1942 | + } | |
| 1943 | + createThreadForProjectMember(targetMember); | |
| 1944 | + })(); | |
| 1945 | + }, | |
| 1946 | + [createThreadForProjectMember, project.groupedProjectCount, project.memberProjects], | |
| 1947 | + ); | |
| 1948 | + | |
| 1949 | + const attemptArchiveThread = useCallback( | |
| 1950 | + async (threadRef: ScopedThreadRef) => { | |
| 1951 | + const result = await archiveThread(threadRef); | |
| 1952 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 1953 | + const error = squashAtomCommandFailure(result); | |
| 1954 | + toastManager.add( | |
| 1955 | + stackedThreadToast({ | |
| 1956 | + type: "error", | |
| 1957 | + title: "Failed to archive thread", | |
| 1958 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1959 | + }), | |
| 1960 | + ); | |
| 1961 | + } | |
| 1962 | + }, | |
| 1963 | + [archiveThread], | |
| 1964 | + ); | |
| 1965 | + | |
| 1966 | + const cancelRename = useCallback(() => { | |
| 1967 | + setRenamingThreadKey(null); | |
| 1968 | + renamingInputRef.current = null; | |
| 1969 | + }, []); | |
| 1970 | + | |
| 1971 | + const startThreadRename = useCallback((threadKey: string, title: string) => { | |
| 1972 | + setRenamingThreadKey(threadKey); | |
| 1973 | + setRenamingTitle(title); | |
| 1974 | + renamingCommittedRef.current = false; | |
| 1975 | + }, []); | |
| 1976 | + | |
| 1977 | + const commitRename = useCallback( | |
| 1978 | + async (threadRef: ScopedThreadRef, newTitle: string, originalTitle: string) => { | |
| 1979 | + const threadKey = scopedThreadKey(threadRef); | |
| 1980 | + const finishRename = () => { | |
| 1981 | + setRenamingThreadKey((current) => { | |
| 1982 | + if (current !== threadKey) return current; | |
| 1983 | + renamingInputRef.current = null; | |
| 1984 | + return null; | |
| 1985 | + }); | |
| 1986 | + }; | |
| 1987 | + | |
| 1988 | + const trimmed = newTitle.trim(); | |
| 1989 | + if (trimmed.length === 0) { | |
| 1990 | + toastManager.add({ | |
| 1991 | + type: "warning", | |
| 1992 | + title: "Thread title cannot be empty", | |
| 1993 | + }); | |
| 1994 | + finishRename(); | |
| 1995 | + return; | |
| 1996 | + } | |
| 1997 | + if (trimmed === originalTitle) { | |
| 1998 | + finishRename(); | |
| 1999 | + return; | |
| 2000 | + } | |
| 2001 | + const result = await updateThreadMetadata({ | |
| 2002 | + environmentId: threadRef.environmentId, | |
| 2003 | + input: { | |
| 2004 | + threadId: threadRef.threadId, | |
| 2005 | + title: trimmed, | |
| 2006 | + }, | |
| 2007 | + }); | |
| 2008 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2009 | + const error = squashAtomCommandFailure(result); | |
| 2010 | + toastManager.add( | |
| 2011 | + stackedThreadToast({ | |
| 2012 | + type: "error", | |
| 2013 | + title: "Failed to rename thread", | |
| 2014 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2015 | + }), | |
| 2016 | + ); | |
| 2017 | + } | |
| 2018 | + finishRename(); | |
| 2019 | + }, | |
| 2020 | + [updateThreadMetadata], | |
| 2021 | + ); | |
| 2022 | + | |
| 2023 | + const closeProjectRenameDialog = useCallback(() => { | |
| 2024 | + setProjectRenameTarget(null); | |
| 2025 | + setProjectRenameTitle(""); | |
| 2026 | + }, []); | |
| 2027 | + | |
| 2028 | + const submitProjectRename = useCallback(async () => { | |
| 2029 | + if (!projectRenameTarget) { | |
| 2030 | + return; | |
| 2031 | + } | |
| 2032 | + | |
| 2033 | + const trimmed = projectRenameTitle.trim(); | |
| 2034 | + if (trimmed.length === 0) { | |
| 2035 | + toastManager.add({ | |
| 2036 | + type: "warning", | |
| 2037 | + title: "Project title cannot be empty", | |
| 2038 | + }); | |
| 2039 | + return; | |
| 2040 | + } | |
| 2041 | + | |
| 2042 | + if (trimmed === projectRenameTarget.title) { | |
| 2043 | + closeProjectRenameDialog(); | |
| 2044 | + return; | |
| 2045 | + } | |
| 2046 | + | |
| 2047 | + const result = await updateProject({ | |
| 2048 | + environmentId: projectRenameTarget.environmentId, | |
| 2049 | + input: { | |
| 2050 | + projectId: projectRenameTarget.id, | |
| 2051 | + title: trimmed, | |
| 2052 | + }, | |
| 2053 | + }); | |
| 2054 | + if (result._tag === "Success") { | |
| 2055 | + closeProjectRenameDialog(); | |
| 2056 | + } else if (!isAtomCommandInterrupted(result)) { | |
| 2057 | + const error = squashAtomCommandFailure(result); | |
| 2058 | + toastManager.add( | |
| 2059 | + stackedThreadToast({ | |
| 2060 | + type: "error", | |
| 2061 | + title: "Failed to rename project", | |
| 2062 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2063 | + }), | |
| 2064 | + ); | |
| 2065 | + } | |
| 2066 | + }, [closeProjectRenameDialog, projectRenameTarget, projectRenameTitle, updateProject]); | |
| 2067 | + | |
| 2068 | + const closeProjectGroupingDialog = useCallback(() => { | |
| 2069 | + setProjectGroupingTarget(null); | |
| 2070 | + setProjectGroupingSelection("inherit"); | |
| 2071 | + }, []); | |
| 2072 | + | |
| 2073 | + const saveProjectGroupingPreference = useCallback(() => { | |
| 2074 | + if (!projectGroupingTarget) { | |
| 2075 | + return; | |
| 2076 | + } | |
| 2077 | + | |
| 2078 | + const overrideKey = deriveProjectGroupingOverrideKey(projectGroupingTarget); | |
| 2079 | + const nextOverrides = { | |
| 2080 | + ...projectGroupingSettings.sidebarProjectGroupingOverrides, | |
| 2081 | + }; | |
| 2082 | + if (projectGroupingSelection === "inherit") { | |
| 2083 | + delete nextOverrides[overrideKey]; | |
| 2084 | + } else { | |
| 2085 | + nextOverrides[overrideKey] = projectGroupingSelection; | |
| 2086 | + } | |
| 2087 | + updateSettings({ | |
| 2088 | + sidebarProjectGroupingOverrides: nextOverrides, | |
| 2089 | + }); | |
| 2090 | + closeProjectGroupingDialog(); | |
| 2091 | + }, [ | |
| 2092 | + closeProjectGroupingDialog, | |
| 2093 | + projectGroupingSelection, | |
| 2094 | + projectGroupingSettings.sidebarProjectGroupingOverrides, | |
| 2095 | + projectGroupingTarget, | |
| 2096 | + updateSettings, | |
| 2097 | + ]); | |
| 2098 | + | |
| 2099 | + const handleThreadContextMenu = useCallback( | |
| 2100 | + async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { | |
| 2101 | + const api = readLocalApi(); | |
| 2102 | + if (!api) return; | |
| 2103 | + const threadKey = scopedThreadKey(threadRef); | |
| 2104 | + const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null; | |
| 2105 | + if (!thread) return; | |
| 2106 | + const threadProject = memberProjectByScopedKey.get( | |
| 2107 | + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), | |
| 2108 | + ); | |
| 2109 | + const threadWorkspacePath = | |
| 2110 | + thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null; | |
| 2111 | + const clicked = await api.contextMenu.show( | |
| 2112 | + [ | |
| 2113 | + ...(thread.branch | |
| 2114 | + ? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }] | |
| 2115 | + : []), | |
| 2116 | + { id: "rename", label: "Rename thread" }, | |
| 2117 | + { id: "mark-unread", label: "Mark unread" }, | |
| 2118 | + { id: "copy-path", label: "Copy Path" }, | |
| 2119 | + { id: "copy-thread-id", label: "Copy Thread ID" }, | |
| 2120 | + { id: "delete", label: "Delete", destructive: true, icon: "trash" }, | |
| 2121 | + ], | |
| 2122 | + position, | |
| 2123 | + ); | |
| 2124 | + | |
| 2125 | + if (clicked === "new-thread-on-branch") { | |
| 2126 | + // Explicit branch carry-over: reuse the thread's worktree when it | |
| 2127 | + // has one, otherwise its branch on the local checkout. | |
| 2128 | + const result = await settlePromise(() => | |
| 2129 | + handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), { | |
| 2130 | + branch: thread.branch, | |
| 2131 | + worktreePath: thread.worktreePath, | |
| 2132 | + envMode: thread.worktreePath ? "worktree" : "local", | |
| 2133 | + startFromOrigin: false, | |
| 2134 | + }), | |
| 2135 | + ); | |
| 2136 | + if (result._tag === "Failure") { | |
| 2137 | + const error = squashAtomCommandFailure(result); | |
| 2138 | + toastManager.add( | |
| 2139 | + stackedThreadToast({ | |
| 2140 | + type: "error", | |
| 2141 | + title: "Could not create thread", | |
| 2142 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2143 | + }), | |
| 2144 | + ); | |
| 2145 | + } | |
| 2146 | + return; | |
| 2147 | + } | |
| 2148 | + | |
| 2149 | + if (clicked === "rename") { | |
| 2150 | + startThreadRename(threadKey, thread.title); | |
| 2151 | + return; | |
| 2152 | + } | |
| 2153 | + | |
| 2154 | + if (clicked === "mark-unread") { | |
| 2155 | + markThreadUnread(threadKey, thread.latestTurn?.completedAt); | |
| 2156 | + return; | |
| 2157 | + } | |
| 2158 | + if (clicked === "copy-path") { | |
| 2159 | + if (!threadWorkspacePath) { | |
| 2160 | + toastManager.add( | |
| 2161 | + stackedThreadToast({ | |
| 2162 | + type: "error", | |
| 2163 | + title: "Path unavailable", | |
| 2164 | + description: "This thread does not have a workspace path to copy.", | |
| 2165 | + }), | |
| 2166 | + ); | |
| 2167 | + return; | |
| 2168 | + } | |
| 2169 | + copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); | |
| 2170 | + return; | |
| 2171 | + } | |
| 2172 | + if (clicked === "copy-thread-id") { | |
| 2173 | + copyThreadIdToClipboard(thread.id, { threadId: thread.id }); | |
| 2174 | + return; | |
| 2175 | + } | |
| 2176 | + if (clicked !== "delete") return; | |
| 2177 | + if (appSettingsConfirmThreadDelete) { | |
| 2178 | + const confirmed = await api.dialogs.confirm( | |
| 2179 | + [ | |
| 2180 | + `Delete thread "${thread.title}"?`, | |
| 2181 | + "This permanently clears conversation history for this thread.", | |
| 2182 | + ].join("\n"), | |
| 2183 | + ); | |
| 2184 | + if (!confirmed) { | |
| 2185 | + return; | |
| 2186 | + } | |
| 2187 | + } | |
| 2188 | + const result = await deleteThread(threadRef); | |
| 2189 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2190 | + const error = squashAtomCommandFailure(result); | |
| 2191 | + toastManager.add( | |
| 2192 | + stackedThreadToast({ | |
| 2193 | + type: "error", | |
| 2194 | + title: "Failed to delete thread", | |
| 2195 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2196 | + }), | |
| 2197 | + ); | |
| 2198 | + } | |
| 2199 | + }, | |
| 2200 | + [ | |
| 2201 | + appSettingsConfirmThreadDelete, | |
| 2202 | + copyPathToClipboard, | |
| 2203 | + copyThreadIdToClipboard, | |
| 2204 | + deleteThread, | |
| 2205 | + handleNewThread, | |
| 2206 | + markThreadUnread, | |
| 2207 | + memberProjectByScopedKey, | |
| 2208 | + project.workspaceRoot, | |
| 2209 | + startThreadRename, | |
| 2210 | + ], | |
| 2211 | + ); | |
| 2212 | + | |
| 2213 | + return ( | |
| 2214 | + <> | |
| 2215 | + <div className="group/project-header relative"> | |
| 2216 | + <SidebarMenuButton | |
| 2217 | + ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined} | |
| 2218 | + className={`pr-8 group-hover/project-header:bg-sidebar-row-hover group-hover/project-header:text-sidebar-foreground max-sm:pr-14 ${ | |
| 2219 | + isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "" | |
| 2220 | + }`} | |
| 2221 | + {...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})} | |
| 2222 | + {...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})} | |
| 2223 | + onPointerDownCapture={handleProjectButtonPointerDownCapture} | |
| 2224 | + onClick={handleProjectButtonClick} | |
| 2225 | + onKeyDown={handleProjectButtonKeyDown} | |
| 2226 | + onContextMenu={handleProjectButtonContextMenu} | |
| 2227 | + > | |
| 2228 | + {!projectExpanded && projectStatus ? ( | |
| 2229 | + <Tooltip> | |
| 2230 | + <TooltipTrigger | |
| 2231 | + render={ | |
| 2232 | + <span | |
| 2233 | + aria-label={projectStatus.label} | |
| 2234 | + className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`} | |
| 2235 | + /> | |
| 2236 | + } | |
| 2237 | + > | |
| 2238 | + <span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0"> | |
| 2239 | + <span | |
| 2240 | + className={`size-[9px] rounded-full ${projectStatus.dotClass} ${ | |
| 2241 | + projectStatus.pulse ? "animate-status-pulse" : "" | |
| 2242 | + }`} | |
| 2243 | + /> | |
| 2244 | + </span> | |
| 2245 | + <ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-icon-muted opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" /> | |
| 2246 | + </TooltipTrigger> | |
| 2247 | + <TooltipPopup side="top">{projectStatus.label}</TooltipPopup> | |
| 2248 | + </Tooltip> | |
| 2249 | + ) : ( | |
| 2250 | + <ChevronRightIcon | |
| 2251 | + className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${ | |
| 2252 | + projectExpanded ? "rotate-90" : "" | |
| 2253 | + }`} | |
| 2254 | + /> | |
| 2255 | + )} | |
| 2256 | + <ProjectFavicon environmentId={project.environmentId} cwd={project.workspaceRoot} /> | |
| 2257 | + <span className="flex min-w-0 flex-1 items-center gap-2"> | |
| 2258 | + <span className="truncate text-sm font-medium text-sidebar-foreground/90"> | |
| 2259 | + {project.displayName} | |
| 2260 | + </span> | |
| 2261 | + {project.groupedProjectCount > 1 ? ( | |
| 2262 | + <span className="shrink-0 text-secondary-label text-[10px]"> | |
| 2263 | + {project.groupedProjectCount} projects | |
| 2264 | + </span> | |
| 2265 | + ) : null} | |
| 2266 | + </span> | |
| 2267 | + </SidebarMenuButton> | |
| 2268 | + {/* Environment badge – visible by default, crossfades with the | |
| 2269 | + "new thread" button on hover using the same pointer-events + | |
| 2270 | + opacity pattern as the thread row archive/timestamp swap. */} | |
| 2271 | + {project.environmentPresence === "remote-only" && ( | |
| 2272 | + <Tooltip> | |
| 2273 | + <TooltipTrigger | |
| 2274 | + render={ | |
| 2275 | + <span | |
| 2276 | + aria-label={ | |
| 2277 | + project.allRemoteMembersAreDesktopLocal | |
| 2278 | + ? "Local sandbox project" | |
| 2279 | + : "Remote project" | |
| 2280 | + } | |
| 2281 | + className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center rounded-md text-icon-muted transition-opacity duration-150 max-sm:right-7 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0 max-sm:group-hover/project-header:opacity-100 max-sm:group-focus-within/project-header:opacity-100" | |
| 2282 | + /> | |
| 2283 | + } | |
| 2284 | + > | |
| 2285 | + {project.allRemoteMembersAreDesktopLocal ? ( | |
| 2286 | + <ContainerIcon className="size-3" /> | |
| 2287 | + ) : ( | |
| 2288 | + <CloudIcon className="size-3" /> | |
| 2289 | + )} | |
| 2290 | + </TooltipTrigger> | |
| 2291 | + <TooltipPopup side="top"> | |
| 2292 | + {project.allRemoteMembersAreDesktopLocal | |
| 2293 | + ? `Local sandbox: ${project.remoteEnvironmentLabels.join(", ")}` | |
| 2294 | + : `Remote environment: ${project.remoteEnvironmentLabels.join(", ")}`} | |
| 2295 | + </TooltipPopup> | |
| 2296 | + </Tooltip> | |
| 2297 | + )} | |
| 2298 | + <Tooltip> | |
| 2299 | + <TooltipTrigger | |
| 2300 | + render={ | |
| 2301 | + <div className="pointer-events-none absolute top-[calc(50%+1px)] right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/project-header:pointer-events-auto group-hover/project-header:opacity-100 group-focus-within/project-header:pointer-events-auto group-focus-within/project-header:opacity-100"> | |
| 2302 | + <button | |
| 2303 | + type="button" | |
| 2304 | + aria-label={`Create new thread in ${project.displayName}`} | |
| 2305 | + data-testid="new-thread-button" | |
| 2306 | + className={SIDEBAR_ICON_ACTION_BUTTON_CLASS} | |
| 2307 | + onClick={handleCreateThreadClick} | |
| 2308 | + > | |
| 2309 | + <SquarePenIcon className="size-3.5" /> | |
| 2310 | + </button> | |
| 2311 | + </div> | |
| 2312 | + } | |
| 2313 | + /> | |
| 2314 | + <TooltipPopup side="top"> | |
| 2315 | + {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"} | |
| 2316 | + </TooltipPopup> | |
| 2317 | + </Tooltip> | |
| 2318 | + </div> | |
| 2319 | + | |
| 2320 | + <SidebarProjectThreadList | |
| 2321 | + projectKey={project.projectKey} | |
| 2322 | + projectExpanded={projectExpanded} | |
| 2323 | + hasOverflowingThreads={hasOverflowingThreads} | |
| 2324 | + hiddenThreadStatus={hiddenThreadStatus} | |
| 2325 | + orderedProjectThreadKeys={orderedProjectThreadKeys} | |
| 2326 | + renderedThreads={renderedThreads} | |
| 2327 | + showEmptyThreadState={showEmptyThreadState} | |
| 2328 | + shouldShowThreadPanel={shouldShowThreadPanel} | |
| 2329 | + isThreadListExpanded={isThreadListExpanded} | |
| 2330 | + projectCwd={project.workspaceRoot} | |
| 2331 | + activeRouteThreadKey={activeRouteThreadKey} | |
| 2332 | + threadJumpLabelByKey={threadJumpLabelByKey} | |
| 2333 | + appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive} | |
| 2334 | + renamingThreadKey={renamingThreadKey} | |
| 2335 | + renamingTitle={renamingTitle} | |
| 2336 | + setRenamingTitle={setRenamingTitle} | |
| 2337 | + startThreadRename={startThreadRename} | |
| 2338 | + renamingInputRef={renamingInputRef} | |
| 2339 | + renamingCommittedRef={renamingCommittedRef} | |
| 2340 | + confirmingArchiveThreadKey={confirmingArchiveThreadKey} | |
| 2341 | + setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey} | |
| 2342 | + confirmArchiveButtonRefs={confirmArchiveButtonRefs} | |
| 2343 | + attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} | |
| 2344 | + handleThreadClick={handleThreadClick} | |
| 2345 | + navigateToThread={navigateToThread} | |
| 2346 | + handleMultiSelectContextMenu={handleMultiSelectContextMenu} | |
| 2347 | + handleThreadContextMenu={handleThreadContextMenu} | |
| 2348 | + clearSelection={clearSelection} | |
| 2349 | + commitRename={commitRename} | |
| 2350 | + cancelRename={cancelRename} | |
| 2351 | + attemptArchiveThread={attemptArchiveThread} | |
| 2352 | + openPrLink={openPrLink} | |
| 2353 | + expandThreadListForProject={expandThreadListForProject} | |
| 2354 | + collapseThreadListForProject={collapseThreadListForProject} | |
| 2355 | + /> | |
| 2356 | + | |
| 2357 | + <Dialog | |
| 2358 | + open={projectRenameTarget !== null} | |
| 2359 | + onOpenChange={(open) => { | |
| 2360 | + if (!open) { | |
| 2361 | + closeProjectRenameDialog(); | |
| 2362 | + } | |
| 2363 | + }} | |
| 2364 | + > | |
| 2365 | + <DialogPopup className="max-w-lg"> | |
| 2366 | + <DialogHeader> | |
| 2367 | + <DialogTitle>Rename project</DialogTitle> | |
| 2368 | + <DialogDescription> | |
| 2369 | + {projectRenameTarget | |
| 2370 | + ? `Update the title for ${projectRenameTarget.workspaceRoot}.` | |
| 2371 | + : "Update the project title."} | |
| 2372 | + </DialogDescription> | |
| 2373 | + </DialogHeader> | |
| 2374 | + <DialogPanel className="space-y-4"> | |
| 2375 | + <div className="grid gap-1.5"> | |
| 2376 | + <span className="text-xs font-medium text-foreground">Project title</span> | |
| 2377 | + <Input | |
| 2378 | + aria-label="Project title" | |
| 2379 | + value={projectRenameTitle} | |
| 2380 | + onChange={(event) => setProjectRenameTitle(event.target.value)} | |
| 2381 | + onKeyDown={(event) => { | |
| 2382 | + if (event.key === "Enter") { | |
| 2383 | + event.preventDefault(); | |
| 2384 | + void submitProjectRename(); | |
| 2385 | + } | |
| 2386 | + }} | |
| 2387 | + /> | |
| 2388 | + </div> | |
| 2389 | + {projectRenameTarget?.environmentLabel ? ( | |
| 2390 | + <p className="text-xs text-muted-foreground"> | |
| 2391 | + Environment: {projectRenameTarget.environmentLabel} | |
| 2392 | + </p> | |
| 2393 | + ) : null} | |
| 2394 | + </DialogPanel> | |
| 2395 | + <DialogFooter> | |
| 2396 | + <Button variant="outline" onClick={closeProjectRenameDialog}> | |
| 2397 | + Cancel | |
| 2398 | + </Button> | |
| 2399 | + <Button onClick={() => void submitProjectRename()}>Save</Button> | |
| 2400 | + </DialogFooter> | |
| 2401 | + </DialogPopup> | |
| 2402 | + </Dialog> | |
| 2403 | + | |
| 2404 | + <Dialog | |
| 2405 | + open={projectGroupingTarget !== null} | |
| 2406 | + onOpenChange={(open) => { | |
| 2407 | + if (!open) { | |
| 2408 | + closeProjectGroupingDialog(); | |
| 2409 | + } | |
| 2410 | + }} | |
| 2411 | + > | |
| 2412 | + <DialogPopup className="max-w-lg"> | |
| 2413 | + <DialogHeader> | |
| 2414 | + <DialogTitle>Project grouping</DialogTitle> | |
| 2415 | + <DialogDescription> | |
| 2416 | + {projectGroupingTarget | |
| 2417 | + ? `Choose how ${projectGroupingTarget.workspaceRoot} should be grouped in the sidebar.` | |
| 2418 | + : "Choose how this project should be grouped in the sidebar."} | |
| 2419 | + </DialogDescription> | |
| 2420 | + </DialogHeader> | |
| 2421 | + <DialogPanel className="space-y-4"> | |
| 2422 | + <div className="grid gap-1.5"> | |
| 2423 | + <span className="text-xs font-medium text-foreground">Grouping rule</span> | |
| 2424 | + <Select | |
| 2425 | + value={projectGroupingSelection} | |
| 2426 | + onValueChange={(value) => { | |
| 2427 | + if ( | |
| 2428 | + value === "inherit" || | |
| 2429 | + value === "repository" || | |
| 2430 | + value === "repository_path" || | |
| 2431 | + value === "separate" | |
| 2432 | + ) { | |
| 2433 | + setProjectGroupingSelection(value); | |
| 2434 | + } | |
| 2435 | + }} | |
| 2436 | + > | |
| 2437 | + <SelectTrigger className="w-full" aria-label="Project grouping rule"> | |
| 2438 | + <SelectValue> | |
| 2439 | + {projectGroupingSelection === "inherit" | |
| 2440 | + ? `Use global default (${PROJECT_GROUPING_MODE_LABELS[projectGroupingSettings.sidebarProjectGroupingMode]})` | |
| 2441 | + : PROJECT_GROUPING_MODE_LABELS[projectGroupingSelection]} | |
| 2442 | + </SelectValue> | |
| 2443 | + </SelectTrigger> | |
| 2444 | + <SelectPopup align="end" alignItemWithTrigger={false}> | |
| 2445 | + <SelectItem hideIndicator value="inherit"> | |
| 2446 | + Use global default | |
| 2447 | + </SelectItem> | |
| 2448 | + <SelectItem hideIndicator value="repository"> | |
| 2449 | + {PROJECT_GROUPING_MODE_LABELS.repository} | |
| 2450 | + </SelectItem> | |
| 2451 | + <SelectItem hideIndicator value="repository_path"> | |
| 2452 | + {PROJECT_GROUPING_MODE_LABELS.repository_path} | |
| 2453 | + </SelectItem> | |
| 2454 | + <SelectItem hideIndicator value="separate"> | |
| 2455 | + {PROJECT_GROUPING_MODE_LABELS.separate} | |
| 2456 | + </SelectItem> | |
| 2457 | + </SelectPopup> | |
| 2458 | + </Select> | |
| 2459 | + </div> | |
| 2460 | + <p className="text-xs text-muted-foreground"> | |
| 2461 | + {projectGroupingSelection === "inherit" | |
| 2462 | + ? projectGroupingModeDescription(projectGroupingSettings.sidebarProjectGroupingMode) | |
| 2463 | + : projectGroupingModeDescription(projectGroupingSelection)} | |
| 2464 | + </p> | |
| 2465 | + </DialogPanel> | |
| 2466 | + <DialogFooter> | |
| 2467 | + <Button variant="outline" onClick={closeProjectGroupingDialog}> | |
| 2468 | + Cancel | |
| 2469 | + </Button> | |
| 2470 | + <Button onClick={saveProjectGroupingPreference}>Save</Button> | |
| 2471 | + </DialogFooter> | |
| 2472 | + </DialogPopup> | |
| 2473 | + </Dialog> | |
| 2474 | + </> | |
| 2475 | + ); | |
| 2476 | +}); | |
| 2477 | + | |
| 2478 | +const SidebarProjectListRow = memo(function SidebarProjectListRow(props: SidebarProjectItemProps) { | |
| 2479 | + return ( | |
| 2480 | + <SidebarMenuItem className="rounded-md"> | |
| 2481 | + <SidebarProjectItem {...props} /> | |
| 2482 | + </SidebarMenuItem> | |
| 2483 | + ); | |
| 2484 | +}); | |
| 2485 | + | |
| 2486 | +function LocalSecondaryStatus() { | |
| 2487 | + const { environments } = useEnvironments(); | |
| 2488 | + // The desktop reports which local secondary backends (e.g. the WSL backend) | |
| 2489 | + // exist; the hook polls because the bridge has no change event. A backend that | |
| 2490 | + // is still cold-booting has no httpBaseUrl yet and isn't in the catalog, so we | |
| 2491 | + // surface "Connecting" straight from the bootstrap list and clear it once the | |
| 2492 | + // matching environment reports a connected phase. | |
| 2493 | + const secondaries = useDesktopLocalBootstraps(); | |
| 2494 | + | |
| 2495 | + // Connected desktop-local environments keyed by their backend URL so we can | |
| 2496 | + // match a bootstrap (which only knows the URL) to its connection phase. | |
| 2497 | + const localEnvByUrl = useMemo(() => { | |
| 2498 | + const map = new Map<string, { phase: string; error: string | null }>(); | |
| 2499 | + for (const environment of environments) { | |
| 2500 | + if ( | |
| 2501 | + isDesktopLocalConnectionTarget(environment.entry.target) && | |
| 2502 | + environment.displayUrl !== null | |
| 2503 | + ) { | |
| 2504 | + map.set(environment.displayUrl, { | |
| 2505 | + phase: environment.connection.phase, | |
| 2506 | + error: environment.connection.error, | |
| 2507 | + }); | |
| 2508 | + } | |
| 2509 | + } | |
| 2510 | + return map; | |
| 2511 | + }, [environments]); | |
| 2512 | + | |
| 2513 | + const connecting: string[] = []; | |
| 2514 | + const failed: Array<{ label: string; error: string | null }> = []; | |
| 2515 | + for (const bootstrap of secondaries) { | |
| 2516 | + const env = | |
| 2517 | + bootstrap.httpBaseUrl !== null ? localEnvByUrl.get(bootstrap.httpBaseUrl) : undefined; | |
| 2518 | + if (env?.phase === "connected") { | |
| 2519 | + continue; | |
| 2520 | + } | |
| 2521 | + if (env?.phase === "error") { | |
| 2522 | + failed.push({ label: bootstrap.label, error: env.error }); | |
| 2523 | + continue; | |
| 2524 | + } | |
| 2525 | + connecting.push(bootstrap.label); | |
| 2526 | + } | |
| 2527 | + | |
| 2528 | + if (connecting.length === 0 && failed.length === 0) { | |
| 2529 | + return null; | |
| 2530 | + } | |
| 2531 | + | |
| 2532 | + return ( | |
| 2533 | + <SidebarGroup className="px-2 pt-2 pb-0"> | |
| 2534 | + {connecting.length > 0 ? ( | |
| 2535 | + <Alert | |
| 2536 | + variant="default" | |
| 2537 | + className="rounded-2xl border-border/40 bg-accent/40 text-muted-foreground" | |
| 2538 | + > | |
| 2539 | + <LoaderIcon className="animate-spin" /> | |
| 2540 | + <AlertTitle className="text-xs font-medium text-foreground"> | |
| 2541 | + Connecting {connecting.join(", ")} | |
| 2542 | + </AlertTitle> | |
| 2543 | + </Alert> | |
| 2544 | + ) : null} | |
| 2545 | + {failed.length > 0 ? ( | |
| 2546 | + <Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8"> | |
| 2547 | + <TriangleAlertIcon /> | |
| 2548 | + <AlertTitle>Couldn't connect {failed.map((entry) => entry.label).join(", ")}</AlertTitle> | |
| 2549 | + <AlertDescription> | |
| 2550 | + {failed | |
| 2551 | + .map((entry) => entry.error) | |
| 2552 | + .filter(Boolean) | |
| 2553 | + .join("; ") || "The backend didn't respond."} | |
| 2554 | + </AlertDescription> | |
| 2555 | + </Alert> | |
| 2556 | + ) : null} | |
| 2557 | + </SidebarGroup> | |
| 2558 | + ); | |
| 2559 | +} | |
| 2560 | + | |
| 2561 | +type SortableProjectHandleProps = Pick< | |
| 2562 | + ReturnType<typeof useSortable>, | |
| 2563 | + "attributes" | "listeners" | "setActivatorNodeRef" | |
| 2564 | +>; | |
| 2565 | + | |
| 2566 | +function ProjectSortMenu({ | |
| 2567 | + projectSortOrder, | |
| 2568 | + threadSortOrder, | |
| 2569 | + threadPreviewCount, | |
| 2570 | + onProjectSortOrderChange, | |
| 2571 | + onThreadSortOrderChange, | |
| 2572 | + onThreadPreviewCountChange, | |
| 2573 | +}: { | |
| 2574 | + projectSortOrder: SidebarProjectSortOrder; | |
| 2575 | + threadSortOrder: SidebarThreadSortOrder; | |
| 2576 | + threadPreviewCount: SidebarThreadPreviewCount; | |
| 2577 | + onProjectSortOrderChange: (sortOrder: SidebarProjectSortOrder) => void; | |
| 2578 | + onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void; | |
| 2579 | + onThreadPreviewCountChange: (count: SidebarThreadPreviewCount) => void; | |
| 2580 | +}) { | |
| 2581 | + const handleThreadPreviewCountChange = useCallback( | |
| 2582 | + (nextValue: number | null) => { | |
| 2583 | + if (nextValue === null) { | |
| 2584 | + return; | |
| 2585 | + } | |
| 2586 | + | |
| 2587 | + const clampedValue = clampSidebarThreadPreviewCount(nextValue); | |
| 2588 | + if (clampedValue !== threadPreviewCount) { | |
| 2589 | + onThreadPreviewCountChange(clampedValue); | |
| 2590 | + } | |
| 2591 | + }, | |
| 2592 | + [onThreadPreviewCountChange, threadPreviewCount], | |
| 2593 | + ); | |
| 2594 | + | |
| 2595 | + return ( | |
| 2596 | + <Menu> | |
| 2597 | + <Tooltip> | |
| 2598 | + <TooltipTrigger | |
| 2599 | + render={ | |
| 2600 | + <MenuTrigger className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-icon-muted transition-colors hover:bg-accent hover:text-foreground" /> | |
| 2601 | + } | |
| 2602 | + > | |
| 2603 | + <ArrowUpDownIcon className="size-3.5" /> | |
| 2604 | + </TooltipTrigger> | |
| 2605 | + <TooltipPopup side="right">Sidebar options</TooltipPopup> | |
| 2606 | + </Tooltip> | |
| 2607 | + <MenuPopup align="end" side="bottom" className="min-w-52"> | |
| 2608 | + <MenuGroup> | |
| 2609 | + <div className="px-2 py-1 sm:text-xs font-medium text-muted-foreground"> | |
| 2610 | + Sort projects | |
| 2611 | + </div> | |
| 2612 | + <MenuRadioGroup | |
| 2613 | + value={projectSortOrder} | |
| 2614 | + onValueChange={(value) => { | |
| 2615 | + onProjectSortOrderChange(value as SidebarProjectSortOrder); | |
| 2616 | + }} | |
| 2617 | + > | |
| 2618 | + {(Object.entries(SIDEBAR_SORT_LABELS) as Array<[SidebarProjectSortOrder, string]>).map( | |
| 2619 | + ([value, label]) => ( | |
| 2620 | + <MenuRadioItem key={value} value={value} className="min-h-7 py-1 sm:text-xs"> | |
| 2621 | + {label} | |
| 2622 | + </MenuRadioItem> | |
| 2623 | + ), | |
| 2624 | + )} | |
| 2625 | + </MenuRadioGroup> | |
| 2626 | + </MenuGroup> | |
| 2627 | + <MenuGroup> | |
| 2628 | + <div className="px-2 pt-2 pb-1 sm:text-xs font-medium text-muted-foreground"> | |
| 2629 | + Sort threads | |
| 2630 | + </div> | |
| 2631 | + <MenuRadioGroup | |
| 2632 | + value={threadSortOrder} | |
| 2633 | + onValueChange={(value) => { | |
| 2634 | + onThreadSortOrderChange(value as SidebarThreadSortOrder); | |
| 2635 | + }} | |
| 2636 | + > | |
| 2637 | + {( | |
| 2638 | + Object.entries(SIDEBAR_THREAD_SORT_LABELS) as Array<[SidebarThreadSortOrder, string]> | |
| 2639 | + ).map(([value, label]) => ( | |
| 2640 | + <MenuRadioItem key={value} value={value} className="min-h-7 py-1 sm:text-xs"> | |
| 2641 | + {label} | |
| 2642 | + </MenuRadioItem> | |
| 2643 | + ))} | |
| 2644 | + </MenuRadioGroup> | |
| 2645 | + </MenuGroup> | |
| 2646 | + <MenuGroup> | |
| 2647 | + <div className="px-2 pt-2 pb-1 text-muted-foreground sm:text-xs font-medium"> | |
| 2648 | + Visible threads | |
| 2649 | + </div> | |
| 2650 | + <div className="px-2 py-1"> | |
| 2651 | + <NumberField | |
| 2652 | + aria-label="Visible thread count" | |
| 2653 | + className="w-28 gap-0" | |
| 2654 | + max={MAX_SIDEBAR_THREAD_PREVIEW_COUNT} | |
| 2655 | + min={MIN_SIDEBAR_THREAD_PREVIEW_COUNT} | |
| 2656 | + onValueChange={handleThreadPreviewCountChange} | |
| 2657 | + size="sm" | |
| 2658 | + step={1} | |
| 2659 | + value={threadPreviewCount} | |
| 2660 | + > | |
| 2661 | + <NumberFieldGroup className="h-7 rounded-md sm:h-6.5"> | |
| 2662 | + <NumberFieldDecrement | |
| 2663 | + aria-label="Decrease visible thread count" | |
| 2664 | + className="px-2 sm:px-2 [&_svg]:size-3.5" | |
| 2665 | + /> | |
| 2666 | + <NumberFieldInput | |
| 2667 | + aria-label="Visible thread count" | |
| 2668 | + className="h-7 w-9 grow-0 px-0 text-xs leading-7 sm:h-6.5 sm:leading-6.5" | |
| 2669 | + inputMode="numeric" | |
| 2670 | + onKeyDownCapture={(event) => { | |
| 2671 | + event.stopPropagation(); | |
| 2672 | + }} | |
| 2673 | + /> | |
| 2674 | + <NumberFieldIncrement | |
| 2675 | + aria-label="Increase visible thread count" | |
| 2676 | + className="px-2 sm:px-2 [&_svg]:size-3.5" | |
| 2677 | + /> | |
| 2678 | + </NumberFieldGroup> | |
| 2679 | + </NumberField> | |
| 2680 | + </div> | |
| 2681 | + </MenuGroup> | |
| 2682 | + </MenuPopup> | |
| 2683 | + </Menu> | |
| 2684 | + ); | |
| 2685 | +} | |
| 2686 | + | |
| 2687 | +function SortableProjectItem({ | |
| 2688 | + projectId, | |
| 2689 | + disabled = false, | |
| 2690 | + children, | |
| 2691 | +}: { | |
| 2692 | + projectId: string; | |
| 2693 | + disabled?: boolean; | |
| 2694 | + children: (handleProps: SortableProjectHandleProps) => React.ReactNode; | |
| 2695 | +}) { | |
| 2696 | + const { | |
| 2697 | + attributes, | |
| 2698 | + listeners, | |
| 2699 | + setActivatorNodeRef, | |
| 2700 | + setNodeRef, | |
| 2701 | + transform, | |
| 2702 | + transition, | |
| 2703 | + isDragging, | |
| 2704 | + isOver, | |
| 2705 | + } = useSortable({ id: projectId, disabled }); | |
| 2706 | + return ( | |
| 2707 | + <li | |
| 2708 | + ref={setNodeRef} | |
| 2709 | + style={{ | |
| 2710 | + transform: CSS.Translate.toString(transform), | |
| 2711 | + transition, | |
| 2712 | + }} | |
| 2713 | + className={`group/menu-item relative rounded-md ${ | |
| 2714 | + isDragging ? "z-20 opacity-80" : "" | |
| 2715 | + } ${isOver && !isDragging ? "ring-1 ring-primary/40" : ""}`} | |
| 2716 | + data-sidebar="menu-item" | |
| 2717 | + data-slot="sidebar-menu-item" | |
| 2718 | + > | |
| 2719 | + {children({ attributes, listeners, setActivatorNodeRef })} | |
| 2720 | + </li> | |
| 2721 | + ); | |
| 2722 | +} | |
| 2723 | + | |
| 2724 | +interface SidebarProjectsContentProps { | |
| 2725 | + showArm64IntelBuildWarning: boolean; | |
| 2726 | + arm64IntelBuildWarningDescription: string | null; | |
| 2727 | + desktopUpdateButtonAction: "download" | "install" | "none"; | |
| 2728 | + desktopUpdateButtonDisabled: boolean; | |
| 2729 | + handleDesktopUpdateButtonClick: () => void; | |
| 2730 | + projectSortOrder: SidebarProjectSortOrder; | |
| 2731 | + threadSortOrder: SidebarThreadSortOrder; | |
| 2732 | + threadPreviewCount: SidebarThreadPreviewCount; | |
| 2733 | + updateSettings: ReturnType<typeof useUpdateClientSettings>; | |
| 2734 | + openAddProject: () => void; | |
| 2735 | + isManualProjectSorting: boolean; | |
| 2736 | + projectDnDSensors: ReturnType<typeof useSensors>; | |
| 2737 | + projectCollisionDetection: CollisionDetection; | |
| 2738 | + handleProjectDragStart: (event: DragStartEvent) => void; | |
| 2739 | + handleProjectDragEnd: (event: DragEndEvent) => void; | |
| 2740 | + handleProjectDragCancel: (event: DragCancelEvent) => void; | |
| 2741 | + handleNewThread: ReturnType<typeof useNewThreadHandler>; | |
| 2742 | + archiveThread: ReturnType<typeof useThreadActions>["archiveThread"]; | |
| 2743 | + deleteThread: ReturnType<typeof useThreadActions>["deleteThread"]; | |
| 2744 | + sortedProjects: readonly SidebarProjectSnapshot[]; | |
| 2745 | + expandedThreadListsByProject: ReadonlySet<string>; | |
| 2746 | + activeRouteProjectKey: string | null; | |
| 2747 | + routeThreadKey: string | null; | |
| 2748 | + newThreadShortcutLabel: string | null; | |
| 2749 | + commandPaletteShortcutLabel: string | null; | |
| 2750 | + threadJumpLabelByKey: ReadonlyMap<string, string>; | |
| 2751 | + attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; | |
| 2752 | + expandThreadListForProject: (projectKey: string) => void; | |
| 2753 | + collapseThreadListForProject: (projectKey: string) => void; | |
| 2754 | + dragInProgressRef: React.RefObject<boolean>; | |
| 2755 | + suppressProjectClickAfterDragRef: React.RefObject<boolean>; | |
| 2756 | + suppressProjectClickForContextMenuRef: React.RefObject<boolean>; | |
| 2757 | + attachProjectListAutoAnimateRef: (node: HTMLElement | null) => void; | |
| 2758 | + projectsLength: number; | |
| 2759 | +} | |
| 2760 | + | |
| 2761 | +const SidebarProjectsContent = memo(function SidebarProjectsContent( | |
| 2762 | + props: SidebarProjectsContentProps, | |
| 2763 | +) { | |
| 2764 | + const { | |
| 2765 | + showArm64IntelBuildWarning, | |
| 2766 | + arm64IntelBuildWarningDescription, | |
| 2767 | + desktopUpdateButtonAction, | |
| 2768 | + desktopUpdateButtonDisabled, | |
| 2769 | + handleDesktopUpdateButtonClick, | |
| 2770 | + projectSortOrder, | |
| 2771 | + threadSortOrder, | |
| 2772 | + threadPreviewCount, | |
| 2773 | + updateSettings, | |
| 2774 | + openAddProject, | |
| 2775 | + isManualProjectSorting, | |
| 2776 | + projectDnDSensors, | |
| 2777 | + projectCollisionDetection, | |
| 2778 | + handleProjectDragStart, | |
| 2779 | + handleProjectDragEnd, | |
| 2780 | + handleProjectDragCancel, | |
| 2781 | + handleNewThread, | |
| 2782 | + archiveThread, | |
| 2783 | + deleteThread, | |
| 2784 | + sortedProjects, | |
| 2785 | + expandedThreadListsByProject, | |
| 2786 | + activeRouteProjectKey, | |
| 2787 | + routeThreadKey, | |
| 2788 | + newThreadShortcutLabel, | |
| 2789 | + commandPaletteShortcutLabel, | |
| 2790 | + threadJumpLabelByKey, | |
| 2791 | + attachThreadListAutoAnimateRef, | |
| 2792 | + expandThreadListForProject, | |
| 2793 | + collapseThreadListForProject, | |
| 2794 | + dragInProgressRef, | |
| 2795 | + suppressProjectClickAfterDragRef, | |
| 2796 | + suppressProjectClickForContextMenuRef, | |
| 2797 | + attachProjectListAutoAnimateRef, | |
| 2798 | + projectsLength, | |
| 2799 | + } = props; | |
| 2800 | + | |
| 2801 | + const handleProjectSortOrderChange = useCallback( | |
| 2802 | + (sortOrder: SidebarProjectSortOrder) => { | |
| 2803 | + updateSettings({ sidebarProjectSortOrder: sortOrder }); | |
| 2804 | + }, | |
| 2805 | + [updateSettings], | |
| 2806 | + ); | |
| 2807 | + const handleThreadSortOrderChange = useCallback( | |
| 2808 | + (sortOrder: SidebarThreadSortOrder) => { | |
| 2809 | + updateSettings({ sidebarThreadSortOrder: sortOrder }); | |
| 2810 | + }, | |
| 2811 | + [updateSettings], | |
| 2812 | + ); | |
| 2813 | + const handleThreadPreviewCountChange = useCallback( | |
| 2814 | + (count: SidebarThreadPreviewCount) => { | |
| 2815 | + updateSettings({ sidebarThreadPreviewCount: count }); | |
| 2816 | + }, | |
| 2817 | + [updateSettings], | |
| 2818 | + ); | |
| 2819 | + | |
| 2820 | + return ( | |
| 2821 | + <SidebarContent | |
| 2822 | + className="gap-0" | |
| 2823 | + fixedHeader={ | |
| 2824 | + // Lifted above the stage backdrop, whose fade bleeds below the | |
| 2825 | + // header and would otherwise paint across the search row's outline. | |
| 2826 | + <SidebarGroup className="relative z-[1] px-2 pt-2 pb-1"> | |
| 2827 | + <SidebarMenu> | |
| 2828 | + <SidebarMenuItem> | |
| 2829 | + <CommandDialogTrigger | |
| 2830 | + render={ | |
| 2831 | + <SidebarMenuButton | |
| 2832 | + className="focus-visible:ring-0" | |
| 2833 | + data-testid="command-palette-trigger" | |
| 2834 | + /> | |
| 2835 | + } | |
| 2836 | + > | |
| 2837 | + <SearchIcon /> | |
| 2838 | + <span className="flex-1 truncate">Search</span> | |
| 2839 | + {commandPaletteShortcutLabel ? ( | |
| 2840 | + <Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]"> | |
| 2841 | + {commandPaletteShortcutLabel} | |
| 2842 | + </Kbd> | |
| 2843 | + ) : null} | |
| 2844 | + </CommandDialogTrigger> | |
| 2845 | + </SidebarMenuItem> | |
| 2846 | + </SidebarMenu> | |
| 2847 | + </SidebarGroup> | |
| 2848 | + } | |
| 2849 | + > | |
| 2850 | + {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( | |
| 2851 | + <SidebarGroup className="px-2 pt-2 pb-0"> | |
| 2852 | + <Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8"> | |
| 2853 | + <TriangleAlertIcon /> | |
| 2854 | + <AlertTitle>Intel build on Apple Silicon</AlertTitle> | |
| 2855 | + <AlertDescription>{arm64IntelBuildWarningDescription}</AlertDescription> | |
| 2856 | + {desktopUpdateButtonAction !== "none" ? ( | |
| 2857 | + <AlertAction> | |
| 2858 | + <Button | |
| 2859 | + size="xs" | |
| 2860 | + variant="outline" | |
| 2861 | + disabled={desktopUpdateButtonDisabled} | |
| 2862 | + onClick={handleDesktopUpdateButtonClick} | |
| 2863 | + > | |
| 2864 | + {desktopUpdateButtonAction === "download" | |
| 2865 | + ? "Download ARM build" | |
| 2866 | + : "Install ARM build"} | |
| 2867 | + </Button> | |
| 2868 | + </AlertAction> | |
| 2869 | + ) : null} | |
| 2870 | + </Alert> | |
| 2871 | + </SidebarGroup> | |
| 2872 | + ) : null} | |
| 2873 | + <LocalSecondaryStatus /> | |
| 2874 | + <SidebarGroup className="px-2 py-2"> | |
| 2875 | + <div className="mb-1 flex items-center justify-between pl-2 pr-1.5"> | |
| 2876 | + <span className="text-xs font-medium text-sidebar-muted-foreground/80">Projects</span> | |
| 2877 | + <div className="flex items-center gap-1"> | |
| 2878 | + <ProjectSortMenu | |
| 2879 | + projectSortOrder={projectSortOrder} | |
| 2880 | + threadSortOrder={threadSortOrder} | |
| 2881 | + threadPreviewCount={threadPreviewCount} | |
| 2882 | + onProjectSortOrderChange={handleProjectSortOrderChange} | |
| 2883 | + onThreadSortOrderChange={handleThreadSortOrderChange} | |
| 2884 | + onThreadPreviewCountChange={handleThreadPreviewCountChange} | |
| 2885 | + /> | |
| 2886 | + <Tooltip> | |
| 2887 | + <TooltipTrigger | |
| 2888 | + render={ | |
| 2889 | + <button | |
| 2890 | + type="button" | |
| 2891 | + aria-label="Add project" | |
| 2892 | + data-testid="sidebar-add-project-trigger" | |
| 2893 | + className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-icon-muted transition-colors hover:bg-accent hover:text-foreground" | |
| 2894 | + onClick={openAddProject} | |
| 2895 | + /> | |
| 2896 | + } | |
| 2897 | + > | |
| 2898 | + <FolderPlusIcon className="size-3.5" /> | |
| 2899 | + </TooltipTrigger> | |
| 2900 | + <TooltipPopup side="right">Add project</TooltipPopup> | |
| 2901 | + </Tooltip> | |
| 2902 | + </div> | |
| 2903 | + </div> | |
| 2904 | + | |
| 2905 | + {isManualProjectSorting ? ( | |
| 2906 | + <DndContext | |
| 2907 | + sensors={projectDnDSensors} | |
| 2908 | + collisionDetection={projectCollisionDetection} | |
| 2909 | + modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]} | |
| 2910 | + onDragStart={handleProjectDragStart} | |
| 2911 | + onDragEnd={handleProjectDragEnd} | |
| 2912 | + onDragCancel={handleProjectDragCancel} | |
| 2913 | + > | |
| 2914 | + <SidebarMenu> | |
| 2915 | + <SortableContext | |
| 2916 | + items={sortedProjects.map((project) => project.projectKey)} | |
| 2917 | + strategy={verticalListSortingStrategy} | |
| 2918 | + > | |
| 2919 | + {sortedProjects.map((project) => ( | |
| 2920 | + <SortableProjectItem key={project.projectKey} projectId={project.projectKey}> | |
| 2921 | + {(dragHandleProps) => ( | |
| 2922 | + <SidebarProjectItem | |
| 2923 | + project={project} | |
| 2924 | + isThreadListExpanded={expandedThreadListsByProject.has(project.projectKey)} | |
| 2925 | + activeRouteThreadKey={ | |
| 2926 | + activeRouteProjectKey === project.projectKey ? routeThreadKey : null | |
| 2927 | + } | |
| 2928 | + newThreadShortcutLabel={newThreadShortcutLabel} | |
| 2929 | + handleNewThread={handleNewThread} | |
| 2930 | + archiveThread={archiveThread} | |
| 2931 | + deleteThread={deleteThread} | |
| 2932 | + threadJumpLabelByKey={threadJumpLabelByKey} | |
| 2933 | + attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} | |
| 2934 | + expandThreadListForProject={expandThreadListForProject} | |
| 2935 | + collapseThreadListForProject={collapseThreadListForProject} | |
| 2936 | + dragInProgressRef={dragInProgressRef} | |
| 2937 | + suppressProjectClickAfterDragRef={suppressProjectClickAfterDragRef} | |
| 2938 | + suppressProjectClickForContextMenuRef={ | |
| 2939 | + suppressProjectClickForContextMenuRef | |
| 2940 | + } | |
| 2941 | + isManualProjectSorting={isManualProjectSorting} | |
| 2942 | + dragHandleProps={dragHandleProps} | |
| 2943 | + /> | |
| 2944 | + )} | |
| 2945 | + </SortableProjectItem> | |
| 2946 | + ))} | |
| 2947 | + </SortableContext> | |
| 2948 | + </SidebarMenu> | |
| 2949 | + </DndContext> | |
| 2950 | + ) : ( | |
| 2951 | + <SidebarMenu ref={attachProjectListAutoAnimateRef}> | |
| 2952 | + {sortedProjects.map((project) => ( | |
| 2953 | + <SidebarProjectListRow | |
| 2954 | + key={project.projectKey} | |
| 2955 | + project={project} | |
| 2956 | + isThreadListExpanded={expandedThreadListsByProject.has(project.projectKey)} | |
| 2957 | + activeRouteThreadKey={ | |
| 2958 | + activeRouteProjectKey === project.projectKey ? routeThreadKey : null | |
| 2959 | + } | |
| 2960 | + newThreadShortcutLabel={newThreadShortcutLabel} | |
| 2961 | + handleNewThread={handleNewThread} | |
| 2962 | + archiveThread={archiveThread} | |
| 2963 | + deleteThread={deleteThread} | |
| 2964 | + threadJumpLabelByKey={threadJumpLabelByKey} | |
| 2965 | + attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} | |
| 2966 | + expandThreadListForProject={expandThreadListForProject} | |
| 2967 | + collapseThreadListForProject={collapseThreadListForProject} | |
| 2968 | + dragInProgressRef={dragInProgressRef} | |
| 2969 | + suppressProjectClickAfterDragRef={suppressProjectClickAfterDragRef} | |
| 2970 | + suppressProjectClickForContextMenuRef={suppressProjectClickForContextMenuRef} | |
| 2971 | + isManualProjectSorting={isManualProjectSorting} | |
| 2972 | + dragHandleProps={null} | |
| 2973 | + /> | |
| 2974 | + ))} | |
| 2975 | + </SidebarMenu> | |
| 2976 | + )} | |
| 2977 | + | |
| 2978 | + {projectsLength === 0 && ( | |
| 2979 | + <div className="px-2 pt-4 text-center text-secondary-label text-xs">No projects yet</div> | |
| 2980 | + )} | |
| 2981 | + </SidebarGroup> | |
| 2982 | + </SidebarContent> | |
| 2983 | + ); | |
| 2984 | +}); | |
| 2985 | + | |
| 2986 | +export default function LegacySidebar() { | |
| 2987 | + const projects = useProjects(); | |
| 2988 | + const sidebarThreads = useThreadShells(); | |
| 2989 | + const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); | |
| 2990 | + const projectOrder = useUiStateStore((store) => store.projectOrder); | |
| 2991 | + const reorderProjects = useUiStateStore((store) => store.reorderProjects); | |
| 2992 | + const navigate = useNavigate(); | |
| 2993 | + const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder); | |
| 2994 | + const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); | |
| 2995 | + const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); | |
| 2996 | + const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount); | |
| 2997 | + const updateSettings = useUpdateClientSettings(); | |
| 2998 | + const handleNewThread = useNewThreadHandler(); | |
| 2999 | + const { archiveThread, deleteThread } = useThreadActions(); | |
| 3000 | + const { isMobile, setOpenMobile } = useSidebar(); | |
| 3001 | + const routeTarget = useParams({ | |
| 3002 | + strict: false, | |
| 3003 | + select: (params) => resolveThreadRouteTarget(params), | |
| 3004 | + }); | |
| 3005 | + const routeDraftThread = useComposerDraftStore((store) => | |
| 3006 | + routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null, | |
| 3007 | + ); | |
| 3008 | + const routeThreadRef = useMemo( | |
| 3009 | + () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread), | |
| 3010 | + [routeDraftThread, routeTarget], | |
| 3011 | + ); | |
| 3012 | + const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; | |
| 3013 | + const routeTerminalOpen = useTerminalUiStateStore((state) => | |
| 3014 | + routeThreadRef | |
| 3015 | + ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen | |
| 3016 | + : false, | |
| 3017 | + ); | |
| 3018 | + const keybindings = useAtomValue(primaryServerKeybindingsAtom); | |
| 3019 | + const openAddProjectCommandPalette = useCallback( | |
| 3020 | + () => openCommandPalette({ open: "add-project" }), | |
| 3021 | + [], | |
| 3022 | + ); | |
| 3023 | + const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState< | |
| 3024 | + ReadonlySet<string> | |
| 3025 | + >(() => new Set()); | |
| 3026 | + const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility(); | |
| 3027 | + const dragInProgressRef = useRef(false); | |
| 3028 | + const suppressProjectClickAfterDragRef = useRef(false); | |
| 3029 | + const suppressProjectClickForContextMenuRef = useRef(false); | |
| 3030 | + const desktopUpdateState = useDesktopUpdateState(); | |
| 3031 | + const clearSelection = useThreadSelectionStore((s) => s.clearSelection); | |
| 3032 | + const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); | |
| 3033 | + const platform = navigator.platform; | |
| 3034 | + const shortcutModifiers = useShortcutModifierState(); | |
| 3035 | + const { environments } = useEnvironments(); | |
| 3036 | + const primaryEnvironmentId = usePrimaryEnvironmentId(); | |
| 3037 | + const environmentLabelById = useMemo( | |
| 3038 | + () => | |
| 3039 | + new Map( | |
| 3040 | + environments.map((environment) => [environment.environmentId, environment.label] as const), | |
| 3041 | + ), | |
| 3042 | + [environments], | |
| 3043 | + ); | |
| 3044 | + const desktopLocalEnvironmentIds = useMemo( | |
| 3045 | + () => | |
| 3046 | + new Set( | |
| 3047 | + environments | |
| 3048 | + .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target)) | |
| 3049 | + .map((environment) => environment.environmentId), | |
| 3050 | + ), | |
| 3051 | + [environments], | |
| 3052 | + ); | |
| 3053 | + const orderedProjects = useMemo(() => { | |
| 3054 | + return orderItemsByPreferredIds({ | |
| 3055 | + items: projects, | |
| 3056 | + preferredIds: projectOrder, | |
| 3057 | + getId: getProjectOrderKey, | |
| 3058 | + getPreferenceIds: (project) => [ | |
| 3059 | + getProjectOrderKey(project), | |
| 3060 | + legacyProjectCwdPreferenceKey(project.workspaceRoot), | |
| 3061 | + ], | |
| 3062 | + }); | |
| 3063 | + }, [projectOrder, projects]); | |
| 3064 | + | |
| 3065 | + // Build a mapping from physical project key → logical project key for | |
| 3066 | + // cross-environment grouping. Projects that share a repositoryIdentity | |
| 3067 | + // canonicalKey are treated as one logical project in the sidebar. | |
| 3068 | + const physicalToLogicalKey = useMemo(() => { | |
| 3069 | + return buildPhysicalToLogicalProjectKeyMap({ | |
| 3070 | + projects: orderedProjects, | |
| 3071 | + settings: projectGroupingSettings, | |
| 3072 | + primaryEnvironmentId, | |
| 3073 | + }); | |
| 3074 | + }, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]); | |
| 3075 | + const projectPhysicalKeyByScopedRef = useMemo( | |
| 3076 | + () => | |
| 3077 | + new Map( | |
| 3078 | + orderedProjects.map((project) => [ | |
| 3079 | + scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), | |
| 3080 | + derivePhysicalProjectKey(project), | |
| 3081 | + ]), | |
| 3082 | + ), | |
| 3083 | + [orderedProjects], | |
| 3084 | + ); | |
| 3085 | + | |
| 3086 | + const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(() => { | |
| 3087 | + return buildSidebarProjectSnapshots({ | |
| 3088 | + projects: orderedProjects, | |
| 3089 | + settings: projectGroupingSettings, | |
| 3090 | + primaryEnvironmentId, | |
| 3091 | + resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, | |
| 3092 | + isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId), | |
| 3093 | + }); | |
| 3094 | + }, [ | |
| 3095 | + environmentLabelById, | |
| 3096 | + desktopLocalEnvironmentIds, | |
| 3097 | + orderedProjects, | |
| 3098 | + projectGroupingSettings, | |
| 3099 | + primaryEnvironmentId, | |
| 3100 | + ]); | |
| 3101 | + | |
| 3102 | + const sidebarProjectByKey = useMemo( | |
| 3103 | + () => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)), | |
| 3104 | + [sidebarProjects], | |
| 3105 | + ); | |
| 3106 | + const sidebarThreadByKey = useMemo( | |
| 3107 | + () => | |
| 3108 | + new Map( | |
| 3109 | + sidebarThreads.map( | |
| 3110 | + (thread) => | |
| 3111 | + [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, | |
| 3112 | + ), | |
| 3113 | + ), | |
| 3114 | + [sidebarThreads], | |
| 3115 | + ); | |
| 3116 | + // Resolve the active route's project key to a logical key so it matches the | |
| 3117 | + // sidebar's grouped project entries. | |
| 3118 | + const activeRouteProjectKey = useMemo(() => { | |
| 3119 | + if (!routeThreadKey) { | |
| 3120 | + return null; | |
| 3121 | + } | |
| 3122 | + const activeThread = sidebarThreadByKey.get(routeThreadKey); | |
| 3123 | + if (!activeThread) return null; | |
| 3124 | + const physicalKey = | |
| 3125 | + projectPhysicalKeyByScopedRef.get( | |
| 3126 | + scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId)), | |
| 3127 | + ) ?? scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId)); | |
| 3128 | + return physicalToLogicalKey.get(physicalKey) ?? physicalKey; | |
| 3129 | + }, [routeThreadKey, sidebarThreadByKey, physicalToLogicalKey, projectPhysicalKeyByScopedRef]); | |
| 3130 | + | |
| 3131 | + // Group threads by logical project key so all threads from grouped projects | |
| 3132 | + // are displayed together. | |
| 3133 | + const threadsByProjectKey = useMemo(() => { | |
| 3134 | + const next = new Map<string, SidebarThreadSummary[]>(); | |
| 3135 | + for (const thread of sidebarThreads) { | |
| 3136 | + const physicalKey = | |
| 3137 | + projectPhysicalKeyByScopedRef.get( | |
| 3138 | + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), | |
| 3139 | + ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); | |
| 3140 | + const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey; | |
| 3141 | + const existing = next.get(logicalKey); | |
| 3142 | + if (existing) { | |
| 3143 | + existing.push(thread); | |
| 3144 | + } else { | |
| 3145 | + next.set(logicalKey, [thread]); | |
| 3146 | + } | |
| 3147 | + } | |
| 3148 | + return next; | |
| 3149 | + }, [sidebarThreads, physicalToLogicalKey, projectPhysicalKeyByScopedRef]); | |
| 3150 | + const getCurrentSidebarShortcutContext = useCallback( | |
| 3151 | + () => ({ | |
| 3152 | + terminalFocus: isTerminalFocused(), | |
| 3153 | + terminalOpen: routeTerminalOpen, | |
| 3154 | + modelPickerOpen: isModelPickerOpen(), | |
| 3155 | + }), | |
| 3156 | + [routeTerminalOpen], | |
| 3157 | + ); | |
| 3158 | + const newThreadShortcutLabelOptions = useMemo( | |
| 3159 | + () => ({ | |
| 3160 | + platform, | |
| 3161 | + context: { | |
| 3162 | + terminalFocus: false, | |
| 3163 | + terminalOpen: false, | |
| 3164 | + }, | |
| 3165 | + }), | |
| 3166 | + [platform], | |
| 3167 | + ); | |
| 3168 | + const newThreadShortcutLabel = | |
| 3169 | + shortcutLabelForCommand(keybindings, "chat.newLocal", newThreadShortcutLabelOptions) ?? | |
| 3170 | + shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions); | |
| 3171 | + | |
| 3172 | + const navigateToThread = useCallback( | |
| 3173 | + (threadRef: ScopedThreadRef) => { | |
| 3174 | + if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { | |
| 3175 | + clearSelection(); | |
| 3176 | + } | |
| 3177 | + setSelectionAnchor(scopedThreadKey(threadRef)); | |
| 3178 | + if (isMobile) { | |
| 3179 | + setOpenMobile(false); | |
| 3180 | + } | |
| 3181 | + void navigate({ | |
| 3182 | + to: "/$environmentId/$threadId", | |
| 3183 | + params: buildThreadRouteParams(threadRef), | |
| 3184 | + }); | |
| 3185 | + }, | |
| 3186 | + [clearSelection, isMobile, navigate, setOpenMobile, setSelectionAnchor], | |
| 3187 | + ); | |
| 3188 | + | |
| 3189 | + const projectDnDSensors = useSensors( | |
| 3190 | + useSensor(PointerSensor, { | |
| 3191 | + activationConstraint: { distance: 6 }, | |
| 3192 | + }), | |
| 3193 | + ); | |
| 3194 | + const projectCollisionDetection = useCallback<CollisionDetection>((args) => { | |
| 3195 | + const pointerCollisions = pointerWithin(args); | |
| 3196 | + if (pointerCollisions.length > 0) { | |
| 3197 | + return pointerCollisions; | |
| 3198 | + } | |
| 3199 | + | |
| 3200 | + return closestCorners(args); | |
| 3201 | + }, []); | |
| 3202 | + | |
| 3203 | + const handleProjectDragEnd = useCallback( | |
| 3204 | + (event: DragEndEvent) => { | |
| 3205 | + if (sidebarProjectSortOrder !== "manual") { | |
| 3206 | + dragInProgressRef.current = false; | |
| 3207 | + return; | |
| 3208 | + } | |
| 3209 | + dragInProgressRef.current = false; | |
| 3210 | + const { active, over } = event; | |
| 3211 | + if (!over || active.id === over.id) return; | |
| 3212 | + const activeProject = sidebarProjects.find((project) => project.projectKey === active.id); | |
| 3213 | + const overProject = sidebarProjects.find((project) => project.projectKey === over.id); | |
| 3214 | + if (!activeProject || !overProject) return; | |
| 3215 | + const activeMemberKeys = activeProject.memberProjects.map( | |
| 3216 | + (member) => member.physicalProjectKey, | |
| 3217 | + ); | |
| 3218 | + const overMemberKeys = overProject.memberProjects.map((member) => member.physicalProjectKey); | |
| 3219 | + reorderProjects(orderedProjects.map(getProjectOrderKey), activeMemberKeys, overMemberKeys); | |
| 3220 | + }, | |
| 3221 | + [orderedProjects, sidebarProjectSortOrder, reorderProjects, sidebarProjects], | |
| 3222 | + ); | |
| 3223 | + | |
| 3224 | + const handleProjectDragStart = useCallback( | |
| 3225 | + (_event: DragStartEvent) => { | |
| 3226 | + if (sidebarProjectSortOrder !== "manual") { | |
| 3227 | + return; | |
| 3228 | + } | |
| 3229 | + dragInProgressRef.current = true; | |
| 3230 | + suppressProjectClickAfterDragRef.current = true; | |
| 3231 | + }, | |
| 3232 | + [sidebarProjectSortOrder], | |
| 3233 | + ); | |
| 3234 | + | |
| 3235 | + const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => { | |
| 3236 | + dragInProgressRef.current = false; | |
| 3237 | + }, []); | |
| 3238 | + | |
| 3239 | + const animatedProjectListsRef = useRef(new WeakSet<HTMLElement>()); | |
| 3240 | + const attachProjectListAutoAnimateRef = useCallback((node: HTMLElement | null) => { | |
| 3241 | + if (!node || animatedProjectListsRef.current.has(node)) { | |
| 3242 | + return; | |
| 3243 | + } | |
| 3244 | + autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS); | |
| 3245 | + animatedProjectListsRef.current.add(node); | |
| 3246 | + }, []); | |
| 3247 | + | |
| 3248 | + const animatedThreadListsRef = useRef(new WeakSet<HTMLElement>()); | |
| 3249 | + const attachThreadListAutoAnimateRef = useCallback((node: HTMLElement | null) => { | |
| 3250 | + if (!node || animatedThreadListsRef.current.has(node)) { | |
| 3251 | + return; | |
| 3252 | + } | |
| 3253 | + autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS); | |
| 3254 | + animatedThreadListsRef.current.add(node); | |
| 3255 | + }, []); | |
| 3256 | + | |
| 3257 | + const visibleThreads = useMemo( | |
| 3258 | + () => sidebarThreads.filter((thread) => thread.archivedAt === null), | |
| 3259 | + [sidebarThreads], | |
| 3260 | + ); | |
| 3261 | + const sortedProjects = useMemo(() => { | |
| 3262 | + const sortableProjects = sidebarProjects.map((project) => ({ | |
| 3263 | + ...project, | |
| 3264 | + id: project.projectKey, | |
| 3265 | + })); | |
| 3266 | + const sortableThreads = visibleThreads.map((thread) => { | |
| 3267 | + const physicalKey = | |
| 3268 | + projectPhysicalKeyByScopedRef.get( | |
| 3269 | + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), | |
| 3270 | + ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); | |
| 3271 | + return { | |
| 3272 | + ...thread, | |
| 3273 | + projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId, | |
| 3274 | + }; | |
| 3275 | + }); | |
| 3276 | + return sortProjectsForSidebar( | |
| 3277 | + sortableProjects, | |
| 3278 | + sortableThreads, | |
| 3279 | + sidebarProjectSortOrder, | |
| 3280 | + ).flatMap((project) => { | |
| 3281 | + const resolvedProject = sidebarProjectByKey.get(project.id); | |
| 3282 | + return resolvedProject ? [resolvedProject] : []; | |
| 3283 | + }); | |
| 3284 | + }, [ | |
| 3285 | + sidebarProjectSortOrder, | |
| 3286 | + physicalToLogicalKey, | |
| 3287 | + projectPhysicalKeyByScopedRef, | |
| 3288 | + sidebarProjectByKey, | |
| 3289 | + sidebarProjects, | |
| 3290 | + visibleThreads, | |
| 3291 | + ]); | |
| 3292 | + const isManualProjectSorting = sidebarProjectSortOrder === "manual"; | |
| 3293 | + const visibleSidebarThreadKeys = useMemo( | |
| 3294 | + () => | |
| 3295 | + sortedProjects.flatMap((project) => { | |
| 3296 | + const projectThreads = sortThreads( | |
| 3297 | + (threadsByProjectKey.get(project.projectKey) ?? []).filter( | |
| 3298 | + (thread) => thread.archivedAt === null, | |
| 3299 | + ), | |
| 3300 | + sidebarThreadSortOrder, | |
| 3301 | + ); | |
| 3302 | + const projectExpanded = resolveProjectExpanded( | |
| 3303 | + projectExpandedById, | |
| 3304 | + projectExpansionPreferenceKeys(project), | |
| 3305 | + ); | |
| 3306 | + const activeThreadKey = routeThreadKey ?? undefined; | |
| 3307 | + const pinnedCollapsedThread = | |
| 3308 | + !projectExpanded && activeThreadKey | |
| 3309 | + ? (projectThreads.find( | |
| 3310 | + (thread) => | |
| 3311 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === | |
| 3312 | + activeThreadKey, | |
| 3313 | + ) ?? null) | |
| 3314 | + : null; | |
| 3315 | + const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null; | |
| 3316 | + if (!shouldShowThreadPanel) { | |
| 3317 | + return []; | |
| 3318 | + } | |
| 3319 | + const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey); | |
| 3320 | + const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount; | |
| 3321 | + const previewThreads = | |
| 3322 | + isThreadListExpanded || !hasOverflowingThreads | |
| 3323 | + ? projectThreads | |
| 3324 | + : projectThreads.slice(0, sidebarThreadPreviewCount); | |
| 3325 | + const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads; | |
| 3326 | + return renderedThreads.map((thread) => | |
| 3327 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 3328 | + ); | |
| 3329 | + }), | |
| 3330 | + [ | |
| 3331 | + sidebarThreadSortOrder, | |
| 3332 | + sidebarThreadPreviewCount, | |
| 3333 | + expandedThreadListsByProject, | |
| 3334 | + projectExpandedById, | |
| 3335 | + routeThreadKey, | |
| 3336 | + sortedProjects, | |
| 3337 | + threadsByProjectKey, | |
| 3338 | + ], | |
| 3339 | + ); | |
| 3340 | + const threadJumpCommandByKey = useMemo(() => { | |
| 3341 | + const mapping = new Map<string, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>(); | |
| 3342 | + for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) { | |
| 3343 | + const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex); | |
| 3344 | + if (!jumpCommand) { | |
| 3345 | + return mapping; | |
| 3346 | + } | |
| 3347 | + mapping.set(threadKey, jumpCommand); | |
| 3348 | + } | |
| 3349 | + | |
| 3350 | + return mapping; | |
| 3351 | + }, [visibleSidebarThreadKeys]); | |
| 3352 | + const threadJumpThreadKeys = useMemo( | |
| 3353 | + () => [...threadJumpCommandByKey.keys()], | |
| 3354 | + [threadJumpCommandByKey], | |
| 3355 | + ); | |
| 3356 | + const sidebarShortcutContext = { | |
| 3357 | + terminalFocus: false, | |
| 3358 | + terminalOpen: routeTerminalOpen, | |
| 3359 | + modelPickerOpen: isModelPickerOpen(), | |
| 3360 | + }; | |
| 3361 | + const threadJumpLabelByKey = useMemo( | |
| 3362 | + () => | |
| 3363 | + buildThreadJumpLabelMap({ | |
| 3364 | + keybindings, | |
| 3365 | + platform, | |
| 3366 | + terminalOpen: sidebarShortcutContext.terminalOpen, | |
| 3367 | + threadJumpCommandByKey, | |
| 3368 | + }), | |
| 3369 | + [keybindings, platform, sidebarShortcutContext.terminalOpen, threadJumpCommandByKey], | |
| 3370 | + ); | |
| 3371 | + const shouldShowThreadJumpHintsNow = shouldShowThreadJumpHintsForModifiers( | |
| 3372 | + shortcutModifiers, | |
| 3373 | + keybindings, | |
| 3374 | + { | |
| 3375 | + platform, | |
| 3376 | + context: sidebarShortcutContext, | |
| 3377 | + }, | |
| 3378 | + ); | |
| 3379 | + const visibleThreadJumpLabelByKey = showThreadJumpHints | |
| 3380 | + ? threadJumpLabelByKey | |
| 3381 | + : EMPTY_THREAD_JUMP_LABELS; | |
| 3382 | + const orderedSidebarThreadKeys = visibleSidebarThreadKeys; | |
| 3383 | + const prewarmedSidebarThreadKeys = useMemo( | |
| 3384 | + () => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys), | |
| 3385 | + [visibleSidebarThreadKeys], | |
| 3386 | + ); | |
| 3387 | + const prewarmedSidebarThreadRefs = useMemo( | |
| 3388 | + () => | |
| 3389 | + prewarmedSidebarThreadKeys.flatMap((threadKey) => { | |
| 3390 | + const ref = parseScopedThreadKey(threadKey); | |
| 3391 | + return ref ? [ref] : []; | |
| 3392 | + }), | |
| 3393 | + [prewarmedSidebarThreadKeys], | |
| 3394 | + ); | |
| 3395 | + | |
| 3396 | + useEffect(() => { | |
| 3397 | + updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow); | |
| 3398 | + }, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]); | |
| 3399 | + | |
| 3400 | + useEffect(() => { | |
| 3401 | + const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { | |
| 3402 | + const shortcutContext = getCurrentSidebarShortcutContext(); | |
| 3403 | + | |
| 3404 | + if (event.defaultPrevented || event.repeat) { | |
| 3405 | + return; | |
| 3406 | + } | |
| 3407 | + | |
| 3408 | + const command = resolveShortcutCommand(event, keybindings, { | |
| 3409 | + platform, | |
| 3410 | + context: shortcutContext, | |
| 3411 | + }); | |
| 3412 | + const traversalDirection = threadTraversalDirectionFromCommand(command); | |
| 3413 | + if (traversalDirection !== null) { | |
| 3414 | + const targetThreadKey = resolveAdjacentThreadId({ | |
| 3415 | + threadIds: orderedSidebarThreadKeys, | |
| 3416 | + currentThreadId: routeThreadKey, | |
| 3417 | + direction: traversalDirection, | |
| 3418 | + }); | |
| 3419 | + if (!targetThreadKey) { | |
| 3420 | + return; | |
| 3421 | + } | |
| 3422 | + const targetThread = sidebarThreadByKey.get(targetThreadKey); | |
| 3423 | + if (!targetThread) { | |
| 3424 | + return; | |
| 3425 | + } | |
| 3426 | + | |
| 3427 | + event.preventDefault(); | |
| 3428 | + event.stopPropagation(); | |
| 3429 | + navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); | |
| 3430 | + return; | |
| 3431 | + } | |
| 3432 | + | |
| 3433 | + const jumpIndex = threadJumpIndexFromCommand(command ?? ""); | |
| 3434 | + if (jumpIndex === null) { | |
| 3435 | + return; | |
| 3436 | + } | |
| 3437 | + | |
| 3438 | + const targetThreadKey = threadJumpThreadKeys[jumpIndex]; | |
| 3439 | + if (!targetThreadKey) { | |
| 3440 | + return; | |
| 3441 | + } | |
| 3442 | + const targetThread = sidebarThreadByKey.get(targetThreadKey); | |
| 3443 | + if (!targetThread) { | |
| 3444 | + return; | |
| 3445 | + } | |
| 3446 | + | |
| 3447 | + event.preventDefault(); | |
| 3448 | + event.stopPropagation(); | |
| 3449 | + navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); | |
| 3450 | + }; | |
| 3451 | + | |
| 3452 | + window.addEventListener("keydown", onWindowKeyDown); | |
| 3453 | + | |
| 3454 | + return () => { | |
| 3455 | + window.removeEventListener("keydown", onWindowKeyDown); | |
| 3456 | + }; | |
| 3457 | + }, [ | |
| 3458 | + getCurrentSidebarShortcutContext, | |
| 3459 | + keybindings, | |
| 3460 | + navigateToThread, | |
| 3461 | + orderedSidebarThreadKeys, | |
| 3462 | + platform, | |
| 3463 | + routeThreadKey, | |
| 3464 | + sidebarThreadByKey, | |
| 3465 | + threadJumpThreadKeys, | |
| 3466 | + ]); | |
| 3467 | + | |
| 3468 | + useEffect(() => { | |
| 3469 | + const onMouseDown = (event: globalThis.MouseEvent) => { | |
| 3470 | + if (!useThreadSelectionStore.getState().hasSelection()) return; | |
| 3471 | + const target = event.target instanceof HTMLElement ? event.target : null; | |
| 3472 | + if (!shouldClearThreadSelectionOnMouseDown(target)) return; | |
| 3473 | + clearSelection(); | |
| 3474 | + }; | |
| 3475 | + | |
| 3476 | + window.addEventListener("mousedown", onMouseDown); | |
| 3477 | + return () => { | |
| 3478 | + window.removeEventListener("mousedown", onMouseDown); | |
| 3479 | + }; | |
| 3480 | + }, [clearSelection]); | |
| 3481 | + | |
| 3482 | + const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState); | |
| 3483 | + const desktopUpdateButtonAction = desktopUpdateState | |
| 3484 | + ? resolveDesktopUpdateButtonAction(desktopUpdateState) | |
| 3485 | + : "none"; | |
| 3486 | + const showArm64IntelBuildWarning = | |
| 3487 | + isElectron && shouldShowArm64IntelBuildWarning(desktopUpdateState); | |
| 3488 | + const arm64IntelBuildWarningDescription = | |
| 3489 | + desktopUpdateState && showArm64IntelBuildWarning | |
| 3490 | + ? getArm64IntelBuildWarningDescription(desktopUpdateState) | |
| 3491 | + : null; | |
| 3492 | + const commandPaletteShortcutLabel = shortcutLabelForCommand( | |
| 3493 | + keybindings, | |
| 3494 | + "commandPalette.toggle", | |
| 3495 | + newThreadShortcutLabelOptions, | |
| 3496 | + ); | |
| 3497 | + const handleDesktopUpdateButtonClick = useCallback(() => { | |
| 3498 | + const bridge = window.desktopBridge; | |
| 3499 | + if (!bridge || !desktopUpdateState) return; | |
| 3500 | + if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return; | |
| 3501 | + | |
| 3502 | + if (desktopUpdateButtonAction === "download") { | |
| 3503 | + void bridge | |
| 3504 | + .downloadUpdate() | |
| 3505 | + .then((result) => { | |
| 3506 | + if (result.completed) { | |
| 3507 | + showDesktopUpdateDownloadedToast(bridge, result.state); | |
| 3508 | + } | |
| 3509 | + if (!shouldToastDesktopUpdateActionResult(result)) return; | |
| 3510 | + const actionError = getDesktopUpdateActionError(result); | |
| 3511 | + if (!actionError) return; | |
| 3512 | + toastManager.add( | |
| 3513 | + stackedThreadToast({ | |
| 3514 | + type: "error", | |
| 3515 | + title: "Could not download update", | |
| 3516 | + description: actionError, | |
| 3517 | + }), | |
| 3518 | + ); | |
| 3519 | + }) | |
| 3520 | + .catch((error) => { | |
| 3521 | + toastManager.add( | |
| 3522 | + stackedThreadToast({ | |
| 3523 | + type: "error", | |
| 3524 | + title: "Could not start update download", | |
| 3525 | + description: error instanceof Error ? error.message : "An unexpected error occurred.", | |
| 3526 | + }), | |
| 3527 | + ); | |
| 3528 | + }); | |
| 3529 | + return; | |
| 3530 | + } | |
| 3531 | + | |
| 3532 | + if (desktopUpdateButtonAction === "install") { | |
| 3533 | + const confirmed = window.confirm( | |
| 3534 | + getDesktopUpdateInstallConfirmationMessage(desktopUpdateState, navigator.platform), | |
| 3535 | + ); | |
| 3536 | + if (!confirmed) return; | |
| 3537 | + void bridge | |
| 3538 | + .installUpdate() | |
| 3539 | + .then((result) => { | |
| 3540 | + if (!shouldToastDesktopUpdateActionResult(result)) return; | |
| 3541 | + const actionError = getDesktopUpdateActionError(result); | |
| 3542 | + if (!actionError) return; | |
| 3543 | + toastManager.add( | |
| 3544 | + stackedThreadToast({ | |
| 3545 | + type: "error", | |
| 3546 | + title: "Could not install update", | |
| 3547 | + description: actionError, | |
| 3548 | + }), | |
| 3549 | + ); | |
| 3550 | + }) | |
| 3551 | + .catch((error) => { | |
| 3552 | + toastManager.add( | |
| 3553 | + stackedThreadToast({ | |
| 3554 | + type: "error", | |
| 3555 | + title: "Could not install update", | |
| 3556 | + description: error instanceof Error ? error.message : "An unexpected error occurred.", | |
| 3557 | + }), | |
| 3558 | + ); | |
| 3559 | + }); | |
| 3560 | + } | |
| 3561 | + }, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]); | |
| 3562 | + | |
| 3563 | + const expandThreadListForProject = useCallback((projectKey: string) => { | |
| 3564 | + setExpandedThreadListsByProject((current) => { | |
| 3565 | + if (current.has(projectKey)) return current; | |
| 3566 | + const next = new Set(current); | |
| 3567 | + next.add(projectKey); | |
| 3568 | + return next; | |
| 3569 | + }); | |
| 3570 | + }, []); | |
| 3571 | + | |
| 3572 | + const collapseThreadListForProject = useCallback((projectKey: string) => { | |
| 3573 | + setExpandedThreadListsByProject((current) => { | |
| 3574 | + if (!current.has(projectKey)) return current; | |
| 3575 | + const next = new Set(current); | |
| 3576 | + next.delete(projectKey); | |
| 3577 | + return next; | |
| 3578 | + }); | |
| 3579 | + }, []); | |
| 3580 | + | |
| 3581 | + return ( | |
| 3582 | + <> | |
| 3583 | + {prewarmedSidebarThreadRefs.map((threadRef) => ( | |
| 3584 | + <SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} /> | |
| 3585 | + ))} | |
| 3586 | + <SidebarChromeHeader isElectron={isElectron} /> | |
| 3587 | + | |
| 3588 | + <SidebarProjectsContent | |
| 3589 | + showArm64IntelBuildWarning={showArm64IntelBuildWarning} | |
| 3590 | + arm64IntelBuildWarningDescription={arm64IntelBuildWarningDescription} | |
| 3591 | + desktopUpdateButtonAction={desktopUpdateButtonAction} | |
| 3592 | + desktopUpdateButtonDisabled={desktopUpdateButtonDisabled} | |
| 3593 | + handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick} | |
| 3594 | + projectSortOrder={sidebarProjectSortOrder} | |
| 3595 | + threadSortOrder={sidebarThreadSortOrder} | |
| 3596 | + threadPreviewCount={sidebarThreadPreviewCount} | |
| 3597 | + updateSettings={updateSettings} | |
| 3598 | + openAddProject={openAddProjectCommandPalette} | |
| 3599 | + isManualProjectSorting={isManualProjectSorting} | |
| 3600 | + projectDnDSensors={projectDnDSensors} | |
| 3601 | + projectCollisionDetection={projectCollisionDetection} | |
| 3602 | + handleProjectDragStart={handleProjectDragStart} | |
| 3603 | + handleProjectDragEnd={handleProjectDragEnd} | |
| 3604 | + handleProjectDragCancel={handleProjectDragCancel} | |
| 3605 | + handleNewThread={handleNewThread} | |
| 3606 | + archiveThread={archiveThread} | |
| 3607 | + deleteThread={deleteThread} | |
| 3608 | + sortedProjects={sortedProjects} | |
| 3609 | + expandedThreadListsByProject={expandedThreadListsByProject} | |
| 3610 | + activeRouteProjectKey={activeRouteProjectKey} | |
| 3611 | + routeThreadKey={routeThreadKey} | |
| 3612 | + newThreadShortcutLabel={newThreadShortcutLabel} | |
| 3613 | + commandPaletteShortcutLabel={commandPaletteShortcutLabel} | |
| 3614 | + threadJumpLabelByKey={visibleThreadJumpLabelByKey} | |
| 3615 | + attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} | |
| 3616 | + expandThreadListForProject={expandThreadListForProject} | |
| 3617 | + collapseThreadListForProject={collapseThreadListForProject} | |
| 3618 | + dragInProgressRef={dragInProgressRef} | |
| 3619 | + suppressProjectClickAfterDragRef={suppressProjectClickAfterDragRef} | |
| 3620 | + suppressProjectClickForContextMenuRef={suppressProjectClickForContextMenuRef} | |
| 3621 | + attachProjectListAutoAnimateRef={attachProjectListAutoAnimateRef} | |
| 3622 | + projectsLength={projects.length} | |
| 3623 | + /> | |
| 3624 | + <SidebarChromeFooter /> | |
| 3625 | + </> | |
| 3626 | + ); | |
| 3627 | +} | |
| @@ -17,7 +17,7 @@ import { · 16 unmodified lines | ||
| 17 | 17 | resolveProjectStatusIndicator, |
| 18 | 18 | resolveSidebarStageBadgeLabel, |
| 19 | 19 | resolveThreadRowClassName, |
| 20 | − resolveSidebarV2Status, | |
| 20 | + resolveSidebarThreadStatus, | |
| 21 | 21 | resolveThreadStatusPill, |
| 22 | 22 | resolveWorkingStartedAt, |
| 23 | 23 | searchSidebarThreadsByTitle, |
| @@ -25,11 +25,11 @@ import { · 1 unmodified line | ||
| 25 | 25 | shouldNavigateAfterProjectRemoval, |
| 26 | 26 | shouldClearThreadSelectionOnMouseDown, |
| 27 | 27 | sortLogicalProjectsForSidebar, |
| 28 | − sortSettledThreadsForSidebarV2, | |
| 28 | + sortSettledThreadsForSidebar, | |
| 29 | 29 | pinOrderKeyBetween, |
| 30 | 30 | planPinnedReorder, |
| 31 | − sortPinnedThreadsForSidebarV2, | |
| 32 | − sortThreadsForSidebarV2, | |
| 31 | + sortPinnedThreadsForSidebar, | |
| 32 | + sortThreadsForSidebar, | |
| 33 | 33 | sortProjectsForSidebar, |
| 34 | 34 | sortScopedProjectsForSidebar, |
| 35 | 35 | THREAD_JUMP_HINT_SHOW_DELAY_MS, |
| @@ -627,7 +627,7 @@ describe("isContextMenuPointerDown", () => { · 591 unmodified lines | ||
| 627 | 627 | }); |
| 628 | 628 | }); |
| 629 | 629 | |
| 630 | −describe("resolveSidebarV2Status", () => { | |
| 630 | +describe("resolveSidebarThreadStatus", () => { | |
| 631 | 631 | const session = { |
| 632 | 632 | threadId: ThreadId.make("thread-1"), |
| 633 | 633 | status: "running" as const, |
| @@ -642,15 +642,17 @@ describe("resolveSidebarV2Status", () => { · 8 unmodified lines | ||
| 642 | 642 | const idle = { hasPendingApprovals: false, hasPendingUserInput: false }; |
| 643 | 643 | |
| 644 | 644 | it("prioritizes approval over a running session", () => { |
| 645 | − expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, session })).toBe( | |
| 645 | + expect(resolveSidebarThreadStatus({ ...idle, hasPendingApprovals: true, session })).toBe( | |
| 646 | 646 | "approval", |
| 647 | 647 | ); |
| 648 | 648 | }); |
| 649 | 649 | |
| 650 | 650 | it("prioritizes awaiting input over a running session, below approval", () => { |
| 651 | − expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, session })).toBe("input"); | |
| 651 | + expect(resolveSidebarThreadStatus({ ...idle, hasPendingUserInput: true, session })).toBe( | |
| 652 | + "input", | |
| 653 | + ); | |
| 652 | 654 | expect( |
| 653 | − resolveSidebarV2Status({ | |
| 655 | + resolveSidebarThreadStatus({ | |
| 654 | 656 | ...idle, |
| 655 | 657 | hasPendingApprovals: true, |
| 656 | 658 | hasPendingUserInput: true, |
| @@ -660,9 +662,9 @@ describe("resolveSidebarV2Status", () => { · 3 unmodified lines | ||
| 660 | 662 | }); |
| 661 | 663 | |
| 662 | 664 | it("reports working for running and starting sessions", () => { |
| 663 | − expect(resolveSidebarV2Status({ ...idle, session })).toBe("working"); | |
| 665 | + expect(resolveSidebarThreadStatus({ ...idle, session })).toBe("working"); | |
| 664 | 666 | expect( |
| 665 | − resolveSidebarV2Status({ | |
| 667 | + resolveSidebarThreadStatus({ | |
| 666 | 668 | ...idle, |
| 667 | 669 | session: { ...session, status: "starting" as const }, |
| 668 | 670 | }), |
| @@ -671,19 +673,19 @@ describe("resolveSidebarV2Status", () => { · 2 unmodified lines | ||
| 671 | 673 | |
| 672 | 674 | it("reports failed only while the session status is error", () => { |
| 673 | 675 | expect( |
| 674 | − resolveSidebarV2Status({ | |
| 676 | + resolveSidebarThreadStatus({ | |
| 675 | 677 | ...idle, |
| 676 | 678 | session: { ...session, status: "error" as const, lastError: "boom" }, |
| 677 | 679 | }), |
| 678 | 680 | ).toBe("failed"); |
| 679 | 681 | expect( |
| 680 | − resolveSidebarV2Status({ | |
| 682 | + resolveSidebarThreadStatus({ | |
| 681 | 683 | ...idle, |
| 682 | 684 | session: { ...session, status: "stopped" as const, lastError: "persisted" }, |
| 683 | 685 | }), |
| 684 | 686 | ).toBe("ready"); |
| 685 | 687 | expect( |
| 686 | − resolveSidebarV2Status({ | |
| 688 | + resolveSidebarThreadStatus({ | |
| 687 | 689 | ...idle, |
| 688 | 690 | session: { ...session, status: "ready" as const, lastError: "persisted" }, |
| 689 | 691 | }), |
| @@ -691,7 +693,7 @@ describe("resolveSidebarV2Status", () => { · 1 unmodified line | ||
| 691 | 693 | }); |
| 692 | 694 | |
| 693 | 695 | it("defaults to ready with no session", () => { |
| 694 | − expect(resolveSidebarV2Status({ ...idle, session: null })).toBe("ready"); | |
| 696 | + expect(resolveSidebarThreadStatus({ ...idle, session: null })).toBe("ready"); | |
| 695 | 697 | }); |
| 696 | 698 | }); |
| 697 | 699 | |
| @@ -715,14 +717,14 @@ describe("searchSidebarThreadsByTitle", () => { · 17 unmodified lines | ||
| 715 | 717 | }); |
| 716 | 718 | }); |
| 717 | 719 | |
| 718 | −describe("sortThreadsForSidebarV2", () => { | |
| 720 | +describe("sortThreadsForSidebar", () => { | |
| 719 | 721 | const sortable = (input: { id: string; createdAt: string }) => ({ |
| 720 | 722 | id: input.id, |
| 721 | 723 | createdAt: input.createdAt, |
| 722 | 724 | }); |
| 723 | 725 | |
| 724 | 726 | it("orders by creation time, newest first, ignoring activity", () => { |
| 725 | − const sorted = sortThreadsForSidebarV2([ | |
| 727 | + const sorted = sortThreadsForSidebar([ | |
| 726 | 728 | sortable({ id: "oldest", createdAt: "2026-03-09T08:00:00.000Z" }), |
| 727 | 729 | sortable({ id: "newest", createdAt: "2026-03-09T12:00:00.000Z" }), |
| 728 | 730 | sortable({ id: "middle", createdAt: "2026-03-09T10:00:00.000Z" }), |
| @@ -732,7 +734,7 @@ describe("sortThreadsForSidebarV2", () => { · 3 unmodified lines | ||
| 732 | 734 | }); |
| 733 | 735 | |
| 734 | 736 | it("breaks creation-time ties by id so the order is stable", () => { |
| 735 | − const sorted = sortThreadsForSidebarV2([ | |
| 737 | + const sorted = sortThreadsForSidebar([ | |
| 736 | 738 | sortable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z" }), |
| 737 | 739 | sortable({ id: "a", createdAt: "2026-03-09T10:00:00.000Z" }), |
| 738 | 740 | ]); |
| @@ -838,7 +840,7 @@ describe("planPinnedReorder", () => { · 99 unmodified lines | ||
| 838 | 840 | }); |
| 839 | 841 | }); |
| 840 | 842 | |
| 841 | −describe("sortPinnedThreadsForSidebarV2", () => { | |
| 843 | +describe("sortPinnedThreadsForSidebar", () => { | |
| 842 | 844 | const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({ |
| 843 | 845 | id: input.id, |
| 844 | 846 | createdAt: input.createdAt, |
| @@ -846,7 +848,7 @@ describe("sortPinnedThreadsForSidebarV2", () => { · 1 unmodified line | ||
| 846 | 848 | }); |
| 847 | 849 | |
| 848 | 850 | it("sorts keyed threads by key ahead of keyless threads in creation order", () => { |
| 849 | − const sorted = sortPinnedThreadsForSidebarV2([ | |
| 851 | + const sorted = sortPinnedThreadsForSidebar([ | |
| 850 | 852 | pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }), |
| 851 | 853 | pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }), |
| 852 | 854 | pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }), |
| @@ -862,7 +864,7 @@ describe("sortPinnedThreadsForSidebarV2", () => { · 9 unmodified lines | ||
| 862 | 864 | }); |
| 863 | 865 | |
| 864 | 866 | it("breaks equal keys by id so raced writes render identically everywhere", () => { |
| 865 | − const sorted = sortPinnedThreadsForSidebarV2([ | |
| 867 | + const sorted = sortPinnedThreadsForSidebar([ | |
| 866 | 868 | pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }), |
| 867 | 869 | pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }), |
| 868 | 870 | ]); |
| @@ -871,7 +873,7 @@ describe("sortPinnedThreadsForSidebarV2", () => { · 2 unmodified lines | ||
| 871 | 873 | }); |
| 872 | 874 | }); |
| 873 | 875 | |
| 874 | −describe("sortSettledThreadsForSidebarV2", () => { | |
| 876 | +describe("sortSettledThreadsForSidebar", () => { | |
| 875 | 877 | const settled = (input: { |
| 876 | 878 | id: string; |
| 877 | 879 | settledAt?: string | null; |
| @@ -887,7 +889,7 @@ describe("sortSettledThreadsForSidebarV2", () => { · 9 unmodified lines | ||
| 887 | 889 | }); |
| 888 | 890 | |
| 889 | 891 | it("orders by settle time, most recently settled first", () => { |
| 890 | − const sorted = sortSettledThreadsForSidebarV2([ | |
| 892 | + const sorted = sortSettledThreadsForSidebar([ | |
| 891 | 893 | settled({ |
| 892 | 894 | id: "settled-first", |
| 893 | 895 | settledAt: "2026-03-09T10:00:00.000Z", |
| @@ -905,7 +907,7 @@ describe("sortSettledThreadsForSidebarV2", () => { · 11 unmodified lines | ||
| 905 | 907 | }); |
| 906 | 908 | |
| 907 | 909 | it("falls back to last activity for auto-settled threads without a settledAt stamp", () => { |
| 908 | − const sorted = sortSettledThreadsForSidebarV2([ | |
| 910 | + const sorted = sortSettledThreadsForSidebar([ | |
| 909 | 911 | settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }), |
| 910 | 912 | settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }), |
| 911 | 913 | settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }), |
| @@ -917,7 +919,7 @@ describe("sortSettledThreadsForSidebarV2", () => { · 5 unmodified lines | ||
| 917 | 919 | it("counts a turn completion as activity for auto-settled threads", () => { |
| 918 | 920 | // The message came in before the other thread's, but its turn finished |
| 919 | 921 | // after: completion time is the real "work ended" moment. |
| 920 | − const sorted = sortSettledThreadsForSidebarV2([ | |
| 922 | + const sorted = sortSettledThreadsForSidebar([ | |
| 921 | 923 | settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }), |
| 922 | 924 | settled({ |
| 923 | 925 | id: "completed-later", |
| @@ -930,7 +932,7 @@ describe("sortSettledThreadsForSidebarV2", () => { · 6 unmodified lines | ||
| 930 | 932 | }); |
| 931 | 933 | |
| 932 | 934 | it("breaks timestamp ties by id so the order is stable", () => { |
| 933 | − const sorted = sortSettledThreadsForSidebarV2([ | |
| 935 | + const sorted = sortSettledThreadsForSidebar([ | |
| 934 | 936 | settled({ id: "b", settledAt: "2026-03-09T10:00:00.000Z" }), |
| 935 | 937 | settled({ id: "a", settledAt: "2026-03-09T10:00:00.000Z" }), |
| 936 | 938 | ]); |
| @@ -423,21 +423,27 @@ export function resolveThreadRowClassName(input: { · 422 unmodified lines | ||
| 423 | 423 | ); |
| 424 | 424 | } |
| 425 | 425 | |
| 426 | −// ── Sidebar v2 status model ───────────────────────────────────────── | |
| 426 | +// ── Sidebar thread status model ───────────────────────────────────── | |
| 427 | 427 | // Five visual states, three colors: color is reserved for "act now" |
| 428 | 428 | // (approval), "in motion" (working), and "broken" (failed). Ready is the |
| 429 | 429 | // unlabeled resting state — the agent stopped and is waiting on the user, |
| 430 | 430 | // whether it finished, asked a question, or proposed a plan. |
| 431 | 431 | // Unread completion is tracked separately: it describes whether a ready |
| 432 | 432 | // thread needs attention, not what the thread is currently doing. |
| 433 | −export type SidebarV2Status = "approval" | "input" | "working" | "monitoring" | "failed" | "ready"; | |
| 434 | − | |
| 435 | −type SidebarV2StatusInput = Pick< | |
| 433 | +export type SidebarThreadStatus = | |
| 434 | + | "approval" | |
| 435 | + | "input" | |
| 436 | + | "working" | |
| 437 | + | "monitoring" | |
| 438 | + | "failed" | |
| 439 | + | "ready"; | |
| 440 | + | |
| 441 | +type SidebarThreadStatusInput = Pick< | |
| 436 | 442 | SidebarThreadSummary, |
| 437 | 443 | "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness" |
| 438 | 444 | >; |
| 439 | 445 | |
| 440 | −export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status { | |
| 446 | +export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus { | |
| 441 | 447 | if (thread.hasPendingApprovals) { |
| 442 | 448 | return "approval"; |
| 443 | 449 | } |
| @@ -496,11 +502,11 @@ export function firstValidTimestamp( · 52 unmodified lines | ||
| 496 | 502 | return null; |
| 497 | 503 | } |
| 498 | 504 | |
| 499 | −// v2 sort: static creation order, newest thread on top. Activity NEVER | |
| 505 | +// Sidebar sort: static creation order, newest thread on top. Activity NEVER | |
| 500 | 506 | // reorders the list — a row holds its position from open until settled, so |
| 501 | 507 | // the screen only moves at lifecycle transitions. Status (including pending |
| 502 | 508 | // approval) is carried by each card's edge strip, not by position. |
| 503 | −export function sortThreadsForSidebarV2< | |
| 509 | +export function sortThreadsForSidebar< | |
| 504 | 510 | T extends { readonly id: string; readonly createdAt: string }, |
| 505 | 511 | >(threads: readonly T[]): T[] { |
| 506 | 512 | return [...threads].toSorted( |
| @@ -517,7 +523,7 @@ export { · 10 unmodified lines | ||
| 517 | 523 | pinOrderKeyBetween, |
| 518 | 524 | planPinnedReorder, |
| 519 | 525 | } from "@t3tools/client-runtime/state/thread-sort"; |
| 520 | −export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebarV2 } from "@t3tools/client-runtime/state/thread-sort"; | |
| 526 | +export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort"; | |
| 521 | 527 | |
| 522 | 528 | /** |
| 523 | 529 | * Search the already-ordered sidebar thread collection by title only. |
| @@ -566,7 +572,7 @@ export function resolveSettledTimestamp(thread: SettledTimestampInput): string | · 42 unmodified lines | ||
| 566 | 572 | |
| 567 | 573 | // Settled rows are history, so they order by when the work ENDED, not when |
| 568 | 574 | // the thread was created or last touched. |
| 569 | −export function sortSettledThreadsForSidebarV2< | |
| 575 | +export function sortSettledThreadsForSidebar< | |
| 570 | 576 | T extends SettledTimestampInput & { readonly id: string }, |
| 571 | 577 | >(threads: readonly T[]): T[] { |
| 572 | 578 | const timestampMs = (thread: T) => { |
| @@ -1,99 +1,79 @@ | ||
| 1 | −import { | |
| 2 | − ArchiveIcon, | |
| 3 | − ArrowUpDownIcon, | |
| 4 | − ChevronRightIcon, | |
| 5 | − CloudIcon, | |
| 6 | − ContainerIcon, | |
| 7 | − FolderPlusIcon, | |
| 8 | − Globe2Icon, | |
| 9 | − LoaderIcon, | |
| 10 | − SearchIcon, | |
| 11 | − SquarePenIcon, | |
| 12 | − TerminalIcon, | |
| 13 | − TriangleAlertIcon, | |
| 14 | −} from "lucide-react"; | |
| 15 | −import { | |
| 16 | − ChangeRequestStatusIcon, | |
| 17 | − prStatusIndicator, | |
| 18 | − PrStatusTooltipContent, | |
| 19 | − resolveThreadPr, | |
| 20 | − terminalStatusFromRunningIds, | |
| 21 | − ThreadStatusLabel, | |
| 22 | − ThreadWorktreeIndicator, | |
| 23 | −} from "./ThreadStatusIndicators"; | |
| 24 | −import { ProjectFavicon } from "./ProjectFavicon"; | |
| 25 | −import { useAtomValue } from "@effect/atom-react"; | |
| 26 | 1 | import { autoAnimate } from "@formkit/auto-animate"; |
| 27 | −import React, { useCallback, useEffect, memo, useMemo, useRef, useState } from "react"; | |
| 28 | −import { useShallow } from "zustand/react/shallow"; | |
| 2 | +import { useAtomValue } from "@effect/atom-react"; | |
| 29 | 3 | import { |
| 30 | 4 | DndContext, |
| 31 | − type DragCancelEvent, | |
| 32 | − type CollisionDetection, | |
| 33 | 5 | PointerSensor, |
| 34 | − type DragStartEvent, | |
| 35 | − closestCorners, | |
| 36 | − pointerWithin, | |
| 6 | + closestCenter, | |
| 37 | 7 | useSensor, |
| 38 | 8 | useSensors, |
| 39 | 9 | type DragEndEvent, |
| 40 | 10 | } from "@dnd-kit/core"; |
| 41 | −import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; | |
| 11 | +import { | |
| 12 | + SortableContext, | |
| 13 | + arrayMove, | |
| 14 | + useSortable, | |
| 15 | + verticalListSortingStrategy, | |
| 16 | +} from "@dnd-kit/sortable"; | |
| 42 | 17 | import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers"; |
| 43 | 18 | import { CSS } from "@dnd-kit/utilities"; |
| 44 | 19 | import { |
| 45 | − type ContextMenuItem, | |
| 46 | − ProjectId, | |
| 47 | − type ScopedThreadRef, | |
| 48 | − type ResolvedKeybindingsConfig, | |
| 49 | − type SidebarProjectGroupingMode, | |
| 50 | − ThreadId, | |
| 51 | −} from "@t3tools/contracts"; | |
| 20 | + canSnooze, | |
| 21 | + effectiveSettled, | |
| 22 | + effectiveSnoozed, | |
| 23 | + threadWokeAt, | |
| 24 | +} from "@t3tools/client-runtime/state/thread-settled"; | |
| 25 | +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; | |
| 52 | 26 | import { |
| 53 | − parseScopedThreadKey, | |
| 54 | − scopedProjectKey, | |
| 55 | − scopedThreadKey, | |
| 56 | 27 | scopeProjectRef, |
| 57 | 28 | scopeThreadRef, |
| 29 | + scopedThreadKey, | |
| 58 | 30 | } from "@t3tools/client-runtime/environment"; |
| 59 | −import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; | |
| 31 | +import type { ScopedThreadRef, SidebarProjectGroupingMode } from "@t3tools/contracts"; | |
| 32 | +import type { TimestampFormat } from "@t3tools/contracts/settings"; | |
| 33 | +import { | |
| 34 | + AlarmClockIcon, | |
| 35 | + AlarmClockOffIcon, | |
| 36 | + CheckIcon, | |
| 37 | + ChevronDownIcon, | |
| 38 | + CircleAlertIcon, | |
| 39 | + CircleCheckIcon, | |
| 40 | + CircleDashedIcon, | |
| 41 | + ClockIcon, | |
| 42 | + CopyIcon, | |
| 43 | + FolderIcon, | |
| 44 | + FolderPlusIcon, | |
| 45 | + GitBranchIcon, | |
| 46 | + EllipsisIcon, | |
| 47 | + MessageSquareIcon, | |
| 48 | + PinIcon, | |
| 49 | + PlusIcon, | |
| 50 | + SearchIcon, | |
| 51 | + ServerIcon, | |
| 52 | + SquarePenIcon, | |
| 53 | + TerminalIcon, | |
| 54 | + Trash2Icon, | |
| 55 | + Undo2Icon, | |
| 56 | + XIcon, | |
| 57 | +} from "lucide-react"; | |
| 58 | +import { | |
| 59 | + memo, | |
| 60 | + useCallback, | |
| 61 | + useEffect, | |
| 62 | + useMemo, | |
| 63 | + useRef, | |
| 64 | + useState, | |
| 65 | + type KeyboardEvent as ReactKeyboardEvent, | |
| 66 | + type MouseEvent as ReactMouseEvent, | |
| 67 | + type ReactNode, | |
| 68 | +} from "react"; | |
| 69 | +import { useParams, useRouter } from "@tanstack/react-router"; | |
| 70 | + | |
| 60 | 71 | import { |
| 61 | 72 | isAtomCommandInterrupted, |
| 62 | 73 | settlePromise, |
| 63 | 74 | squashAtomCommandFailure, |
| 64 | 75 | } from "@t3tools/client-runtime/state/runtime"; |
| 65 | −import { useLocation, useNavigate, useParams, useRouter } from "@tanstack/react-router"; | |
| 66 | −import { | |
| 67 | − MAX_SIDEBAR_THREAD_PREVIEW_COUNT, | |
| 68 | − MIN_SIDEBAR_THREAD_PREVIEW_COUNT, | |
| 69 | − type SidebarProjectSortOrder, | |
| 70 | − type SidebarThreadPreviewCount, | |
| 71 | − type SidebarThreadSortOrder, | |
| 72 | −} from "@t3tools/contracts/settings"; | |
| 73 | −import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal"; | |
| 74 | −import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps"; | |
| 75 | 76 | import { isElectron } from "../env"; |
| 76 | −import { useOpenPrLink } from "../lib/openPullRequestLink"; | |
| 77 | −import { isTerminalFocused } from "../lib/terminalFocus"; | |
| 78 | −import { isMacPlatform } from "../lib/utils"; | |
| 79 | −import { | |
| 80 | − readThreadShell, | |
| 81 | − useProject, | |
| 82 | − useProjects, | |
| 83 | − useThreadShells, | |
| 84 | − useThreadShellsForProjectRefs, | |
| 85 | −} from "../state/entities"; | |
| 86 | −import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; | |
| 87 | −import { useThreadRunningTerminalIds } from "../state/terminalSessions"; | |
| 88 | −import { useThreadDiscoveredPorts } from "../portDiscoveryState"; | |
| 89 | −import { openDiscoveredPort } from "./preview/openDiscoveredPort"; | |
| 90 | −import { useAtomCommand } from "../state/use-atom-command"; | |
| 91 | −import { previewEnvironment } from "../state/preview"; | |
| 92 | −import { | |
| 93 | − legacyProjectCwdPreferenceKey, | |
| 94 | − resolveProjectExpanded, | |
| 95 | − useUiStateStore, | |
| 96 | −} from "../uiStateStore"; | |
| 97 | 77 | import { |
| 98 | 78 | resolveShortcutCommand, |
| 99 | 79 | shortcutLabelForCommand, |
| @@ -102,39 +82,89 @@ import { · 2 unmodified lines | ||
| 102 | 82 | threadJumpIndexFromCommand, |
| 103 | 83 | threadTraversalDirectionFromCommand, |
| 104 | 84 | } from "../keybindings"; |
| 105 | −import { isModelPickerOpen } from "../modelPickerVisibility"; | |
| 106 | 85 | import { useShortcutModifierState } from "../shortcutModifierState"; |
| 86 | +import { isTerminalFocused } from "../lib/terminalFocus"; | |
| 87 | +import { isModelPickerOpen } from "../modelPickerVisibility"; | |
| 88 | +import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; | |
| 89 | +import { isMacPlatform } from "~/lib/utils"; | |
| 90 | +import { useOpenPrLink } from "../lib/openPullRequestLink"; | |
| 107 | 91 | import { readLocalApi } from "../localApi"; |
| 108 | −import { useComposerDraftStore } from "../composerDraftStore"; | |
| 109 | −import { useNewThreadHandler } from "../hooks/useHandleNewThread"; | |
| 110 | −import { useDesktopUpdateState } from "../state/desktopUpdate"; | |
| 111 | − | |
| 92 | +import { | |
| 93 | + deriveProjectGroupingOverrideKey, | |
| 94 | + getProjectOrderKey, | |
| 95 | + selectProjectGroupingSettings, | |
| 96 | +} from "../logicalProject"; | |
| 97 | +import { | |
| 98 | + buildSidebarProjectSnapshots, | |
| 99 | + type SidebarProjectGroupMember, | |
| 100 | + type SidebarProjectSnapshot, | |
| 101 | +} from "../sidebarProjectGrouping"; | |
| 102 | +import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; | |
| 103 | +import { useThreadSelectionStore } from "../threadSelectionStore"; | |
| 112 | 104 | import { useThreadActions } from "../hooks/useThreadActions"; |
| 105 | +import { useHandleNewThread } from "../hooks/useHandleNewThread"; | |
| 106 | +import { openCommandPalette } from "../commandPaletteBus"; | |
| 107 | +import { startNewThreadFromContext } from "../lib/chatThreadActions"; | |
| 108 | +import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings"; | |
| 109 | +import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; | |
| 110 | +import { useNowMinute } from "../hooks/useNowMinute"; | |
| 111 | +import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; | |
| 112 | +import { useProjects, useThreadShells } from "../state/entities"; | |
| 113 | +import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server"; | |
| 114 | +import { vcsEnvironment } from "../state/vcs"; | |
| 115 | +import { threadEnvironment } from "../state/threads"; | |
| 113 | 116 | import { projectEnvironment } from "../state/projects"; |
| 114 | 117 | import { useEnvironmentQuery } from "../state/query"; |
| 115 | −import { threadEnvironment, useEnvironmentThread } from "../state/threads"; | |
| 116 | −import { vcsEnvironment } from "../state/vcs"; | |
| 117 | −import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; | |
| 118 | +import { useAtomCommand } from "../state/use-atom-command"; | |
| 118 | 119 | import { |
| 119 | 120 | buildThreadRouteParams, |
| 120 | 121 | resolveActiveThreadRouteRef, |
| 121 | 122 | resolveThreadRouteTarget, |
| 122 | 123 | } from "../threadRoutes"; |
| 123 | −import { stackedThreadToast, toastManager } from "./ui/toast"; | |
| 124 | −import { formatRelativeTimeLabel } from "../timestampFormat"; | |
| 125 | −import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; | |
| 126 | −import { Kbd } from "./ui/kbd"; | |
| 124 | +import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat"; | |
| 125 | +import type { SidebarThreadSummary } from "../types"; | |
| 126 | +import { cn } from "~/lib/utils"; | |
| 127 | +import { buildThreadActionMenuItems } from "./threadActionMenu.logic"; | |
| 128 | +import { | |
| 129 | + buildBulkTitleRegenerationContextMenuItem, | |
| 130 | + formatWorkingDurationLabel, | |
| 131 | + firstValidTimestampMs, | |
| 132 | + hasUnseenCompletion, | |
| 133 | + isTrailingDoubleClick, | |
| 134 | + orderItemsByPreferredIds, | |
| 135 | + planPinnedReorder, | |
| 136 | + resolveAdjacentThreadId, | |
| 137 | + resolveSettledTimestamp, | |
| 138 | + resolveSidebarThreadStatus, | |
| 139 | + searchSidebarThreadsByTitle, | |
| 140 | + resolveWorkingStartedAt, | |
| 141 | + shouldNavigateAfterProjectRemoval, | |
| 142 | + sortLogicalProjectsForSidebar, | |
| 143 | + sortPinnedThreadsForSidebar, | |
| 144 | + sortSettledThreadsForSidebar, | |
| 145 | + sortThreadsForSidebar, | |
| 146 | +} from "./Sidebar.logic"; | |
| 147 | +import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic"; | |
| 148 | +import { | |
| 149 | + prStatusIndicator, | |
| 150 | + resolveThreadPr, | |
| 151 | + settledPrHoverColorClass, | |
| 152 | + terminalStatusFromRunningIds, | |
| 153 | + type TerminalStatusIndicator, | |
| 154 | +} from "./ThreadStatusIndicators"; | |
| 127 | 155 | import { |
| 128 | − getArm64IntelBuildWarningDescription, | |
| 129 | − getDesktopUpdateActionError, | |
| 130 | − getDesktopUpdateInstallConfirmationMessage, | |
| 131 | − isDesktopUpdateButtonDisabled, | |
| 132 | − resolveDesktopUpdateButtonAction, | |
| 133 | − shouldShowArm64IntelBuildWarning, | |
| 134 | − shouldToastDesktopUpdateActionResult, | |
| 135 | −} from "./desktopUpdate.logic"; | |
| 136 | −import { showDesktopUpdateDownloadedToast } from "./desktopUpdate.toast"; | |
| 137 | −import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; | |
| 156 | + resolveSnoozePresets, | |
| 157 | + snoozeWakeDescription, | |
| 158 | + snoozeWakeLabel, | |
| 159 | + type SnoozePreset, | |
| 160 | +} from "./Sidebar.snooze"; | |
| 161 | +import { ProjectFavicon } from "./ProjectFavicon"; | |
| 162 | +import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon"; | |
| 163 | +import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils"; | |
| 164 | +import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances"; | |
| 165 | +import { primaryServerProvidersAtom } from "../state/server"; | |
| 166 | +import { useThreadRunningTerminalIds } from "../state/terminalSessions"; | |
| 167 | +import { stackedThreadToast, toastManager } from "./ui/toast"; | |
| 138 | 168 | import { Button } from "./ui/button"; |
| 139 | 169 | import { |
| 140 | 170 | Dialog, |
| @@ -146,1542 +176,1867 @@ import { · 5 unmodified lines | ||
| 146 | 176 | DialogTitle, |
| 147 | 177 | } from "./ui/dialog"; |
| 148 | 178 | import { Input } from "./ui/input"; |
| 149 | −import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; | |
| 150 | −import { | |
| 151 | − NumberField, | |
| 152 | − NumberFieldDecrement, | |
| 153 | − NumberFieldGroup, | |
| 154 | − NumberFieldIncrement, | |
| 155 | − NumberFieldInput, | |
| 156 | −} from "./ui/number-field"; | |
| 179 | +import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; | |
| 157 | 180 | import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; |
| 158 | −import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; | |
| 159 | −import { | |
| 160 | − SidebarContent, | |
| 161 | − SidebarGroup, | |
| 162 | − SidebarMenu, | |
| 163 | − SidebarMenuButton, | |
| 164 | − SidebarMenuItem, | |
| 165 | − SidebarMenuSub, | |
| 166 | − SidebarMenuSubButton, | |
| 167 | − SidebarMenuSubItem, | |
| 168 | − useSidebar, | |
| 169 | −} from "./ui/sidebar"; | |
| 170 | −import { useThreadSelectionStore } from "../threadSelectionStore"; | |
| 171 | −import { openCommandPalette } from "../commandPaletteBus"; | |
| 172 | −import { | |
| 173 | − archiveSelectedThreadEntries, | |
| 174 | − buildMultiSelectThreadContextMenuItems, | |
| 175 | − getSidebarThreadIdsToPrewarm, | |
| 176 | − resolveAdjacentThreadId, | |
| 177 | − isContextMenuPointerDown, | |
| 178 | − isTrailingDoubleClick, | |
| 179 | − resolveProjectStatusIndicator, | |
| 180 | − resolveThreadRowClassName, | |
| 181 | − resolveThreadStatusPill, | |
| 182 | − orderItemsByPreferredIds, | |
| 183 | − shouldClearThreadSelectionOnMouseDown, | |
| 184 | − sortProjectsForSidebar, | |
| 185 | − useThreadJumpHintVisibility, | |
| 186 | − ThreadStatusPill, | |
| 187 | −} from "./Sidebar.logic"; | |
| 188 | −import { sortThreads } from "../lib/threadSort"; | |
| 181 | +import { SidebarContent, SidebarGroup, SidebarMenuButton, useSidebar } from "./ui/sidebar"; | |
| 189 | 182 | import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; |
| 190 | −import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; | |
| 191 | −import { useIsMobile } from "~/hooks/useMediaQuery"; | |
| 192 | −import { CommandDialogTrigger } from "./ui/command"; | |
| 193 | −import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings"; | |
| 194 | −import { primaryServerKeybindingsAtom } from "../state/server"; | |
| 195 | −import { | |
| 196 | − derivePhysicalProjectKey, | |
| 197 | − deriveProjectGroupingOverrideKey, | |
| 198 | − getProjectOrderKey, | |
| 199 | − selectProjectGroupingSettings, | |
| 200 | −} from "../logicalProject"; | |
| 201 | −import type { SidebarThreadSummary } from "../types"; | |
| 202 | −import { | |
| 203 | − buildPhysicalToLogicalProjectKeyMap, | |
| 204 | − buildSidebarProjectSnapshots, | |
| 205 | − type SidebarProjectGroupMember, | |
| 206 | − type SidebarProjectSnapshot, | |
| 207 | −} from "../sidebarProjectGrouping"; | |
| 208 | −const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = { | |
| 209 | − updated_at: "Last user message", | |
| 210 | − created_at: "Created at", | |
| 211 | − manual: "Manual", | |
| 212 | −}; | |
| 213 | −const SIDEBAR_THREAD_SORT_LABELS: Record<SidebarThreadSortOrder, string> = { | |
| 214 | − updated_at: "Last user message", | |
| 215 | − created_at: "Created at", | |
| 216 | −}; | |
| 217 | −const SIDEBAR_LIST_ANIMATION_OPTIONS = { | |
| 218 | − duration: 180, | |
| 219 | − easing: "ease-out", | |
| 220 | −} as const; | |
| 221 | −const EMPTY_THREAD_JUMP_LABELS = new Map<string, string>(); | |
| 183 | +import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover"; | |
| 184 | +import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; | |
| 185 | +import { useComposerDraftStore } from "../composerDraftStore"; | |
| 186 | + | |
| 187 | +// Settled-tail paging: recent history is the common lookup; the deep tail | |
| 188 | +// stays behind an explicit Show more. | |
| 189 | +const SETTLED_TAIL_INITIAL_COUNT = 10; | |
| 190 | +const SETTLED_TAIL_PAGE_COUNT = 25; | |
| 222 | 191 | const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = { |
| 223 | 192 | repository: "Group by repository", |
| 224 | 193 | repository_path: "Group by repository path", |
| 225 | 194 | separate: "Keep separate", |
| 226 | 195 | }; |
| 227 | −const SIDEBAR_ICON_ACTION_BUTTON_CLASS = | |
| 228 | − "inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-icon-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"; | |
| 229 | 196 | |
| 230 | −function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: ScopedThreadRef }) { | |
| 231 | − useEnvironmentThread(threadRef.environmentId, threadRef.threadId); | |
| 232 | − return null; | |
| 197 | +function compactSidebarTimeLabel(label: string): string { | |
| 198 | + if (label === "just now") return "now"; | |
| 199 | + return label.endsWith(" ago") ? label.slice(0, -4) : label; | |
| 233 | 200 | } |
| 234 | 201 | |
| 235 | −function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount { | |
| 236 | − return Math.min( | |
| 237 | − MAX_SIDEBAR_THREAD_PREVIEW_COUNT, | |
| 238 | − Math.max(MIN_SIDEBAR_THREAD_PREVIEW_COUNT, value), | |
| 239 | − ) as SidebarThreadPreviewCount; | |
| 202 | +function threadTimeLabel(thread: SidebarThreadSummary): string { | |
| 203 | + const timestamp = thread.latestUserMessageAt ?? thread.updatedAt; | |
| 204 | + return compactSidebarTimeLabel(formatRelativeTimeLabel(timestamp)); | |
| 240 | 205 | } |
| 241 | 206 | |
| 242 | −function formatProjectMemberActionLabel( | |
| 243 | − member: SidebarProjectGroupMember, | |
| 244 | − groupedProjectCount: number, | |
| 245 | −): string { | |
| 246 | − if (groupedProjectCount <= 1) { | |
| 247 | − return member.title; | |
| 248 | − } | |
| 207 | +// Settled rows read "how long ago did this wrap up", matching their sort | |
| 208 | +// key: both go through resolveSettledTimestamp so label and order can't | |
| 209 | +// disagree. | |
| 210 | +function settledTimeLabel(thread: SidebarThreadSummary): string { | |
| 211 | + const timestamp = resolveSettledTimestamp(thread); | |
| 212 | + return timestamp === null ? "" : compactSidebarTimeLabel(formatRelativeTimeLabel(timestamp)); | |
| 213 | +} | |
| 249 | 214 | |
| 250 | − return member.environmentLabel | |
| 251 | − ? `${member.environmentLabel} — ${member.workspaceRoot}` | |
| 252 | − : member.workspaceRoot; | |
| 215 | +// Floats at the row's right edge, vertically centered, while the jump | |
| 216 | +// modifier is held. An overlay pill instead of an inline slot: the hint | |
| 217 | +// must neither displace the status/time label (holding ⌘ used to blank | |
| 218 | +// out "Working") nor shift any layout when it appears. pointer-events-none | |
| 219 | +// so it never swallows clicks meant for the settle/un-settle buttons it | |
| 220 | +// can overlap. | |
| 221 | +function JumpHintBadge(props: { label: string }) { | |
| 222 | + return ( | |
| 223 | + <span | |
| 224 | + aria-hidden | |
| 225 | + className="pointer-events-none absolute right-1.5 top-1/2 z-10 inline-flex h-5 -translate-y-1/2 items-center rounded-full border border-border/80 bg-background/95 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm" | |
| 226 | + > | |
| 227 | + {props.label} | |
| 228 | + </span> | |
| 229 | + ); | |
| 253 | 230 | } |
| 254 | 231 | |
| 255 | −function projectExpansionPreferenceKeys(project: SidebarProjectSnapshot): string[] { | |
| 256 | − return [ | |
| 257 | − project.projectKey, | |
| 258 | − ...project.memberProjects.map((member) => member.physicalProjectKey), | |
| 259 | − ...project.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)), | |
| 260 | − ]; | |
| 232 | +// Self-ticking so only this span re-renders each second, not the whole row. | |
| 233 | +function WorkingDuration(props: { startedAt: string | null }) { | |
| 234 | + const startedMs = props.startedAt !== null ? Date.parse(props.startedAt) : Number.NaN; | |
| 235 | + const [, setTick] = useState(0); | |
| 236 | + useEffect(() => { | |
| 237 | + if (Number.isNaN(startedMs)) return; | |
| 238 | + const id = window.setInterval(() => setTick((tick) => tick + 1), 1_000); | |
| 239 | + return () => window.clearInterval(id); | |
| 240 | + }, [startedMs]); | |
| 241 | + if (Number.isNaN(startedMs)) return null; | |
| 242 | + return ( | |
| 243 | + <span className="font-mono tabular-nums"> | |
| 244 | + {formatWorkingDurationLabel(Date.now() - startedMs)} | |
| 245 | + </span> | |
| 246 | + ); | |
| 261 | 247 | } |
| 262 | 248 | |
| 263 | −function projectGroupingModeDescription(mode: SidebarProjectGroupingMode): string { | |
| 264 | − switch (mode) { | |
| 265 | − case "repository": | |
| 266 | − return "Projects from the same repository share one sidebar row."; | |
| 267 | − case "repository_path": | |
| 268 | − return "Projects group only when both the repository and repo-relative path match."; | |
| 269 | − case "separate": | |
| 270 | − return "Every project path gets its own sidebar row."; | |
| 271 | − } | |
| 249 | +function terminalProcessLabel(count: number): string { | |
| 250 | + return `${count} terminal ${count === 1 ? "process" : "processes"} running`; | |
| 272 | 251 | } |
| 273 | 252 | |
| 274 | −function buildThreadJumpLabelMap(input: { | |
| 275 | − keybindings: ResolvedKeybindingsConfig; | |
| 276 | − platform: string; | |
| 277 | − terminalOpen: boolean; | |
| 278 | − threadJumpCommandByKey: ReadonlyMap< | |
| 279 | − string, | |
| 280 | − NonNullable<ReturnType<typeof threadJumpCommandForIndex>> | |
| 281 | − >; | |
| 282 | −}): ReadonlyMap<string, string> { | |
| 283 | − if (input.threadJumpCommandByKey.size === 0) { | |
| 284 | − return EMPTY_THREAD_JUMP_LABELS; | |
| 285 | − } | |
| 253 | +function SidebarThreadTooltip({ | |
| 254 | + thread, | |
| 255 | + projectTitle, | |
| 256 | + projectCwd, | |
| 257 | + environmentLabel, | |
| 258 | + driverKind, | |
| 259 | + modelInstanceId, | |
| 260 | + modelLabel, | |
| 261 | + branchMismatch, | |
| 262 | + terminalStatus, | |
| 263 | + terminalProcessCount, | |
| 264 | +}: { | |
| 265 | + thread: SidebarThreadSummary; | |
| 266 | + projectTitle: string | null; | |
| 267 | + projectCwd: string | null; | |
| 268 | + environmentLabel: string | null; | |
| 269 | + driverKind: ProviderInstanceEntry["driverKind"] | null; | |
| 270 | + modelInstanceId: string; | |
| 271 | + modelLabel: string; | |
| 272 | + branchMismatch: { | |
| 273 | + threadBranch: string; | |
| 274 | + currentBranch: string; | |
| 275 | + } | null; | |
| 276 | + terminalStatus: TerminalStatusIndicator | null; | |
| 277 | + terminalProcessCount: number; | |
| 278 | +}) { | |
| 279 | + return ( | |
| 280 | + <TooltipPopup | |
| 281 | + side="right" | |
| 282 | + align="start" | |
| 283 | + sideOffset={4} | |
| 284 | + variant="glass" | |
| 285 | + className="max-w-80 text-left whitespace-normal [&_[data-slot=tooltip-viewport]]:p-0" | |
| 286 | + > | |
| 287 | + <div className="flex min-w-0 max-w-80 flex-col gap-2 p-[var(--floating-content-inset)]"> | |
| 288 | + <div className="min-w-0 truncate text-xs leading-none font-medium text-foreground"> | |
| 289 | + {thread.title} | |
| 290 | + </div> | |
| 291 | + <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground"> | |
| 292 | + {projectTitle ? ( | |
| 293 | + <div className="flex min-w-0 items-center gap-2"> | |
| 294 | + <ProjectFavicon | |
| 295 | + environmentId={thread.environmentId} | |
| 296 | + cwd={projectCwd ?? ""} | |
| 297 | + className="size-3 shrink-0 stroke-muted-foreground" | |
| 298 | + /> | |
| 299 | + <div className="min-w-0 truncate text-foreground/75">{projectTitle}</div> | |
| 300 | + </div> | |
| 301 | + ) : null} | |
| 302 | + {environmentLabel ? ( | |
| 303 | + <div className="flex min-w-0 items-center gap-2"> | |
| 304 | + <ServerIcon className="size-3 shrink-0 stroke-muted-foreground" /> | |
| 305 | + <div className="min-w-0 truncate text-foreground/75">{environmentLabel}</div> | |
| 306 | + </div> | |
| 307 | + ) : null} | |
| 308 | + {thread.branch ? ( | |
| 309 | + <div className="flex min-w-0 items-center gap-2"> | |
| 310 | + <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" /> | |
| 311 | + <div className="min-w-0 truncate text-foreground/75">{thread.branch}</div> | |
| 312 | + </div> | |
| 313 | + ) : null} | |
| 314 | + {branchMismatch ? ( | |
| 315 | + <div className="flex min-w-0 items-start gap-2 text-warning"> | |
| 316 | + <CircleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" /> | |
| 317 | + <div className="min-w-0 flex-1 wrap-break-word leading-5"> | |
| 318 | + You're currently checked out on another branch. | |
| 319 | + </div> | |
| 320 | + </div> | |
| 321 | + ) : null} | |
| 322 | + {driverKind ? ( | |
| 323 | + <div className="flex min-w-0 items-center gap-2"> | |
| 324 | + <ProviderInstanceIcon | |
| 325 | + driverKind={driverKind} | |
| 326 | + displayName={thread.session?.providerName ?? modelInstanceId} | |
| 327 | + iconClassName="size-3 shrink-0 grayscale opacity-60" | |
| 328 | + /> | |
| 329 | + <div className="min-w-0 truncate text-foreground/75">{modelLabel}</div> | |
| 330 | + </div> | |
| 331 | + ) : null} | |
| 332 | + {terminalStatus ? ( | |
| 333 | + <div className="flex min-w-0 items-center gap-2"> | |
| 334 | + <TerminalIcon | |
| 335 | + aria-hidden | |
| 336 | + className={cn("size-3 shrink-0", terminalStatus.colorClass)} | |
| 337 | + /> | |
| 338 | + <div className="min-w-0 truncate text-foreground/75"> | |
| 339 | + {terminalProcessLabel(terminalProcessCount)} | |
| 340 | + </div> | |
| 341 | + </div> | |
| 342 | + ) : null} | |
| 343 | + {thread.session?.lastError ? ( | |
| 344 | + <div className="flex min-w-0 items-center gap-2 text-red-600 dark:text-red-400"> | |
| 345 | + <CircleAlertIcon className="size-3 shrink-0 stroke-current" /> | |
| 346 | + <div className="min-w-0 truncate">Error occurred</div> | |
| 347 | + </div> | |
| 348 | + ) : null} | |
| 349 | + </div> | |
| 350 | + </div> | |
| 351 | + </TooltipPopup> | |
| 352 | + ); | |
| 353 | +} | |
| 286 | 354 | |
| 287 | − const shortcutLabelOptions = { | |
| 288 | − platform: input.platform, | |
| 289 | − context: { | |
| 290 | − terminalFocus: false, | |
| 291 | − terminalOpen: input.terminalOpen, | |
| 292 | − }, | |
| 293 | − } as const; | |
| 294 | − const mapping = new Map<string, string>(); | |
| 295 | − for (const [threadKey, command] of input.threadJumpCommandByKey) { | |
| 296 | − const label = shortcutLabelForCommand(input.keybindings, command, shortcutLabelOptions); | |
| 297 | − if (label) { | |
| 298 | − mapping.set(threadKey, label); | |
| 299 | − } | |
| 300 | − } | |
| 301 | − return mapping.size > 0 ? mapping : EMPTY_THREAD_JUMP_LABELS; | |
| 355 | +/** | |
| 356 | + * Hover entry point for snooze: a clock button opening the preset menu. | |
| 357 | + * Controlled by the row (which also uses the open state to pin its hover | |
| 358 | + * actions while the menu is up). | |
| 359 | + */ | |
| 360 | +function SnoozePopoverButton(props: { | |
| 361 | + open: boolean; | |
| 362 | + onOpenChange: (open: boolean) => void; | |
| 363 | + onSnooze: (preset: SnoozePreset) => void; | |
| 364 | + timestampFormat: TimestampFormat; | |
| 365 | +}) { | |
| 366 | + const { open, onOpenChange, onSnooze, timestampFormat } = props; | |
| 367 | + // Presets resolve at open time so "In 1 hour" is relative to the click, | |
| 368 | + // not to when the row mounted. | |
| 369 | + const presets = useMemo( | |
| 370 | + () => (open ? resolveSnoozePresets(new Date(), timestampFormat) : []), | |
| 371 | + [open, timestampFormat], | |
| 372 | + ); | |
| 373 | + return ( | |
| 374 | + <Popover open={open} onOpenChange={onOpenChange}> | |
| 375 | + <PopoverTrigger | |
| 376 | + render={ | |
| 377 | + <button | |
| 378 | + type="button" | |
| 379 | + aria-label="Snooze thread" | |
| 380 | + onClick={(event) => event.stopPropagation()} | |
| 381 | + onDoubleClick={(event) => event.stopPropagation()} | |
| 382 | + className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" | |
| 383 | + /> | |
| 384 | + } | |
| 385 | + > | |
| 386 | + <ClockIcon className="size-3" /> | |
| 387 | + </PopoverTrigger> | |
| 388 | + <PopoverPopup side="bottom" align="end" className="w-56" viewportClassName="p-1"> | |
| 389 | + {presets.map((preset) => ( | |
| 390 | + <button | |
| 391 | + key={preset.id} | |
| 392 | + type="button" | |
| 393 | + onClick={(event) => { | |
| 394 | + event.stopPropagation(); | |
| 395 | + onOpenChange(false); | |
| 396 | + onSnooze(preset); | |
| 397 | + }} | |
| 398 | + className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-foreground/90 hover:bg-accent hover:text-foreground" | |
| 399 | + > | |
| 400 | + <span className="flex-1">{preset.label}</span> | |
| 401 | + <span className="font-mono text-[10px] text-muted-foreground/60 tabular-nums"> | |
| 402 | + {preset.whenLabel} | |
| 403 | + </span> | |
| 404 | + </button> | |
| 405 | + ))} | |
| 406 | + </PopoverPopup> | |
| 407 | + </Popover> | |
| 408 | + ); | |
| 409 | +} | |
| 410 | + | |
| 411 | +// Subset of useSortable applied to a pinned card's root <li>. Listeners go | |
| 412 | +// on the whole card (no dedicated handle): the pointer sensor's distance | |
| 413 | +// constraint keeps plain clicks working, and we skip dnd-kit's aria | |
| 414 | +// attributes since there is no keyboard sensor and the card body already | |
| 415 | +// carries its own button semantics. | |
| 416 | +type SortablePinnedRowBag = Pick< | |
| 417 | + ReturnType<typeof useSortable>, | |
| 418 | + "listeners" | "setNodeRef" | "transform" | "transition" | "isDragging" | |
| 419 | +>; | |
| 420 | + | |
| 421 | +function SortablePinnedThreadRow(props: { | |
| 422 | + id: string; | |
| 423 | + children: (bag: SortablePinnedRowBag) => ReactNode; | |
| 424 | +}) { | |
| 425 | + const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ | |
| 426 | + id: props.id, | |
| 427 | + }); | |
| 428 | + return props.children({ listeners, setNodeRef, transform, transition, isDragging }); | |
| 302 | 429 | } |
| 303 | 430 | |
| 304 | −interface SidebarThreadRowProps { | |
| 431 | +const SidebarThreadRow = memo(function SidebarThreadRow(props: { | |
| 305 | 432 | thread: SidebarThreadSummary; |
| 306 | − projectCwd: string | null; | |
| 307 | − orderedProjectThreadKeys: readonly string[]; | |
| 433 | + variant: "card" | "slim"; | |
| 434 | + // Slim rows are either settled (action: un-settle) or merely quiet | |
| 435 | + // (seen Ready threads — action: settle). | |
| 436 | + variantAction: "settle" | "unsettle" | "unsnooze"; | |
| 437 | + // False on environments whose server predates thread.settle/unsettle: | |
| 438 | + // the lifecycle affordances hide entirely rather than fail on click. | |
| 439 | + settlementSupported: boolean; | |
| 440 | + // Same contract for thread.snooze/unsnooze. | |
| 441 | + snoozeSupported: boolean; | |
| 442 | + // Renders the pin glyph. Pinned cards keep the full settle/snooze quick | |
| 443 | + // actions: settling clears the pin server-side, and snoozing hides the | |
| 444 | + // card until wake with the pin intact underneath. The glyph is also the | |
| 445 | + // in-row pin state cue (the pinned block has no header), so it always | |
| 446 | + // shows while pinned; it only becomes a clickable unpin quick-action once | |
| 447 | + // the pinning capability is confirmed, and stays a passive marker while | |
| 448 | + // the descriptor is not loaded. Pinning itself lives in the context menu. | |
| 449 | + pinningSupported: boolean; | |
| 450 | + isPinned: boolean; | |
| 451 | + // Present only on pinned cards whose server supports reordering: dnd-kit | |
| 452 | + // sortable bag applied to the card root so the whole card drags (the | |
| 453 | + // pointer sensor's distance constraint keeps plain clicks working). | |
| 454 | + sortable?: SortablePinnedRowBag | undefined; | |
| 455 | + // Compact wake countdown ("2h") for rows in the snoozed shelf. | |
| 456 | + snoozeWakeLabelText: string | null; | |
| 457 | + // When a snooze ended (timer or early wake); drives the Woke pill until | |
| 458 | + // the user visits the thread. | |
| 459 | + wokeAt: string | null; | |
| 308 | 460 | isActive: boolean; |
| 309 | 461 | jumpLabel: string | null; |
| 310 | − appSettingsConfirmThreadArchive: boolean; | |
| 311 | − renamingThreadKey: string | null; | |
| 462 | + currentEnvironmentId: string | null; | |
| 463 | + environmentLabel: string | null; | |
| 464 | + projectCwd: string | null; | |
| 465 | + projectTitle: string | null; | |
| 466 | + providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>; | |
| 467 | + timestampFormat: TimestampFormat; | |
| 468 | + onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; | |
| 469 | + onThreadActivate: (threadRef: ScopedThreadRef) => void; | |
| 470 | + onStartRename: (threadRef: ScopedThreadRef, title: string) => void; | |
| 471 | + onRenameTitleChange: (title: string) => void; | |
| 472 | + onCommitRename: (threadRef: ScopedThreadRef, title: string, originalTitle: string) => void; | |
| 473 | + onCancelRename: () => void; | |
| 474 | + isRenaming: boolean; | |
| 312 | 475 | renamingTitle: string; |
| 313 | − setRenamingTitle: (title: string) => void; | |
| 314 | − startThreadRename: (threadKey: string, title: string) => void; | |
| 315 | − renamingInputRef: React.RefObject<HTMLInputElement | null>; | |
| 316 | − renamingCommittedRef: React.RefObject<boolean>; | |
| 317 | − confirmingArchiveThreadKey: string | null; | |
| 318 | − setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>; | |
| 319 | − confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>; | |
| 320 | − handleThreadClick: ( | |
| 321 | − event: React.MouseEvent, | |
| 322 | − threadRef: ScopedThreadRef, | |
| 323 | − orderedProjectThreadKeys: readonly string[], | |
| 324 | − ) => void; | |
| 325 | − navigateToThread: (threadRef: ScopedThreadRef) => void; | |
| 326 | − handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise<void>; | |
| 327 | − handleThreadContextMenu: ( | |
| 328 | − threadRef: ScopedThreadRef, | |
| 329 | − position: { x: number; y: number }, | |
| 330 | − ) => Promise<void>; | |
| 331 | − clearSelection: () => void; | |
| 332 | − commitRename: ( | |
| 333 | − threadRef: ScopedThreadRef, | |
| 334 | − newTitle: string, | |
| 335 | − originalTitle: string, | |
| 336 | − ) => Promise<void>; | |
| 337 | − cancelRename: () => void; | |
| 338 | − attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise<void>; | |
| 339 | − openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void; | |
| 340 | −} | |
| 341 | − | |
| 342 | −export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) { | |
| 476 | + onContextMenu: (threadRef: ScopedThreadRef, position: { x: number; y: number }) => void; | |
| 477 | + onSettle: (threadRef: ScopedThreadRef) => void; | |
| 478 | + onUnsettle: (threadRef: ScopedThreadRef) => void; | |
| 479 | + onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void; | |
| 480 | + onUnsnooze: (threadRef: ScopedThreadRef) => void; | |
| 481 | + onUnpin: (threadRef: ScopedThreadRef) => void; | |
| 482 | + onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void; | |
| 483 | + onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void; | |
| 484 | +}) { | |
| 343 | 485 | const { |
| 344 | − orderedProjectThreadKeys, | |
| 345 | − isActive, | |
| 346 | − jumpLabel, | |
| 347 | − appSettingsConfirmThreadArchive, | |
| 348 | − renamingThreadKey, | |
| 486 | + isRenaming, | |
| 487 | + onChangeRequestState, | |
| 488 | + onCancelRename, | |
| 489 | + onCommitRename, | |
| 490 | + onContextMenu, | |
| 491 | + onAcknowledgeWoke, | |
| 492 | + onRenameTitleChange, | |
| 493 | + onSettle, | |
| 494 | + onSnooze, | |
| 495 | + onStartRename, | |
| 496 | + onThreadActivate, | |
| 497 | + onThreadClick, | |
| 498 | + onUnsettle, | |
| 499 | + onUnsnooze, | |
| 500 | + onUnpin, | |
| 349 | 501 | renamingTitle, |
| 350 | − setRenamingTitle, | |
| 351 | − startThreadRename, | |
| 352 | − renamingInputRef, | |
| 353 | − renamingCommittedRef, | |
| 354 | − confirmingArchiveThreadKey, | |
| 355 | − setConfirmingArchiveThreadKey, | |
| 356 | − confirmArchiveButtonRefs, | |
| 357 | − handleThreadClick, | |
| 358 | − navigateToThread, | |
| 359 | − handleMultiSelectContextMenu, | |
| 360 | − handleThreadContextMenu, | |
| 361 | − clearSelection, | |
| 362 | − commitRename, | |
| 363 | − cancelRename, | |
| 364 | − attemptArchiveThread, | |
| 365 | − openPrLink, | |
| 366 | 502 | thread, |
| 503 | + variant, | |
| 504 | + variantAction, | |
| 367 | 505 | } = props; |
| 368 | − const threadRef = scopeThreadRef(thread.environmentId, thread.id); | |
| 506 | + const threadRef = useMemo( | |
| 507 | + () => scopeThreadRef(thread.environmentId, thread.id), | |
| 508 | + [thread.environmentId, thread.id], | |
| 509 | + ); | |
| 369 | 510 | const threadKey = scopedThreadKey(threadRef); |
| 511 | + const isRegeneratingTitle = thread.titleRegeneration != null; | |
| 370 | 512 | const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); |
| 371 | 513 | const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); |
| 514 | + const openPrLink = useOpenPrLink(); | |
| 372 | 515 | const runningTerminalIds = useThreadRunningTerminalIds({ |
| 373 | 516 | environmentId: thread.environmentId, |
| 374 | 517 | threadId: thread.id, |
| 375 | 518 | }); |
| 376 | − const isMobile = useIsMobile(); | |
| 377 | − const discoveredPorts = useThreadDiscoveredPorts({ | |
| 378 | − environmentId: thread.environmentId, | |
| 379 | − threadId: thread.id, | |
| 380 | − }); | |
| 381 | − const openPreview = useAtomCommand(previewEnvironment.open, { | |
| 382 | − reportFailure: false, | |
| 383 | − }); | |
| 384 | − const environment = useEnvironment(thread.environmentId); | |
| 385 | − const primaryEnvironmentId = usePrimaryEnvironmentId(); | |
| 386 | − const isRemoteThread = | |
| 387 | − primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId; | |
| 388 | − const remoteEnvLabel = environment?.label ?? null; | |
| 389 | − // A desktop-local secondary backend (e.g. the WSL backend) shows up as a | |
| 390 | − // bearer environment whose connection id is prefixed "local:". It runs on the | |
| 391 | − // user's own machine, so the cloud icon is misleading — label it "Local" and | |
| 392 | − // suppress the cloud icon (the project header already shows a container icon | |
| 393 | − // for desktop-local projects, see sidebarProjectGrouping). | |
| 394 | − const isDesktopLocalThread = | |
| 395 | − environment !== null && isDesktopLocalConnectionTarget(environment.entry.target); | |
| 396 | − const threadEnvironmentLabel = isRemoteThread | |
| 397 | − ? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote")) | |
| 398 | − : null; | |
| 399 | − // For grouped projects, the thread may belong to a different environment | |
| 400 | − // than the representative project. Look up the thread's own project cwd | |
| 401 | − // so git status (and thus PR detection) queries the correct path. | |
| 402 | − const threadProject = useProject( | |
| 403 | − useMemo( | |
| 404 | − () => scopeProjectRef(thread.environmentId, thread.projectId), | |
| 405 | − [thread.environmentId, thread.projectId], | |
| 406 | − ), | |
| 407 | − ); | |
| 408 | − const threadProjectCwd = threadProject?.workspaceRoot ?? null; | |
| 409 | − const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd; | |
| 519 | + const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); | |
| 520 | + const terminalProcessCount = runningTerminalIds.length; | |
| 521 | + | |
| 522 | + const gitCwd = thread.worktreePath ?? props.projectCwd; | |
| 410 | 523 | const gitStatus = useEnvironmentQuery( |
| 411 | − thread.branch != null && gitCwd !== null | |
| 524 | + (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null | |
| 412 | 525 | ? vcsEnvironment.status({ |
| 413 | 526 | environmentId: thread.environmentId, |
| 414 | 527 | input: { cwd: gitCwd }, |
| 415 | 528 | }) |
| 416 | 529 | : null, |
| 417 | 530 | ); |
| 418 | − const isHighlighted = isActive || isSelected; | |
| 419 | − const handleOpenDiscoveredPort = useCallback( | |
| 420 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 421 | − const port = discoveredPorts[0]; | |
| 422 | − if (!port) return; | |
| 423 | − event.preventDefault(); | |
| 424 | − event.stopPropagation(); | |
| 425 | − navigateToThread(threadRef); | |
| 426 | − void (async () => { | |
| 427 | − const result = await openDiscoveredPort({ threadRef, port, openPreview }); | |
| 428 | − if (result._tag === "Success" || isAtomCommandInterrupted(result)) { | |
| 429 | − return; | |
| 430 | − } | |
| 431 | − const error = squashAtomCommandFailure(result); | |
| 432 | − toastManager.add( | |
| 433 | − stackedThreadToast({ | |
| 434 | − type: "error", | |
| 435 | − title: "Unable to open preview", | |
| 436 | − description: | |
| 437 | − error instanceof Error ? error.message : "The preview could not be opened.", | |
| 438 | − }), | |
| 439 | − ); | |
| 440 | − })(); | |
| 441 | − }, | |
| 442 | − [discoveredPorts, navigateToThread, openPreview, threadRef], | |
| 443 | − ); | |
| 444 | − const isThreadRunning = | |
| 445 | − thread.session?.status === "running" && thread.session.activeTurnId != null; | |
| 446 | − const threadStatus = resolveThreadStatusPill({ | |
| 447 | − thread: { | |
| 448 | − ...thread, | |
| 449 | − lastVisitedAt, | |
| 450 | − }, | |
| 451 | − }); | |
| 452 | 531 | const pr = resolveThreadPr({ |
| 453 | 532 | threadBranch: thread.branch, |
| 454 | 533 | gitStatus: gitStatus.data, |
| 455 | 534 | }); |
| 456 | − const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider); | |
| 457 | − const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); | |
| 458 | − const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning; | |
| 459 | − const threadMetaClassName = isConfirmingArchive | |
| 460 | − ? "pointer-events-none opacity-0" | |
| 461 | − : !isThreadRunning | |
| 462 | − ? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0" | |
| 463 | − : "pointer-events-none"; | |
| 464 | − const clearConfirmingArchive = useCallback(() => { | |
| 465 | − setConfirmingArchiveThreadKey((current) => (current === threadKey ? null : current)); | |
| 466 | − }, [setConfirmingArchiveThreadKey, threadKey]); | |
| 467 | − const handleMouseLeave = useCallback(() => { | |
| 468 | − clearConfirmingArchive(); | |
| 469 | − }, [clearConfirmingArchive]); | |
| 470 | − const handleBlurCapture = useCallback( | |
| 471 | − (event: React.FocusEvent<HTMLLIElement>) => { | |
| 472 | − const currentTarget = event.currentTarget; | |
| 473 | − requestAnimationFrame(() => { | |
| 474 | − if (currentTarget.contains(document.activeElement)) { | |
| 475 | − return; | |
| 535 | + const prState = pr?.state ?? null; | |
| 536 | + | |
| 537 | + // Same semantics as the legacy sidebar (never-visited counts as read): | |
| 538 | + // switching sidebars must not light up every historical thread as unread. | |
| 539 | + const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); | |
| 540 | + const status = resolveSidebarThreadStatus(thread); | |
| 541 | + // A woken thread reappears at its original position (the sort is | |
| 542 | + // deliberately static), so the pill has to carry the weight. Snoozing is | |
| 543 | + // an explicit act, so the pill clears only when the user re-engages: | |
| 544 | + // reading a completion-triggered wake, clicking the pill, sending a | |
| 545 | + // message, settling, archiving — or finishing the work outright (merged | |
| 546 | + // or closed PR). Timer wakes survive a mere visit. An unparseable visit | |
| 547 | + // timestamp counts as never-visited — corrupt local data must not eat | |
| 548 | + // the wake signal. | |
| 549 | + const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt); | |
| 550 | + const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt); | |
| 551 | + const isWoke = | |
| 552 | + wokeAtDate !== null && | |
| 553 | + (lastVisitedDate === null || lastVisitedDate < wokeAtDate) && | |
| 554 | + prState !== "merged" && | |
| 555 | + prState !== "closed"; | |
| 556 | + // In-flight rows (working, or waiting on approval/input) fade as a whole: | |
| 557 | + // there is nothing for the user to do yet, so prominence is reserved for | |
| 558 | + // rows that need a human — done (unread), read-but-unsettled, failed, and | |
| 559 | + // freshly woken. The status label keeps its hue, so waiting rows stay | |
| 560 | + // findable. In-flight rows recede the same as read-ready ones (inbox-zero: | |
| 561 | + // working threads aren't your problem yet) — only the colored status label | |
| 562 | + // stands out. | |
| 563 | + const isInFlight = | |
| 564 | + status === "working" || status === "monitoring" || status === "approval" || status === "input"; | |
| 565 | + const shouldRecede = | |
| 566 | + (status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected; | |
| 567 | + // Status hues follow the system-wide convention set by sidebar v1 and the | |
| 568 | + // mobile Live Activity/widgets (amber approval, indigo input, sky working) | |
| 569 | + // so a thread reads the same color everywhere it surfaces. | |
| 570 | + const topStatus = | |
| 571 | + status === "working" | |
| 572 | + ? { | |
| 573 | + label: "Working", | |
| 574 | + icon: "working" as const, | |
| 575 | + // No shimmer: a label that animates forever is noise in a sidebar | |
| 576 | + // full of them (and repaints every vsync on high-refresh displays). | |
| 577 | + // Working is a background state, so it rests at the dim end of what | |
| 578 | + // the old pulse cycled through; only the thread you have open gets | |
| 579 | + // the label at full strength. | |
| 580 | + className: cn("text-sky-600 dark:text-sky-400", !props.isActive && "opacity-75"), | |
| 476 | 581 | } |
| 477 | − clearConfirmingArchive(); | |
| 478 | − }); | |
| 582 | + : status === "monitoring" | |
| 583 | + ? { | |
| 584 | + // Monitoring is calm background presence, not active progress | |
| 585 | + // (monitoring-pill D6), so it keeps the label at full strength. | |
| 586 | + label: "Monitoring", | |
| 587 | + icon: null, | |
| 588 | + className: "text-sky-600 dark:text-sky-400", | |
| 589 | + } | |
| 590 | + : status === "approval" | |
| 591 | + ? { | |
| 592 | + label: "Approval", | |
| 593 | + icon: null, | |
| 594 | + className: "text-amber-700 dark:text-amber-300", | |
| 595 | + } | |
| 596 | + : status === "input" | |
| 597 | + ? { | |
| 598 | + label: "Input", | |
| 599 | + icon: null, | |
| 600 | + className: "text-indigo-600 dark:text-indigo-300", | |
| 601 | + } | |
| 602 | + : status === "failed" | |
| 603 | + ? { | |
| 604 | + label: "Failed", | |
| 605 | + icon: null, | |
| 606 | + className: "text-red-700 dark:text-red-300", | |
| 607 | + } | |
| 608 | + : isWoke | |
| 609 | + ? { | |
| 610 | + label: "Woke", | |
| 611 | + icon: "woke" as const, | |
| 612 | + className: "text-amber-700 dark:text-amber-300", | |
| 613 | + } | |
| 614 | + : isUnread | |
| 615 | + ? { | |
| 616 | + label: "Done", | |
| 617 | + icon: "done" as const, | |
| 618 | + className: "text-emerald-700 dark:text-emerald-300", | |
| 619 | + } | |
| 620 | + : null; | |
| 621 | + const isWokeStatus = topStatus?.icon === "woke"; | |
| 622 | + | |
| 623 | + const branchMismatch = resolveLocalCheckoutBranchMismatch({ | |
| 624 | + effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", | |
| 625 | + activeWorktreePath: thread.worktreePath, | |
| 626 | + activeThreadBranch: thread.branch, | |
| 627 | + currentGitBranch: gitStatus.data?.refName ?? null, | |
| 628 | + }); | |
| 629 | + const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider); | |
| 630 | + const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined; | |
| 631 | + // Report the PR state up: the parent partitions rows with effectiveSettled, | |
| 632 | + // and a merged/closed PR auto-settles a thread — data only rows have. | |
| 633 | + useEffect(() => { | |
| 634 | + onChangeRequestState(threadKey, prState); | |
| 635 | + }, [onChangeRequestState, prState, threadKey]); | |
| 636 | + | |
| 637 | + const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; | |
| 638 | + const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; | |
| 639 | + const driverKind = providerEntry?.driverKind ?? null; | |
| 640 | + const selectedModel = providerEntry?.models.find( | |
| 641 | + (model) => model.slug === thread.modelSelection.model, | |
| 642 | + ); | |
| 643 | + const modelLabel = selectedModel | |
| 644 | + ? getTriggerDisplayModelLabel(selectedModel) | |
| 645 | + : thread.modelSelection.model; | |
| 646 | + | |
| 647 | + const isRemote = | |
| 648 | + props.currentEnvironmentId !== null && thread.environmentId !== props.currentEnvironmentId; | |
| 649 | + | |
| 650 | + const detailsTooltip = ( | |
| 651 | + <SidebarThreadTooltip | |
| 652 | + thread={thread} | |
| 653 | + projectTitle={props.projectTitle} | |
| 654 | + projectCwd={props.projectCwd} | |
| 655 | + environmentLabel={props.environmentLabel} | |
| 656 | + driverKind={driverKind} | |
| 657 | + modelInstanceId={modelInstanceId} | |
| 658 | + modelLabel={modelLabel} | |
| 659 | + branchMismatch={branchMismatch} | |
| 660 | + terminalStatus={terminalStatus} | |
| 661 | + terminalProcessCount={terminalProcessCount} | |
| 662 | + /> | |
| 663 | + ); | |
| 664 | + | |
| 665 | + const handleClick = useCallback( | |
| 666 | + (event: ReactMouseEvent) => { | |
| 667 | + onThreadClick(event, threadRef); | |
| 479 | 668 | }, |
| 480 | − [clearConfirmingArchive], | |
| 669 | + [onThreadClick, threadRef], | |
| 481 | 670 | ); |
| 482 | − const handleRowClick = useCallback( | |
| 483 | − (event: React.MouseEvent) => { | |
| 484 | − handleThreadClick(event, threadRef, orderedProjectThreadKeys); | |
| 485 | − }, | |
| 486 | − [handleThreadClick, orderedProjectThreadKeys, threadRef], | |
| 487 | − ); | |
| 488 | − const handleRowDoubleClick = useCallback( | |
| 489 | − (event: React.MouseEvent) => { | |
| 490 | − // Already renaming this row: a double-click on the row chrome (outside the | |
| 491 | − // input) must not restart and discard the in-progress edit. | |
| 492 | − if (renamingThreadKey === threadKey) return; | |
| 493 | − // On mobile the first tap navigates and closes the sidebar sheet, so the | |
| 494 | − // inline rename can't be shown. Renaming there stays on the context menu. | |
| 495 | − if (isMobile) return; | |
| 496 | − // cmd/ctrl/shift double-clicks are multi-select intent, not rename. | |
| 497 | − if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; | |
| 498 | − // Ignore double-clicks bubbling from nested controls (PR status, port, | |
| 499 | − // archive buttons) — only the row body should enter inline rename. | |
| 500 | − if ((event.target as HTMLElement).closest("button, a")) return; | |
| 671 | + const handleAcknowledgeWokeClick = useCallback( | |
| 672 | + (event: ReactMouseEvent) => { | |
| 501 | 673 | event.preventDefault(); |
| 502 | − startThreadRename(threadKey, thread.title); | |
| 674 | + event.stopPropagation(); | |
| 675 | + if (props.wokeAt === null) return; | |
| 676 | + onAcknowledgeWoke(threadRef, props.wokeAt); | |
| 503 | 677 | }, |
| 504 | − [isMobile, renamingThreadKey, startThreadRename, threadKey, thread.title], | |
| 678 | + [onAcknowledgeWoke, props.wokeAt, threadRef], | |
| 505 | 679 | ); |
| 506 | − const handleRowKeyDown = useCallback( | |
| 507 | − (event: React.KeyboardEvent) => { | |
| 508 | − if (event.key !== "Enter" && event.key !== " ") return; | |
| 680 | + const handleContextMenu = useCallback( | |
| 681 | + (event: ReactMouseEvent) => { | |
| 509 | 682 | event.preventDefault(); |
| 510 | − navigateToThread(threadRef); | |
| 683 | + onContextMenu(threadRef, { x: event.clientX, y: event.clientY }); | |
| 511 | 684 | }, |
| 512 | − [navigateToThread, threadRef], | |
| 685 | + [onContextMenu, threadRef], | |
| 513 | 686 | ); |
| 514 | − const handleRowContextMenu = useCallback( | |
| 515 | − (event: React.MouseEvent) => { | |
| 687 | + const handleKeyDown = useCallback( | |
| 688 | + (event: ReactKeyboardEvent) => { | |
| 689 | + if (event.target !== event.currentTarget) return; | |
| 690 | + if (event.key !== "Enter" && event.key !== " ") return; | |
| 516 | 691 | event.preventDefault(); |
| 517 | − const hasSelection = useThreadSelectionStore.getState().hasSelection(); | |
| 518 | − if (hasSelection && isSelected) { | |
| 519 | − void (async () => { | |
| 520 | − const result = await settlePromise(() => | |
| 521 | − handleMultiSelectContextMenu({ | |
| 522 | − x: event.clientX, | |
| 523 | − y: event.clientY, | |
| 524 | − }), | |
| 525 | − ); | |
| 526 | − if (result._tag === "Failure") { | |
| 527 | − const error = squashAtomCommandFailure(result); | |
| 528 | − toastManager.add( | |
| 529 | − stackedThreadToast({ | |
| 530 | − type: "error", | |
| 531 | − title: "Thread action failed", | |
| 532 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 533 | − }), | |
| 534 | − ); | |
| 535 | − } | |
| 536 | − })(); | |
| 537 | − return; | |
| 538 | − } | |
| 539 | − | |
| 540 | − if (hasSelection) { | |
| 541 | − clearSelection(); | |
| 542 | − } | |
| 543 | − void (async () => { | |
| 544 | − const result = await settlePromise(() => | |
| 545 | − handleThreadContextMenu(threadRef, { | |
| 546 | − x: event.clientX, | |
| 547 | − y: event.clientY, | |
| 548 | − }), | |
| 549 | − ); | |
| 550 | − if (result._tag === "Failure") { | |
| 551 | − const error = squashAtomCommandFailure(result); | |
| 552 | − toastManager.add( | |
| 553 | − stackedThreadToast({ | |
| 554 | − type: "error", | |
| 555 | − title: "Thread action failed", | |
| 556 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 557 | − }), | |
| 558 | − ); | |
| 559 | − } | |
| 560 | − })(); | |
| 692 | + onThreadActivate(threadRef); | |
| 561 | 693 | }, |
| 562 | − [clearSelection, handleMultiSelectContextMenu, handleThreadContextMenu, isSelected, threadRef], | |
| 694 | + [onThreadActivate, threadRef], | |
| 563 | 695 | ); |
| 564 | − const handlePrClick = useCallback( | |
| 565 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 566 | − if (!prStatus) return; | |
| 567 | − openPrLink(event, prStatus.url); | |
| 568 | − }, | |
| 569 | − [openPrLink, prStatus], | |
| 570 | − ); | |
| 571 | − const handleRenameInputRef = useCallback( | |
| 572 | − (element: HTMLInputElement | null) => { | |
| 573 | − if (element && renamingInputRef.current !== element) { | |
| 574 | − renamingInputRef.current = element; | |
| 575 | − element.focus(); | |
| 576 | − element.select(); | |
| 696 | + const handleDoubleClick = useCallback( | |
| 697 | + (event: ReactMouseEvent) => { | |
| 698 | + if (isRenaming || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { | |
| 699 | + return; | |
| 577 | 700 | } |
| 701 | + if ((event.target as HTMLElement).closest("button, a, input")) return; | |
| 702 | + event.preventDefault(); | |
| 703 | + onStartRename(threadRef, thread.title); | |
| 578 | 704 | }, |
| 579 | − [renamingInputRef], | |
| 580 | − ); | |
| 581 | − const handleRenameInputChange = useCallback( | |
| 582 | − (event: React.ChangeEvent<HTMLInputElement>) => { | |
| 583 | − setRenamingTitle(event.target.value); | |
| 584 | − }, | |
| 585 | − [setRenamingTitle], | |
| 705 | + [isRenaming, onStartRename, thread.title, threadRef], | |
| 586 | 706 | ); |
| 587 | − const handleRenameInputKeyDown = useCallback( | |
| 588 | − (event: React.KeyboardEvent<HTMLInputElement>) => { | |
| 707 | + const renameCommittedRef = useRef(false); | |
| 708 | + useEffect(() => { | |
| 709 | + if (isRenaming) renameCommittedRef.current = false; | |
| 710 | + }, [isRenaming]); | |
| 711 | + const handleRenameKeyDown = useCallback( | |
| 712 | + (event: ReactKeyboardEvent<HTMLInputElement>) => { | |
| 589 | 713 | event.stopPropagation(); |
| 590 | 714 | if (event.key === "Enter") { |
| 591 | 715 | event.preventDefault(); |
| 592 | − renamingCommittedRef.current = true; | |
| 593 | − void commitRename(threadRef, renamingTitle, thread.title); | |
| 716 | + renameCommittedRef.current = true; | |
| 717 | + onCommitRename(threadRef, renamingTitle, thread.title); | |
| 594 | 718 | } else if (event.key === "Escape") { |
| 595 | 719 | event.preventDefault(); |
| 596 | − renamingCommittedRef.current = true; | |
| 597 | − cancelRename(); | |
| 720 | + renameCommittedRef.current = true; | |
| 721 | + onCancelRename(); | |
| 598 | 722 | } |
| 599 | 723 | }, |
| 600 | − [cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef], | |
| 724 | + [onCancelRename, onCommitRename, renamingTitle, thread.title, threadRef], | |
| 601 | 725 | ); |
| 602 | − const handleRenameInputBlur = useCallback(() => { | |
| 603 | − if (!renamingCommittedRef.current) { | |
| 604 | − void commitRename(threadRef, renamingTitle, thread.title); | |
| 726 | + const handleRenameBlur = useCallback(() => { | |
| 727 | + if (!renameCommittedRef.current) { | |
| 728 | + onCommitRename(threadRef, renamingTitle, thread.title); | |
| 605 | 729 | } |
| 606 | − }, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]); | |
| 607 | − // Keep clicks/double-clicks inside the rename input from bubbling to the row. | |
| 608 | − // Without stopping `dblclick`, double-clicking to select a word would re-fire | |
| 609 | − // the row's rename handler and reset the in-progress edit back to the title. | |
| 610 | − const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => { | |
| 611 | − event.stopPropagation(); | |
| 612 | − }, []); | |
| 613 | − const handleConfirmArchiveRef = useCallback( | |
| 614 | − (element: HTMLButtonElement | null) => { | |
| 615 | − if (element) { | |
| 616 | − confirmArchiveButtonRefs.current.set(threadKey, element); | |
| 617 | − } else { | |
| 618 | − confirmArchiveButtonRefs.current.delete(threadKey); | |
| 619 | − } | |
| 620 | − }, | |
| 621 | − [confirmArchiveButtonRefs, threadKey], | |
| 622 | − ); | |
| 623 | − const stopPropagationOnPointerDown = useCallback( | |
| 624 | − (event: React.PointerEvent<HTMLButtonElement>) => { | |
| 730 | + }, [onCommitRename, renamingTitle, thread.title, threadRef]); | |
| 731 | + const handleSettleClick = useCallback( | |
| 732 | + (event: ReactMouseEvent) => { | |
| 733 | + event.preventDefault(); | |
| 625 | 734 | event.stopPropagation(); |
| 735 | + onSettle(threadRef); | |
| 626 | 736 | }, |
| 627 | − [], | |
| 737 | + [onSettle, threadRef], | |
| 628 | 738 | ); |
| 629 | − const handleConfirmArchiveClick = useCallback( | |
| 630 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 739 | + const handleUnsettleClick = useCallback( | |
| 740 | + (event: ReactMouseEvent) => { | |
| 631 | 741 | event.preventDefault(); |
| 632 | 742 | event.stopPropagation(); |
| 633 | − clearConfirmingArchive(); | |
| 634 | − void attemptArchiveThread(threadRef); | |
| 743 | + onUnsettle(threadRef); | |
| 635 | 744 | }, |
| 636 | − [attemptArchiveThread, clearConfirmingArchive, threadRef], | |
| 745 | + [onUnsettle, threadRef], | |
| 637 | 746 | ); |
| 638 | − const handleStartArchiveConfirmation = useCallback( | |
| 639 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 747 | + const handleUnsnoozeClick = useCallback( | |
| 748 | + (event: ReactMouseEvent) => { | |
| 640 | 749 | event.preventDefault(); |
| 641 | 750 | event.stopPropagation(); |
| 642 | − setConfirmingArchiveThreadKey(threadKey); | |
| 643 | − requestAnimationFrame(() => { | |
| 644 | − confirmArchiveButtonRefs.current.get(threadKey)?.focus(); | |
| 645 | − }); | |
| 751 | + onUnsnooze(threadRef); | |
| 646 | 752 | }, |
| 647 | − [confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey], | |
| 753 | + [onUnsnooze, threadRef], | |
| 648 | 754 | ); |
| 649 | − const handleArchiveImmediateClick = useCallback( | |
| 650 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 755 | + const handleUnpinClick = useCallback( | |
| 756 | + (event: ReactMouseEvent) => { | |
| 651 | 757 | event.preventDefault(); |
| 652 | 758 | event.stopPropagation(); |
| 653 | − void attemptArchiveThread(threadRef); | |
| 759 | + onUnpin(threadRef); | |
| 654 | 760 | }, |
| 655 | − [attemptArchiveThread, threadRef], | |
| 761 | + [onUnpin, threadRef], | |
| 656 | 762 | ); |
| 657 | − const rowButtonRender = useMemo(() => <div role="button" tabIndex={0} />, []); | |
| 658 | − | |
| 659 | − return ( | |
| 660 | − <SidebarMenuSubItem | |
| 661 | − className="w-full" | |
| 662 | − data-thread-item | |
| 663 | − onMouseLeave={handleMouseLeave} | |
| 664 | − onBlurCapture={handleBlurCapture} | |
| 763 | + const handleSnoozePreset = useCallback( | |
| 764 | + (preset: SnoozePreset) => { | |
| 765 | + onSnooze(threadRef, preset); | |
| 766 | + }, | |
| 767 | + [onSnooze, threadRef], | |
| 768 | + ); | |
| 769 | + // While the snooze popover is open the pointer leaves the row, which | |
| 770 | + // would fade the hover actions out from under the open menu; pin them. | |
| 771 | + const [snoozeMenuOpenRaw, setSnoozeMenuOpen] = useState(false); | |
| 772 | + // Snooze is offered only where it can succeed: capability-gated and never | |
| 773 | + // on blocked-on-you work or queued turns (the server rejects both). | |
| 774 | + const showSnoozeButton = | |
| 775 | + props.snoozeSupported && canSnooze(thread, { now: new Date().toISOString() }); | |
| 776 | + // If the thread becomes blocked while the popover is open, the button | |
| 777 | + // unmounts without firing onOpenChange(false). Deriving the flag keeps a | |
| 778 | + // stale true from permanently hiding the status label / pinning the | |
| 779 | + // hover actions, and the effect clears the raw state so the popover | |
| 780 | + // doesn't resurrect if the button later remounts. | |
| 781 | + const snoozeMenuOpen = snoozeMenuOpenRaw && showSnoozeButton; | |
| 782 | + useEffect(() => { | |
| 783 | + if (!showSnoozeButton) setSnoozeMenuOpen(false); | |
| 784 | + }, [showSnoozeButton]); | |
| 785 | + const handlePrClick = useCallback( | |
| 786 | + (event: ReactMouseEvent<HTMLElement>) => { | |
| 787 | + if (pr?.url) openPrLink(event, pr.url); | |
| 788 | + }, | |
| 789 | + [openPrLink, pr], | |
| 790 | + ); | |
| 791 | + | |
| 792 | + // All sidebar rows share one surface model. Live threads used to look | |
| 793 | + // like elevated cards while settled threads were plain rows, leaving neither | |
| 794 | + // a useful hierarchy nor a reliable hover cue. Status now lives in the row | |
| 795 | + // content; surface is reserved for interaction (hover, multi-select, route). | |
| 796 | + const rowSurfaceClassName = cn( | |
| 797 | + "group/sidebar-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none", | |
| 798 | + props.isActive | |
| 799 | + ? "bg-sidebar-row-active text-sidebar-foreground" | |
| 800 | + : isSelected | |
| 801 | + ? "bg-sidebar-row-selected text-sidebar-foreground" | |
| 802 | + : shouldRecede | |
| 803 | + ? "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 804 | + : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover", | |
| 805 | + isInFlight && | |
| 806 | + !props.isActive && | |
| 807 | + !isSelected && | |
| 808 | + "opacity-70 transition-opacity hover:opacity-100", | |
| 809 | + ); | |
| 810 | + | |
| 811 | + const title = isRenaming ? ( | |
| 812 | + <input | |
| 813 | + autoFocus | |
| 814 | + value={renamingTitle} | |
| 815 | + aria-label="Thread title" | |
| 816 | + onChange={(event) => onRenameTitleChange(event.target.value)} | |
| 817 | + onFocus={(event) => event.currentTarget.select()} | |
| 818 | + onKeyDown={handleRenameKeyDown} | |
| 819 | + onBlur={handleRenameBlur} | |
| 820 | + onClick={(event) => event.stopPropagation()} | |
| 821 | + onDoubleClick={(event) => event.stopPropagation()} | |
| 822 | + className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground" | |
| 823 | + /> | |
| 824 | + ) : ( | |
| 825 | + <span | |
| 826 | + className={cn( | |
| 827 | + "min-w-0 flex-1 text-sm transition-opacity motion-reduce:transition-none", | |
| 828 | + shouldRecede ? "font-normal" : "font-medium", | |
| 829 | + variant === "card" | |
| 830 | + ? cn( | |
| 831 | + "truncate", | |
| 832 | + isUnread || isWoke | |
| 833 | + ? "text-foreground" | |
| 834 | + : shouldRecede | |
| 835 | + ? "text-secondary-label" | |
| 836 | + : status === "failed" | |
| 837 | + ? "text-foreground/95" | |
| 838 | + : "text-foreground/90", | |
| 839 | + ) | |
| 840 | + : cn( | |
| 841 | + "truncate group-hover/sidebar-row:text-foreground", | |
| 842 | + props.isActive || isWoke | |
| 843 | + ? "text-foreground" | |
| 844 | + : isUnread | |
| 845 | + ? "text-muted-foreground" | |
| 846 | + : "text-secondary-label/70", | |
| 847 | + ), | |
| 848 | + isRegeneratingTitle && "opacity-[0.55]", | |
| 849 | + )} | |
| 665 | 850 | > |
| 666 | − <SidebarMenuSubButton | |
| 667 | − render={rowButtonRender} | |
| 668 | − size="sm" | |
| 669 | − isActive={isActive} | |
| 670 | − data-testid={`thread-row-${thread.id}`} | |
| 671 | − className={`${resolveThreadRowClassName({ | |
| 672 | − isActive, | |
| 673 | − isSelected, | |
| 674 | − })} relative isolate`} | |
| 675 | − onClick={handleRowClick} | |
| 676 | − onDoubleClick={handleRowDoubleClick} | |
| 677 | − onKeyDown={handleRowKeyDown} | |
| 678 | − onContextMenu={handleRowContextMenu} | |
| 851 | + {thread.title} | |
| 852 | + </span> | |
| 853 | + ); | |
| 854 | + | |
| 855 | + const prBadge = | |
| 856 | + prStatus && pr ? ( | |
| 857 | + <button | |
| 858 | + type="button" | |
| 859 | + onClick={handlePrClick} | |
| 860 | + className={cn( | |
| 861 | + // Sidebar chrome follows the interface font; tabular digits keep the | |
| 862 | + // number from reflowing as PR states stream in. | |
| 863 | + "shrink-0 text-xs tabular-nums hover:underline", | |
| 864 | + variant === "slim" && variantAction === "unsettle" | |
| 865 | + ? props.isActive | |
| 866 | + ? "text-secondary-label" | |
| 867 | + : cn("text-secondary-label transition-colors", settledPrHoverClass) | |
| 868 | + : prStatus.colorClass, | |
| 869 | + )} | |
| 870 | + aria-label={prStatus.tooltip} | |
| 679 | 871 | > |
| 680 | − <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left"> | |
| 681 | − {prStatus && ( | |
| 682 | − <Tooltip> | |
| 683 | − <TooltipTrigger | |
| 684 | − render={ | |
| 685 | − <button | |
| 686 | − type="button" | |
| 687 | − aria-label={prStatus.tooltip} | |
| 688 | − className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`} | |
| 689 | − onClick={handlePrClick} | |
| 690 | − > | |
| 691 | − <ChangeRequestStatusIcon className="size-3" /> | |
| 692 | − </button> | |
| 693 | − } | |
| 872 | + #{pr.number} | |
| 873 | + </button> | |
| 874 | + ) : null; | |
| 875 | + const terminalStatusIcon = terminalStatus ? ( | |
| 876 | + <span | |
| 877 | + role="img" | |
| 878 | + aria-label={terminalProcessLabel(terminalProcessCount)} | |
| 879 | + data-testid={`sidebar-terminal-status-${thread.id}`} | |
| 880 | + className={cn("inline-flex shrink-0 items-center justify-center", terminalStatus.colorClass)} | |
| 881 | + > | |
| 882 | + <TerminalIcon className={cn("size-3.5", terminalStatus.pulse && "animate-status-pulse")} /> | |
| 883 | + </span> | |
| 884 | + ) : null; | |
| 885 | + | |
| 886 | + if (variant === "slim") { | |
| 887 | + return ( | |
| 888 | + <li | |
| 889 | + data-thread-item | |
| 890 | + className="list-none [content-visibility:auto] [contain-intrinsic-size:auto_34px]" | |
| 891 | + > | |
| 892 | + <Tooltip> | |
| 893 | + <TooltipTrigger | |
| 894 | + render={ | |
| 895 | + <div | |
| 896 | + role="button" | |
| 897 | + tabIndex={0} | |
| 898 | + data-testid="sidebar-row-slim" | |
| 899 | + aria-busy={isRegeneratingTitle || undefined} | |
| 900 | + className={cn(rowSurfaceClassName, "flex h-9 items-center gap-2.5 px-2.5")} | |
| 901 | + onClick={handleClick} | |
| 902 | + onDoubleClick={handleDoubleClick} | |
| 903 | + onKeyDown={handleKeyDown} | |
| 904 | + onContextMenu={handleContextMenu} | |
| 694 | 905 | /> |
| 695 | − <TooltipPopup side="top"> | |
| 696 | − <PrStatusTooltipContent status={prStatus} /> | |
| 697 | − </TooltipPopup> | |
| 698 | − </Tooltip> | |
| 699 | − )} | |
| 700 | − {threadStatus && <ThreadStatusLabel status={threadStatus} />} | |
| 701 | − {renamingThreadKey === threadKey ? ( | |
| 702 | − <input | |
| 703 | − ref={handleRenameInputRef} | |
| 704 | − className="min-w-0 flex-1 truncate rounded border border-ring bg-transparent px-0.5 text-sm outline-none" | |
| 705 | − value={renamingTitle} | |
| 706 | − onChange={handleRenameInputChange} | |
| 707 | − onKeyDown={handleRenameInputKeyDown} | |
| 708 | − onBlur={handleRenameInputBlur} | |
| 709 | − onClick={handleRenameInputClick} | |
| 710 | − onDoubleClick={handleRenameInputClick} | |
| 711 | − /> | |
| 712 | − ) : ( | |
| 713 | − <Tooltip> | |
| 714 | − <TooltipTrigger | |
| 715 | − render={ | |
| 716 | − <span | |
| 717 | − className="min-w-0 flex-1 truncate text-sm" | |
| 718 | − data-testid={`thread-title-${thread.id}`} | |
| 719 | − > | |
| 720 | − {thread.title} | |
| 721 | − </span> | |
| 722 | − } | |
| 906 | + } | |
| 907 | + > | |
| 908 | + {/* Settled history recedes: dimmed favicon at rest, restored on | |
| 909 | + hover so the tail stays scannable when you're hunting. */} | |
| 910 | + <span | |
| 911 | + className={cn( | |
| 912 | + "shrink-0 transition-opacity", | |
| 913 | + !props.isActive && | |
| 914 | + "opacity-40 grayscale group-hover/sidebar-row:opacity-100 group-hover/sidebar-row:grayscale-0", | |
| 915 | + )} | |
| 916 | + > | |
| 917 | + <ProjectFavicon | |
| 918 | + environmentId={thread.environmentId} | |
| 919 | + cwd={props.projectCwd ?? ""} | |
| 920 | + className="size-4" | |
| 921 | + fallbackIcon={MessageSquareIcon} | |
| 723 | 922 | /> |
| 724 | − <TooltipPopup side="top" className="max-w-80 whitespace-normal leading-tight"> | |
| 725 | − {thread.title} | |
| 726 | − </TooltipPopup> | |
| 727 | − </Tooltip> | |
| 728 | − )} | |
| 729 | − </div> | |
| 730 | − <div className="ml-auto flex shrink-0 items-center gap-1.5"> | |
| 731 | − {discoveredPorts.length > 0 && ( | |
| 732 | − <Tooltip> | |
| 733 | − <TooltipTrigger | |
| 734 | − render={ | |
| 923 | + </span> | |
| 924 | + {title} | |
| 925 | + {terminalStatusIcon} | |
| 926 | + {isRegeneratingTitle ? ( | |
| 927 | + <span role="status" className="sr-only"> | |
| 928 | + Regenerating title | |
| 929 | + </span> | |
| 930 | + ) : null} | |
| 931 | + {/* The PR badge stays outside the hover-fading slot: it must | |
| 932 | + remain visible AND clickable while the row is hovered. Only | |
| 933 | + the time/jump label yields to the settle affordance. */} | |
| 934 | + {prBadge} | |
| 935 | + <span className="relative ml-auto flex h-6 min-w-8 shrink-0 items-center justify-end"> | |
| 936 | + <span | |
| 937 | + className={cn( | |
| 938 | + "inline-flex justify-end tabular-nums text-secondary-label transition-opacity", | |
| 939 | + !isWoke && "group-hover/sidebar-row:opacity-0", | |
| 940 | + )} | |
| 941 | + > | |
| 942 | + {variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( | |
| 943 | + // Snoozed rows show when they come BACK, not when they were | |
| 944 | + // last touched — the return ticket is the row's whole story. | |
| 945 | + <span className="text-xs text-blue-600 tabular-nums dark:text-blue-400"> | |
| 946 | + {props.snoozeWakeLabelText} | |
| 947 | + </span> | |
| 948 | + ) : isWoke ? ( | |
| 949 | + // A wake can land straight in the settled tail (e.g. PR | |
| 950 | + // merged while snoozed); the signal must survive the trip. | |
| 735 | 951 | <button |
| 736 | 952 | type="button" |
| 737 | − aria-label={`Open localhost:${discoveredPorts[0]?.port ?? ""}`} | |
| 738 | − className="inline-flex cursor-pointer items-center justify-center text-emerald-600 outline-hidden focus-visible:ring-1 focus-visible:ring-ring dark:text-emerald-400" | |
| 739 | − onClick={handleOpenDiscoveredPort} | |
| 740 | − /> | |
| 741 | − } | |
| 742 | − > | |
| 743 | − <Globe2Icon className="size-3" /> | |
| 744 | − </TooltipTrigger> | |
| 745 | − <TooltipPopup side="top"> | |
| 746 | − Open localhost:{discoveredPorts[0]?.port} | |
| 747 | − {discoveredPorts.length > 1 ? ` (+${discoveredPorts.length - 1})` : ""} | |
| 748 | − </TooltipPopup> | |
| 749 | − </Tooltip> | |
| 750 | − )} | |
| 751 | − <ThreadWorktreeIndicator thread={thread} /> | |
| 752 | − {terminalStatus && ( | |
| 753 | − <Tooltip> | |
| 754 | − <TooltipTrigger | |
| 755 | − render={ | |
| 756 | − <span | |
| 757 | − role="img" | |
| 758 | − aria-label={terminalStatus.label} | |
| 759 | − className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`} | |
| 760 | − /> | |
| 761 | − } | |
| 762 | − > | |
| 763 | − <TerminalIcon | |
| 764 | − className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`} | |
| 765 | − /> | |
| 766 | − </TooltipTrigger> | |
| 767 | − <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup> | |
| 768 | − </Tooltip> | |
| 769 | − )} | |
| 770 | − <div | |
| 771 | − className={`flex min-w-12 justify-end ${ | |
| 772 | − isRemoteThread ? "max-sm:min-w-24" : "max-sm:min-w-20" | |
| 773 | − }`} | |
| 774 | − > | |
| 775 | − {isConfirmingArchive ? ( | |
| 776 | − <button | |
| 777 | − ref={handleConfirmArchiveRef} | |
| 778 | − type="button" | |
| 779 | − data-thread-selection-safe | |
| 780 | − data-testid={`thread-archive-confirm-${thread.id}`} | |
| 781 | − aria-label={`Confirm archive ${thread.title}`} | |
| 782 | − className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-md bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40" | |
| 783 | − onPointerDown={stopPropagationOnPointerDown} | |
| 784 | − onClick={handleConfirmArchiveClick} | |
| 785 | − > | |
| 786 | − Confirm | |
| 787 | − </button> | |
| 788 | − ) : !isThreadRunning ? ( | |
| 789 | − appSettingsConfirmThreadArchive ? ( | |
| 790 | − <div className="pointer-events-none absolute top-1/2 right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100"> | |
| 953 | + aria-label="Dismiss Woke notification" | |
| 954 | + title="Dismiss Woke notification" | |
| 955 | + onClick={handleAcknowledgeWokeClick} | |
| 956 | + className="inline-flex cursor-pointer items-center gap-1 rounded-sm text-xs font-medium text-amber-700 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring dark:text-amber-300" | |
| 957 | + > | |
| 958 | + <AlarmClockIcon aria-hidden className="size-3" /> | |
| 959 | + <span role="status">Woke</span> | |
| 960 | + </button> | |
| 961 | + ) : ( | |
| 962 | + <span className="text-xs"> | |
| 963 | + {variantAction === "unsettle" | |
| 964 | + ? settledTimeLabel(thread) | |
| 965 | + : threadTimeLabel(thread)} | |
| 966 | + </span> | |
| 967 | + )} | |
| 968 | + </span> | |
| 969 | + {variantAction === "unsnooze" ? ( | |
| 970 | + !props.snoozeSupported ? null : ( | |
| 791 | 971 | <button |
| 792 | 972 | type="button" |
| 793 | − data-thread-selection-safe | |
| 794 | − data-testid={`thread-archive-${thread.id}`} | |
| 795 | − aria-label={`Archive ${thread.title}`} | |
| 796 | − className={SIDEBAR_ICON_ACTION_BUTTON_CLASS} | |
| 797 | − onPointerDown={stopPropagationOnPointerDown} | |
| 798 | − onClick={handleStartArchiveConfirmation} | |
| 973 | + aria-label="Wake thread now" | |
| 974 | + onClick={handleUnsnoozeClick} | |
| 975 | + className={cn( | |
| 976 | + "pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100", | |
| 977 | + isWoke && "group-hover/sidebar-row:static", | |
| 978 | + )} | |
| 799 | 979 | > |
| 800 | − <ArchiveIcon className="size-3.5" /> | |
| 980 | + <AlarmClockOffIcon className="size-3" /> | |
| 801 | 981 | </button> |
| 802 | − </div> | |
| 982 | + ) | |
| 983 | + ) : !props.settlementSupported ? null : variantAction === "unsettle" ? ( | |
| 984 | + <button | |
| 985 | + type="button" | |
| 986 | + aria-label="Un-settle thread" | |
| 987 | + onClick={handleUnsettleClick} | |
| 988 | + className={cn( | |
| 989 | + "pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100", | |
| 990 | + isWoke && "group-hover/sidebar-row:static", | |
| 991 | + )} | |
| 992 | + > | |
| 993 | + <Undo2Icon className="mb-px size-3.5" /> | |
| 994 | + </button> | |
| 803 | 995 | ) : ( |
| 804 | − <Tooltip> | |
| 805 | − <TooltipTrigger | |
| 806 | − render={ | |
| 807 | − <div className="pointer-events-none absolute top-1/2 right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100"> | |
| 808 | − <button | |
| 809 | − type="button" | |
| 810 | − data-thread-selection-safe | |
| 811 | − data-testid={`thread-archive-${thread.id}`} | |
| 812 | − aria-label={`Archive ${thread.title}`} | |
| 813 | − className={SIDEBAR_ICON_ACTION_BUTTON_CLASS} | |
| 814 | − onPointerDown={stopPropagationOnPointerDown} | |
| 815 | − onClick={handleArchiveImmediateClick} | |
| 816 | − > | |
| 817 | − <ArchiveIcon className="size-3.5" /> | |
| 818 | − </button> | |
| 819 | − </div> | |
| 820 | − } | |
| 821 | − /> | |
| 822 | − <TooltipPopup side="top">Archive</TooltipPopup> | |
| 823 | − </Tooltip> | |
| 824 | − ) | |
| 825 | − ) : null} | |
| 826 | − <span className={threadMetaClassName}> | |
| 827 | − <span className="inline-flex items-center gap-1"> | |
| 828 | − {isRemoteThread && !isDesktopLocalThread && ( | |
| 829 | − <Tooltip> | |
| 830 | − <TooltipTrigger | |
| 831 | − render={ | |
| 832 | − <span | |
| 833 | − aria-label={threadEnvironmentLabel ?? "Remote"} | |
| 834 | − className="inline-flex items-center justify-center" | |
| 835 | − /> | |
| 836 | − } | |
| 837 | − > | |
| 838 | − <CloudIcon className="size-3 text-muted-foreground/40" /> | |
| 839 | − </TooltipTrigger> | |
| 840 | − <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup> | |
| 841 | − </Tooltip> | |
| 842 | − )} | |
| 843 | − {jumpLabel ? ( | |
| 844 | − <Tooltip> | |
| 845 | − <TooltipTrigger | |
| 846 | − render={ | |
| 847 | − <span | |
| 848 | − aria-label={jumpLabel} | |
| 849 | − className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm" | |
| 850 | − /> | |
| 851 | − } | |
| 852 | − > | |
| 853 | − {jumpLabel} | |
| 854 | − </TooltipTrigger> | |
| 855 | − <TooltipPopup side="top">{jumpLabel}</TooltipPopup> | |
| 856 | − </Tooltip> | |
| 996 | + <button | |
| 997 | + type="button" | |
| 998 | + aria-label="Settle thread" | |
| 999 | + onClick={handleSettleClick} | |
| 1000 | + className={cn( | |
| 1001 | + "pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100", | |
| 1002 | + isWoke && "group-hover/sidebar-row:static", | |
| 1003 | + )} | |
| 1004 | + > | |
| 1005 | + <CheckIcon className="size-3" /> | |
| 1006 | + </button> | |
| 1007 | + )} | |
| 1008 | + </span> | |
| 1009 | + {props.jumpLabel ? <JumpHintBadge label={props.jumpLabel} /> : null} | |
| 1010 | + </TooltipTrigger> | |
| 1011 | + {detailsTooltip} | |
| 1012 | + </Tooltip> | |
| 1013 | + </li> | |
| 1014 | + ); | |
| 1015 | + } | |
| 1016 | + | |
| 1017 | + const diff = latestTurnDiff(thread); | |
| 1018 | + | |
| 1019 | + const sortable = props.sortable; | |
| 1020 | + return ( | |
| 1021 | + <li | |
| 1022 | + data-thread-item | |
| 1023 | + ref={sortable?.setNodeRef} | |
| 1024 | + style={ | |
| 1025 | + sortable | |
| 1026 | + ? { | |
| 1027 | + transform: CSS.Translate.toString(sortable.transform), | |
| 1028 | + transition: sortable.transition, | |
| 1029 | + } | |
| 1030 | + : undefined | |
| 1031 | + } | |
| 1032 | + {...(sortable?.listeners ?? {})} | |
| 1033 | + className={cn( | |
| 1034 | + "list-none py-0.5 [content-visibility:auto] [contain-intrinsic-size:auto_96px]", | |
| 1035 | + sortable?.isDragging && "z-20 opacity-80", | |
| 1036 | + )} | |
| 1037 | + > | |
| 1038 | + <Tooltip> | |
| 1039 | + <TooltipTrigger | |
| 1040 | + render={ | |
| 1041 | + <div | |
| 1042 | + role="button" | |
| 1043 | + tabIndex={0} | |
| 1044 | + data-testid="sidebar-row-card" | |
| 1045 | + aria-busy={isRegeneratingTitle || undefined} | |
| 1046 | + className={rowSurfaceClassName} | |
| 1047 | + onClick={handleClick} | |
| 1048 | + onDoubleClick={handleDoubleClick} | |
| 1049 | + onKeyDown={handleKeyDown} | |
| 1050 | + onContextMenu={handleContextMenu} | |
| 1051 | + /> | |
| 1052 | + } | |
| 1053 | + > | |
| 1054 | + <div className="relative z-10 h-[4.875rem] px-[var(--sidebar-row-content-inset)] py-[var(--sidebar-content-inset)]"> | |
| 1055 | + <div className="flex h-5 min-w-0 items-center gap-1.5"> | |
| 1056 | + <ProjectFavicon | |
| 1057 | + environmentId={thread.environmentId} | |
| 1058 | + cwd={props.projectCwd ?? ""} | |
| 1059 | + className="size-4 shrink-0" | |
| 1060 | + /> | |
| 1061 | + {props.projectTitle ? ( | |
| 1062 | + <span | |
| 1063 | + className={cn( | |
| 1064 | + "min-w-0 flex-1 truncate text-secondary-label text-xs", | |
| 1065 | + shouldRecede ? "font-normal" : "font-medium", | |
| 1066 | + )} | |
| 1067 | + > | |
| 1068 | + {props.projectTitle} | |
| 1069 | + </span> | |
| 1070 | + ) : ( | |
| 1071 | + <span className="flex-1" /> | |
| 1072 | + )} | |
| 1073 | + {props.isPinned ? ( | |
| 1074 | + props.pinningSupported ? ( | |
| 1075 | + <button | |
| 1076 | + type="button" | |
| 1077 | + aria-label="Unpin thread" | |
| 1078 | + title="Unpin thread" | |
| 1079 | + onClick={handleUnpinClick} | |
| 1080 | + className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" | |
| 1081 | + > | |
| 1082 | + <PinIcon aria-hidden className="size-3 shrink-0" /> | |
| 1083 | + </button> | |
| 857 | 1084 | ) : ( |
| 1085 | + <PinIcon | |
| 1086 | + aria-label="Pinned" | |
| 1087 | + role="img" | |
| 1088 | + className="size-3 shrink-0 text-muted-foreground/65" | |
| 1089 | + /> | |
| 1090 | + ) | |
| 1091 | + ) : null} | |
| 1092 | + {/* The visible state owns this slot's width: status at rest, | |
| 1093 | + actions on hover/keyboard focus or while the popover is open. Keeping | |
| 1094 | + the hidden state out of flow lets the project label reclaim | |
| 1095 | + space without either state overlapping it. */} | |
| 1096 | + <span className="group/sidebar-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs"> | |
| 1097 | + {/* Read-only status labels yield to the hover actions. Woke is | |
| 1098 | + itself an action, so it stays pointer-enabled and visible | |
| 1099 | + while the other controls appear beside it. */} | |
| 1100 | + <span | |
| 1101 | + className={cn( | |
| 1102 | + isWokeStatus | |
| 1103 | + ? "pointer-events-auto" | |
| 1104 | + : "pointer-events-none group-has-[:focus-visible]/sidebar-status-slot:absolute group-has-[:focus-visible]/sidebar-status-slot:right-0 group-has-[:focus-visible]/sidebar-status-slot:opacity-0 group-hover/sidebar-row:absolute group-hover/sidebar-row:right-0 group-hover/sidebar-row:opacity-0", | |
| 1105 | + "self-center justify-self-end tabular-nums text-secondary-label transition-opacity", | |
| 1106 | + snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0", | |
| 1107 | + )} | |
| 1108 | + > | |
| 1109 | + {topStatus ? ( | |
| 1110 | + isWokeStatus ? ( | |
| 1111 | + <button | |
| 1112 | + type="button" | |
| 1113 | + aria-label="Dismiss Woke notification" | |
| 1114 | + title="Dismiss Woke notification" | |
| 1115 | + onClick={handleAcknowledgeWokeClick} | |
| 1116 | + className={cn( | |
| 1117 | + "inline-flex cursor-pointer items-center gap-1 rounded-sm font-medium outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring", | |
| 1118 | + topStatus.className, | |
| 1119 | + )} | |
| 1120 | + > | |
| 1121 | + <AlarmClockIcon aria-hidden className="size-4 shrink-0" /> | |
| 1122 | + <span role="status">{topStatus.label}</span> | |
| 1123 | + </button> | |
| 1124 | + ) : ( | |
| 1125 | + <span | |
| 1126 | + className={cn( | |
| 1127 | + "inline-flex items-center gap-1 font-medium", | |
| 1128 | + topStatus.className, | |
| 1129 | + )} | |
| 1130 | + > | |
| 1131 | + {topStatus.icon === "working" ? ( | |
| 1132 | + <CircleDashedIcon aria-hidden className="size-4 shrink-0" /> | |
| 1133 | + ) : topStatus.icon === "done" ? ( | |
| 1134 | + <CircleCheckIcon aria-hidden className="size-4 shrink-0" /> | |
| 1135 | + ) : null} | |
| 1136 | + {/* The label alone is the live region: a role="status" | |
| 1137 | + wrapper around the ticking duration would make | |
| 1138 | + screen readers announce every second. */} | |
| 1139 | + <span role="status">{topStatus.label}</span> | |
| 1140 | + {status === "working" ? ( | |
| 1141 | + <span aria-hidden> | |
| 1142 | + <WorkingDuration startedAt={resolveWorkingStartedAt(thread)} /> | |
| 1143 | + </span> | |
| 1144 | + ) : null} | |
| 1145 | + </span> | |
| 1146 | + ) | |
| 1147 | + ) : ( | |
| 1148 | + threadTimeLabel(thread) | |
| 1149 | + )} | |
| 1150 | + </span> | |
| 1151 | + {props.settlementSupported || showSnoozeButton ? ( | |
| 858 | 1152 | <span |
| 859 | − className={`text-[10px] tabular-nums ${ | |
| 860 | − isHighlighted ? "text-foreground" : "text-secondary-label" | |
| 861 | − }`} | |
| 862 | − > | |
| 863 | − {formatRelativeTimeLabel( | |
| 864 | − thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt, | |
| 1153 | + className={cn( | |
| 1154 | + // focus-visible, not focus-within: a mouse click leaves | |
| 1155 | + // the Settle button focused, and a plain focus-within | |
| 1156 | + // would keep the controls pinned over the status label | |
| 1157 | + // once the pointer moves away (e.g. after a failed | |
| 1158 | + // settle) instead of cross-fading back. | |
| 1159 | + "pointer-events-none absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:static group-hover/sidebar-row:opacity-100", | |
| 1160 | + snoozeMenuOpen && "pointer-events-auto static opacity-100", | |
| 865 | 1161 | )} |
| 1162 | + > | |
| 1163 | + {showSnoozeButton ? ( | |
| 1164 | + <SnoozePopoverButton | |
| 1165 | + open={snoozeMenuOpen} | |
| 1166 | + onOpenChange={setSnoozeMenuOpen} | |
| 1167 | + onSnooze={handleSnoozePreset} | |
| 1168 | + timestampFormat={props.timestampFormat} | |
| 1169 | + /> | |
| 1170 | + ) : null} | |
| 1171 | + {props.settlementSupported ? ( | |
| 1172 | + <button | |
| 1173 | + type="button" | |
| 1174 | + aria-label="Settle thread" | |
| 1175 | + onClick={handleSettleClick} | |
| 1176 | + className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" | |
| 1177 | + > | |
| 1178 | + <CheckIcon className="size-3.5" /> | |
| 1179 | + Settle | |
| 1180 | + </button> | |
| 1181 | + ) : null} | |
| 866 | 1182 | </span> |
| 867 | − )} | |
| 1183 | + ) : null} | |
| 868 | 1184 | </span> |
| 869 | − </span> | |
| 1185 | + </div> | |
| 1186 | + <div className="mt-1 flex min-w-0"> | |
| 1187 | + {title} | |
| 1188 | + {isRegeneratingTitle ? ( | |
| 1189 | + <span role="status" className="sr-only"> | |
| 1190 | + Regenerating title | |
| 1191 | + </span> | |
| 1192 | + ) : null} | |
| 1193 | + </div> | |
| 1194 | + <div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-secondary-label text-xs"> | |
| 1195 | + {/* While working, the current plan step outranks the branch: | |
| 1196 | + it's the one line that says what the thread is doing. */} | |
| 1197 | + {status === "working" && thread.planProgress ? ( | |
| 1198 | + <span className="min-w-0 flex-1 truncate whitespace-nowrap"> | |
| 1199 | + {thread.planProgress.step} | |
| 1200 | + {/* Completed count, matching the transcript chip's n/m. */} | |
| 1201 | + <span className="text-icon-muted tabular-nums"> | |
| 1202 | + {" "} | |
| 1203 | + {thread.planProgress.completedSteps}/{thread.planProgress.totalSteps} | |
| 1204 | + </span> | |
| 1205 | + </span> | |
| 1206 | + ) : thread.branch ? ( | |
| 1207 | + <span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span> | |
| 1208 | + ) : ( | |
| 1209 | + <span className="flex-1" /> | |
| 1210 | + )} | |
| 1211 | + {terminalStatusIcon} | |
| 1212 | + {prBadge} | |
| 1213 | + {diff ? ( | |
| 1214 | + <span className="shrink-0 font-mono"> | |
| 1215 | + <span className="text-emerald-600 dark:text-emerald-400">+{diff.insertions}</span>{" "} | |
| 1216 | + <span className="text-red-600 dark:text-red-400">−{diff.deletions}</span> | |
| 1217 | + </span> | |
| 1218 | + ) : null} | |
| 1219 | + <span | |
| 1220 | + aria-hidden | |
| 1221 | + className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" | |
| 1222 | + > | |
| 1223 | + {isRemote ? ( | |
| 1224 | + <span className="inline-flex shrink-0 items-center text-sidebar-muted-foreground/70"> | |
| 1225 | + <ServerIcon aria-hidden className="size-3.5" /> | |
| 1226 | + </span> | |
| 1227 | + ) : null} | |
| 1228 | + {driverKind ? ( | |
| 1229 | + <span className="inline-flex shrink-0 items-center opacity-60"> | |
| 1230 | + <ProviderInstanceIcon | |
| 1231 | + driverKind={driverKind} | |
| 1232 | + displayName={thread.session?.providerName ?? modelInstanceId} | |
| 1233 | + iconClassName="size-3.5" | |
| 1234 | + /> | |
| 1235 | + </span> | |
| 1236 | + ) : null} | |
| 1237 | + </span> | |
| 1238 | + </div> | |
| 870 | 1239 | </div> |
| 871 | − </div> | |
| 872 | − </SidebarMenuSubButton> | |
| 873 | − </SidebarMenuSubItem> | |
| 1240 | + {props.jumpLabel ? <JumpHintBadge label={props.jumpLabel} /> : null} | |
| 1241 | + </TooltipTrigger> | |
| 1242 | + {detailsTooltip} | |
| 1243 | + </Tooltip> | |
| 1244 | + </li> | |
| 874 | 1245 | ); |
| 875 | 1246 | }); |
| 876 | 1247 | |
| 877 | −interface SidebarProjectThreadListProps { | |
| 878 | − projectKey: string; | |
| 879 | − projectExpanded: boolean; | |
| 880 | − hasOverflowingThreads: boolean; | |
| 881 | − hiddenThreadStatus: ThreadStatusPill | null; | |
| 882 | − orderedProjectThreadKeys: readonly string[]; | |
| 883 | − renderedThreads: readonly SidebarThreadSummary[]; | |
| 884 | − showEmptyThreadState: boolean; | |
| 885 | − shouldShowThreadPanel: boolean; | |
| 886 | − isThreadListExpanded: boolean; | |
| 887 | − projectCwd: string; | |
| 888 | − activeRouteThreadKey: string | null; | |
| 889 | − threadJumpLabelByKey: ReadonlyMap<string, string>; | |
| 890 | − appSettingsConfirmThreadArchive: boolean; | |
| 891 | − renamingThreadKey: string | null; | |
| 892 | − renamingTitle: string; | |
| 893 | − setRenamingTitle: (title: string) => void; | |
| 894 | − startThreadRename: (threadKey: string, title: string) => void; | |
| 895 | − renamingInputRef: React.RefObject<HTMLInputElement | null>; | |
| 896 | − renamingCommittedRef: React.RefObject<boolean>; | |
| 897 | − confirmingArchiveThreadKey: string | null; | |
| 898 | − setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>; | |
| 899 | − confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>; | |
| 900 | − attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; | |
| 901 | − handleThreadClick: ( | |
| 902 | − event: React.MouseEvent, | |
| 903 | − threadRef: ScopedThreadRef, | |
| 904 | − orderedProjectThreadKeys: readonly string[], | |
| 905 | − ) => void; | |
| 906 | − navigateToThread: (threadRef: ScopedThreadRef) => void; | |
| 907 | − handleMultiSelectContextMenu: (position: { x: number; y: number }) => Promise<void>; | |
| 908 | − handleThreadContextMenu: ( | |
| 909 | − threadRef: ScopedThreadRef, | |
| 910 | − position: { x: number; y: number }, | |
| 911 | − ) => Promise<void>; | |
| 912 | − clearSelection: () => void; | |
| 913 | − commitRename: ( | |
| 914 | − threadRef: ScopedThreadRef, | |
| 915 | − newTitle: string, | |
| 916 | − originalTitle: string, | |
| 917 | − ) => Promise<void>; | |
| 918 | − cancelRename: () => void; | |
| 919 | − attemptArchiveThread: (threadRef: ScopedThreadRef) => Promise<void>; | |
| 920 | − openPrLink: (event: React.MouseEvent<HTMLElement>, prUrl: string) => void; | |
| 921 | − expandThreadListForProject: (projectKey: string) => void; | |
| 922 | − collapseThreadListForProject: (projectKey: string) => void; | |
| 1248 | +function latestTurnDiff( | |
| 1249 | + thread: SidebarThreadSummary, | |
| 1250 | +): { insertions: number; deletions: number } | null { | |
| 1251 | + // Shells don't carry checkpoint summaries; diff stats render only when the | |
| 1252 | + // shell projection grows them. Kept as a seam so the row layout is ready. | |
| 1253 | + void thread; | |
| 1254 | + return null; | |
| 923 | 1255 | } |
| 924 | 1256 | |
| 925 | −const SidebarProjectThreadList = memo(function SidebarProjectThreadList( | |
| 926 | − props: SidebarProjectThreadListProps, | |
| 927 | −) { | |
| 928 | − const { | |
| 929 | − projectKey, | |
| 930 | − projectExpanded, | |
| 931 | − hasOverflowingThreads, | |
| 932 | − hiddenThreadStatus, | |
| 933 | − orderedProjectThreadKeys, | |
| 934 | − renderedThreads, | |
| 935 | − showEmptyThreadState, | |
| 936 | − shouldShowThreadPanel, | |
| 937 | − isThreadListExpanded, | |
| 938 | − projectCwd, | |
| 939 | − activeRouteThreadKey, | |
| 940 | − threadJumpLabelByKey, | |
| 941 | − appSettingsConfirmThreadArchive, | |
| 942 | − renamingThreadKey, | |
| 943 | − renamingTitle, | |
| 944 | − setRenamingTitle, | |
| 945 | − startThreadRename, | |
| 946 | − renamingInputRef, | |
| 947 | − renamingCommittedRef, | |
| 948 | − confirmingArchiveThreadKey, | |
| 949 | − setConfirmingArchiveThreadKey, | |
| 950 | − confirmArchiveButtonRefs, | |
| 951 | − attachThreadListAutoAnimateRef, | |
| 952 | − handleThreadClick, | |
| 953 | − navigateToThread, | |
| 954 | − handleMultiSelectContextMenu, | |
| 955 | − handleThreadContextMenu, | |
| 956 | − clearSelection, | |
| 957 | − commitRename, | |
| 958 | − cancelRename, | |
| 959 | − attemptArchiveThread, | |
| 960 | − openPrLink, | |
| 961 | − expandThreadListForProject, | |
| 962 | − collapseThreadListForProject, | |
| 963 | − } = props; | |
| 964 | − const showMoreButtonRender = useMemo(() => <button type="button" />, []); | |
| 965 | − const showLessButtonRender = useMemo(() => <button type="button" />, []); | |
| 966 | − | |
| 1257 | +const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { | |
| 1258 | + thread: SidebarThreadSummary; | |
| 1259 | + projectCwd: string | null; | |
| 1260 | + projectTitle: string | null; | |
| 1261 | + environmentLabel: string | null; | |
| 1262 | + providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>; | |
| 1263 | + isHighlighted: boolean; | |
| 1264 | + isRouteActive: boolean; | |
| 1265 | + resultId: string; | |
| 1266 | + onHighlight: () => void; | |
| 1267 | + onSelect: () => void; | |
| 1268 | +}) { | |
| 1269 | + const { thread } = props; | |
| 1270 | + // Same details tooltip as the regular rows: a search hit is still a thread, | |
| 1271 | + // and the hover card is how you disambiguate identically-titled results. | |
| 1272 | + const gitCwd = thread.worktreePath ?? props.projectCwd; | |
| 1273 | + const gitStatus = useEnvironmentQuery( | |
| 1274 | + (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null | |
| 1275 | + ? vcsEnvironment.status({ | |
| 1276 | + environmentId: thread.environmentId, | |
| 1277 | + input: { cwd: gitCwd }, | |
| 1278 | + }) | |
| 1279 | + : null, | |
| 1280 | + ); | |
| 1281 | + const branchMismatch = resolveLocalCheckoutBranchMismatch({ | |
| 1282 | + effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", | |
| 1283 | + activeWorktreePath: thread.worktreePath, | |
| 1284 | + activeThreadBranch: thread.branch, | |
| 1285 | + currentGitBranch: gitStatus.data?.refName ?? null, | |
| 1286 | + }); | |
| 1287 | + const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; | |
| 1288 | + const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; | |
| 1289 | + const driverKind = providerEntry?.driverKind ?? null; | |
| 1290 | + const selectedModel = providerEntry?.models.find( | |
| 1291 | + (model) => model.slug === thread.modelSelection.model, | |
| 1292 | + ); | |
| 1293 | + const modelLabel = selectedModel | |
| 1294 | + ? getTriggerDisplayModelLabel(selectedModel) | |
| 1295 | + : thread.modelSelection.model; | |
| 1296 | + const runningTerminalIds = useThreadRunningTerminalIds({ | |
| 1297 | + environmentId: thread.environmentId, | |
| 1298 | + threadId: thread.id, | |
| 1299 | + }); | |
| 1300 | + const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); | |
| 967 | 1301 | return ( |
| 968 | − <SidebarMenuSub | |
| 969 | − ref={attachThreadListAutoAnimateRef} | |
| 970 | − className="mx-0.5 my-0 w-full translate-x-0 gap-0.5 overflow-hidden border-l-0 px-1 py-0 sm:mx-1 sm:px-1.5" | |
| 971 | − > | |
| 972 | − {shouldShowThreadPanel && showEmptyThreadState ? ( | |
| 973 | − <SidebarMenuSubItem className="w-full" data-thread-selection-safe> | |
| 974 | − <div | |
| 975 | − data-thread-selection-safe | |
| 976 | − className="flex h-8 w-full translate-x-0 items-center px-2 text-left text-xs text-sidebar-muted-foreground/75" | |
| 977 | − > | |
| 978 | − <span>No threads yet</span> | |
| 979 | − </div> | |
| 980 | − </SidebarMenuSubItem> | |
| 981 | − ) : null} | |
| 982 | − {shouldShowThreadPanel && | |
| 983 | − renderedThreads.map((thread) => { | |
| 984 | − const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); | |
| 985 | − return ( | |
| 986 | − <SidebarThreadRow | |
| 987 | − key={threadKey} | |
| 988 | − thread={thread} | |
| 989 | − projectCwd={projectCwd} | |
| 990 | − orderedProjectThreadKeys={orderedProjectThreadKeys} | |
| 991 | − isActive={activeRouteThreadKey === threadKey} | |
| 992 | − jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null} | |
| 993 | − appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive} | |
| 994 | − renamingThreadKey={renamingThreadKey} | |
| 995 | − renamingTitle={renamingTitle} | |
| 996 | − setRenamingTitle={setRenamingTitle} | |
| 997 | − startThreadRename={startThreadRename} | |
| 998 | − renamingInputRef={renamingInputRef} | |
| 999 | − renamingCommittedRef={renamingCommittedRef} | |
| 1000 | − confirmingArchiveThreadKey={confirmingArchiveThreadKey} | |
| 1001 | − setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey} | |
| 1002 | − confirmArchiveButtonRefs={confirmArchiveButtonRefs} | |
| 1003 | − handleThreadClick={handleThreadClick} | |
| 1004 | − navigateToThread={navigateToThread} | |
| 1005 | − handleMultiSelectContextMenu={handleMultiSelectContextMenu} | |
| 1006 | − handleThreadContextMenu={handleThreadContextMenu} | |
| 1007 | − clearSelection={clearSelection} | |
| 1008 | − commitRename={commitRename} | |
| 1009 | − cancelRename={cancelRename} | |
| 1010 | − attemptArchiveThread={attemptArchiveThread} | |
| 1011 | − openPrLink={openPrLink} | |
| 1302 | + <li role="presentation" className="list-none"> | |
| 1303 | + <Tooltip> | |
| 1304 | + <TooltipTrigger | |
| 1305 | + render={ | |
| 1306 | + <button | |
| 1307 | + id={props.resultId} | |
| 1308 | + type="button" | |
| 1309 | + role="option" | |
| 1310 | + // aria-activedescendant options: focus stays on the search input, | |
| 1311 | + // which owns all keyboard interaction for the listbox. | |
| 1312 | + tabIndex={-1} | |
| 1313 | + aria-selected={props.isHighlighted} | |
| 1314 | + aria-current={props.isRouteActive ? "page" : undefined} | |
| 1315 | + aria-label={ | |
| 1316 | + props.projectTitle ? `${thread.title}, ${props.projectTitle}` : thread.title | |
| 1317 | + } | |
| 1318 | + onMouseMove={props.onHighlight} | |
| 1319 | + onClick={props.onSelect} | |
| 1320 | + className={cn( | |
| 1321 | + "flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm outline-none", | |
| 1322 | + props.isHighlighted || props.isRouteActive | |
| 1323 | + ? "bg-sidebar-row-active text-sidebar-foreground" | |
| 1324 | + : "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground", | |
| 1325 | + )} | |
| 1012 | 1326 | /> |
| 1013 | − ); | |
| 1014 | − })} | |
| 1015 | − | |
| 1016 | − {projectExpanded && hasOverflowingThreads && !isThreadListExpanded && ( | |
| 1017 | − <SidebarMenuSubItem className="w-full"> | |
| 1018 | − <SidebarMenuSubButton | |
| 1019 | − render={showMoreButtonRender} | |
| 1020 | − data-thread-selection-safe | |
| 1021 | − size="sm" | |
| 1022 | − className="h-8 w-full translate-x-0 justify-start px-2 text-left text-xs text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 1023 | − onClick={() => { | |
| 1024 | − expandThreadListForProject(projectKey); | |
| 1025 | − }} | |
| 1026 | − > | |
| 1027 | − <span className="flex min-w-0 flex-1 items-center gap-2"> | |
| 1028 | − {hiddenThreadStatus && <ThreadStatusLabel status={hiddenThreadStatus} compact />} | |
| 1029 | − <span>Show more</span> | |
| 1030 | − </span> | |
| 1031 | − </SidebarMenuSubButton> | |
| 1032 | − </SidebarMenuSubItem> | |
| 1033 | − )} | |
| 1034 | − {projectExpanded && hasOverflowingThreads && isThreadListExpanded && ( | |
| 1035 | − <SidebarMenuSubItem className="w-full"> | |
| 1036 | − <SidebarMenuSubButton | |
| 1037 | − render={showLessButtonRender} | |
| 1038 | − data-thread-selection-safe | |
| 1039 | − size="sm" | |
| 1040 | − className="h-8 w-full translate-x-0 justify-start px-2 text-left text-xs text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 1041 | − onClick={() => { | |
| 1042 | − collapseThreadListForProject(projectKey); | |
| 1043 | − }} | |
| 1044 | − > | |
| 1045 | − <span>Show less</span> | |
| 1046 | − </SidebarMenuSubButton> | |
| 1047 | − </SidebarMenuSubItem> | |
| 1048 | − )} | |
| 1049 | − </SidebarMenuSub> | |
| 1327 | + } | |
| 1328 | + > | |
| 1329 | + <ProjectFavicon | |
| 1330 | + environmentId={thread.environmentId} | |
| 1331 | + cwd={props.projectCwd ?? ""} | |
| 1332 | + className="size-4 shrink-0" | |
| 1333 | + fallbackIcon={MessageSquareIcon} | |
| 1334 | + /> | |
| 1335 | + <span className="min-w-0 flex-1 truncate">{thread.title}</span> | |
| 1336 | + <span className="shrink-0 text-xs text-muted-foreground/55 tabular-nums"> | |
| 1337 | + {threadTimeLabel(thread)} | |
| 1338 | + </span> | |
| 1339 | + </TooltipTrigger> | |
| 1340 | + <SidebarThreadTooltip | |
| 1341 | + thread={thread} | |
| 1342 | + projectTitle={props.projectTitle} | |
| 1343 | + projectCwd={props.projectCwd} | |
| 1344 | + environmentLabel={props.environmentLabel} | |
| 1345 | + driverKind={driverKind} | |
| 1346 | + modelInstanceId={modelInstanceId} | |
| 1347 | + modelLabel={modelLabel} | |
| 1348 | + branchMismatch={branchMismatch} | |
| 1349 | + terminalStatus={terminalStatus} | |
| 1350 | + terminalProcessCount={runningTerminalIds.length} | |
| 1351 | + /> | |
| 1352 | + </Tooltip> | |
| 1353 | + </li> | |
| 1050 | 1354 | ); |
| 1051 | 1355 | }); |
| 1052 | 1356 | |
| 1053 | −interface SidebarProjectItemProps { | |
| 1054 | − project: SidebarProjectSnapshot; | |
| 1055 | − isThreadListExpanded: boolean; | |
| 1056 | − activeRouteThreadKey: string | null; | |
| 1057 | − newThreadShortcutLabel: string | null; | |
| 1058 | − handleNewThread: ReturnType<typeof useNewThreadHandler>; | |
| 1059 | − archiveThread: ReturnType<typeof useThreadActions>["archiveThread"]; | |
| 1060 | − deleteThread: ReturnType<typeof useThreadActions>["deleteThread"]; | |
| 1061 | − threadJumpLabelByKey: ReadonlyMap<string, string>; | |
| 1062 | − attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; | |
| 1063 | − expandThreadListForProject: (projectKey: string) => void; | |
| 1064 | − collapseThreadListForProject: (projectKey: string) => void; | |
| 1065 | − dragInProgressRef: React.RefObject<boolean>; | |
| 1066 | − suppressProjectClickAfterDragRef: React.RefObject<boolean>; | |
| 1067 | − suppressProjectClickForContextMenuRef: React.RefObject<boolean>; | |
| 1068 | − isManualProjectSorting: boolean; | |
| 1069 | − dragHandleProps: SortableProjectHandleProps | null; | |
| 1070 | −} | |
| 1071 | − | |
| 1072 | −const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjectItemProps) { | |
| 1357 | +export default function Sidebar() { | |
| 1358 | + const projects = useProjects(); | |
| 1359 | + const projectOrder = useUiStateStore((store) => store.projectOrder); | |
| 1360 | + const threads = useThreadShells(); | |
| 1361 | + const router = useRouter(); | |
| 1362 | + const { isMobile, setOpenMobile } = useSidebar(); | |
| 1363 | + const keybindings = useAtomValue(primaryServerKeybindingsAtom); | |
| 1364 | + const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays); | |
| 1365 | + const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); | |
| 1366 | + const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); | |
| 1367 | + const timestampFormat = useClientSettings((s) => s.timestampFormat); | |
| 1368 | + const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); | |
| 1073 | 1369 | const { |
| 1074 | − project, | |
| 1075 | − isThreadListExpanded, | |
| 1076 | − activeRouteThreadKey, | |
| 1077 | − newThreadShortcutLabel, | |
| 1078 | − handleNewThread, | |
| 1079 | − archiveThread, | |
| 1370 | + settleThread, | |
| 1371 | + unsettleThread, | |
| 1372 | + snoozeThread, | |
| 1373 | + unsnoozeThread, | |
| 1374 | + pinThread, | |
| 1375 | + unpinThread, | |
| 1376 | + reorderPinnedThread, | |
| 1080 | 1377 | deleteThread, |
| 1081 | − threadJumpLabelByKey, | |
| 1082 | − attachThreadListAutoAnimateRef, | |
| 1083 | − expandThreadListForProject, | |
| 1084 | − collapseThreadListForProject, | |
| 1085 | − dragInProgressRef, | |
| 1086 | − suppressProjectClickAfterDragRef, | |
| 1087 | − suppressProjectClickForContextMenuRef, | |
| 1088 | − isManualProjectSorting, | |
| 1089 | − dragHandleProps, | |
| 1090 | − } = props; | |
| 1091 | − const threadSortOrder = useClientSettings<SidebarThreadSortOrder>( | |
| 1092 | − (settings) => settings.sidebarThreadSortOrder, | |
| 1093 | − ); | |
| 1094 | − const appSettingsConfirmThreadDelete = useClientSettings<boolean>( | |
| 1095 | − (settings) => settings.confirmThreadDelete, | |
| 1096 | − ); | |
| 1097 | − const appSettingsConfirmThreadArchive = useClientSettings<boolean>( | |
| 1098 | − (settings) => settings.confirmThreadArchive, | |
| 1099 | − ); | |
| 1100 | − const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); | |
| 1101 | − const deleteProject = useAtomCommand(projectEnvironment.delete, { | |
| 1378 | + } = useThreadActions(); | |
| 1379 | + const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { | |
| 1102 | 1380 | reportFailure: false, |
| 1103 | 1381 | }); |
| 1104 | − const updateProject = useAtomCommand(projectEnvironment.update, { | |
| 1382 | + const deleteProject = useAtomCommand(projectEnvironment.delete, { | |
| 1105 | 1383 | reportFailure: false, |
| 1106 | 1384 | }); |
| 1107 | − const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { | |
| 1385 | + const updateProject = useAtomCommand(projectEnvironment.update, { | |
| 1108 | 1386 | reportFailure: false, |
| 1109 | 1387 | }); |
| 1110 | 1388 | const updateSettings = useUpdateClientSettings(); |
| 1111 | − const sidebarThreadPreviewCount = useClientSettings<SidebarThreadPreviewCount>( | |
| 1112 | − (settings) => settings.sidebarThreadPreviewCount, | |
| 1113 | − ); | |
| 1114 | − const router = useRouter(); | |
| 1115 | − const { isMobile, setOpenMobile } = useSidebar(); | |
| 1116 | − const markThreadUnread = useUiStateStore((state) => state.markThreadUnread); | |
| 1117 | − const setProjectExpanded = useUiStateStore((state) => state.setProjectExpanded); | |
| 1118 | − const toggleThreadSelection = useThreadSelectionStore((state) => state.toggleThread); | |
| 1119 | − const rangeSelectTo = useThreadSelectionStore((state) => state.rangeSelectTo); | |
| 1120 | − const clearSelection = useThreadSelectionStore((state) => state.clearSelection); | |
| 1121 | − const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection); | |
| 1122 | − const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor); | |
| 1123 | − const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ | |
| 1124 | − threadId: ThreadId; | |
| 1125 | − }>({ | |
| 1126 | − onCopy: (ctx) => { | |
| 1389 | + const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ | |
| 1390 | + onCopy: ({ path }) => { | |
| 1127 | 1391 | toastManager.add({ |
| 1128 | 1392 | type: "success", |
| 1129 | − title: "Thread ID copied", | |
| 1130 | − description: ctx.threadId, | |
| 1393 | + title: "Path copied", | |
| 1394 | + description: path, | |
| 1131 | 1395 | }); |
| 1132 | 1396 | }, |
| 1133 | 1397 | onError: (error) => { |
| 1134 | 1398 | toastManager.add( |
| 1135 | 1399 | stackedThreadToast({ |
| 1136 | 1400 | type: "error", |
| 1137 | − title: "Failed to copy thread ID", | |
| 1401 | + title: "Failed to copy path", | |
| 1138 | 1402 | description: error instanceof Error ? error.message : "An error occurred.", |
| 1139 | 1403 | }), |
| 1140 | 1404 | ); |
| 1141 | 1405 | }, |
| 1142 | 1406 | }); |
| 1143 | − const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ | |
| 1144 | − path: string; | |
| 1145 | − }>({ | |
| 1146 | − onCopy: (ctx) => { | |
| 1407 | + const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({ | |
| 1408 | + target: "branch name", | |
| 1409 | + onCopy: ({ branch }) => { | |
| 1147 | 1410 | toastManager.add({ |
| 1148 | 1411 | type: "success", |
| 1149 | − title: "Path copied", | |
| 1150 | − description: ctx.path, | |
| 1412 | + title: "Branch copied", | |
| 1413 | + description: branch, | |
| 1151 | 1414 | }); |
| 1152 | 1415 | }, |
| 1153 | 1416 | onError: (error) => { |
| 1154 | 1417 | toastManager.add( |
| 1155 | 1418 | stackedThreadToast({ |
| 1156 | 1419 | type: "error", |
| 1157 | − title: "Failed to copy path", | |
| 1420 | + title: "Failed to copy branch", | |
| 1158 | 1421 | description: error instanceof Error ? error.message : "An error occurred.", |
| 1159 | 1422 | }), |
| 1160 | 1423 | ); |
| 1161 | 1424 | }, |
| 1162 | 1425 | }); |
| 1163 | − const openPrLink = useOpenPrLink(); | |
| 1164 | − const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs); | |
| 1165 | − const sidebarThreadByKey = useMemo( | |
| 1426 | + const [projectActionsTarget, setProjectActionsTarget] = useState<SidebarProjectSnapshot | null>( | |
| 1427 | + null, | |
| 1428 | + ); | |
| 1429 | + const [projectScopeMenuOpen, setProjectScopeMenuOpen] = useState(false); | |
| 1430 | + const newThreadContext = useHandleNewThread(); | |
| 1431 | + const openAddProjectCommandPalette = useCallback( | |
| 1432 | + () => openCommandPalette({ open: "add-project" }), | |
| 1433 | + [], | |
| 1434 | + ); | |
| 1435 | + const { environments } = useEnvironments(); | |
| 1436 | + const primaryEnvironmentId = usePrimaryEnvironmentId(); | |
| 1437 | + const clearSelection = useThreadSelectionStore((s) => s.clearSelection); | |
| 1438 | + const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); | |
| 1439 | + const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); | |
| 1440 | + const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo); | |
| 1441 | + const markThreadUnread = useUiStateStore((s) => s.markThreadUnread); | |
| 1442 | + const markThreadVisited = useUiStateStore((s) => s.markThreadVisited); | |
| 1443 | + const acknowledgeWoke = useCallback( | |
| 1444 | + (threadRef: ScopedThreadRef, visitedAt: string) => { | |
| 1445 | + markThreadVisited(scopedThreadKey(threadRef), visitedAt); | |
| 1446 | + }, | |
| 1447 | + [markThreadVisited], | |
| 1448 | + ); | |
| 1449 | + const routeTarget = useParams({ | |
| 1450 | + strict: false, | |
| 1451 | + select: (params) => resolveThreadRouteTarget(params), | |
| 1452 | + }); | |
| 1453 | + const routeDraftThread = useComposerDraftStore((store) => | |
| 1454 | + routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null, | |
| 1455 | + ); | |
| 1456 | + const routeThreadRef = useMemo( | |
| 1457 | + () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread), | |
| 1458 | + [routeDraftThread, routeTarget], | |
| 1459 | + ); | |
| 1460 | + const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; | |
| 1461 | + const routeTargetRef = useRef(routeTarget); | |
| 1462 | + routeTargetRef.current = routeTarget; | |
| 1463 | + // Post-settle navigation validates against the CURRENT route, not the one | |
| 1464 | + // captured when the settle started: if the user navigated elsewhere while | |
| 1465 | + // the command was in flight, completing it must not yank them away. | |
| 1466 | + const routeThreadKeyRef = useRef(routeThreadKey); | |
| 1467 | + routeThreadKeyRef.current = routeThreadKey; | |
| 1468 | + | |
| 1469 | + const environmentLabelById = useMemo( | |
| 1166 | 1470 | () => |
| 1167 | 1471 | new Map( |
| 1168 | − sidebarThreads.map( | |
| 1169 | − (thread) => | |
| 1170 | − [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, | |
| 1171 | − ), | |
| 1172 | − ), | |
| 1173 | − [sidebarThreads], | |
| 1174 | − ); | |
| 1175 | − // Keep a ref so callbacks can read the latest map without appearing in | |
| 1176 | − // dependency arrays (avoids invalidating every thread-row memo on each | |
| 1177 | − // thread-list change). | |
| 1178 | − const sidebarThreadByKeyRef = useRef(sidebarThreadByKey); | |
| 1179 | − sidebarThreadByKeyRef.current = sidebarThreadByKey; | |
| 1180 | − const projectThreads = sidebarThreads; | |
| 1181 | − const projectPreferenceKeys = useMemo(() => projectExpansionPreferenceKeys(project), [project]); | |
| 1182 | − const projectExpanded = useUiStateStore((state) => | |
| 1183 | − resolveProjectExpanded(state.projectExpandedById, projectPreferenceKeys), | |
| 1184 | − ); | |
| 1185 | − const threadLastVisitedAts = useUiStateStore( | |
| 1186 | − useShallow((state) => | |
| 1187 | − projectThreads.map( | |
| 1188 | − (thread) => | |
| 1189 | − state.threadLastVisitedAtById[ | |
| 1190 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) | |
| 1191 | − ] ?? null, | |
| 1472 | + environments.map((environment) => [environment.environmentId, environment.label] as const), | |
| 1192 | 1473 | ), |
| 1193 | − ), | |
| 1474 | + [environments], | |
| 1194 | 1475 | ); |
| 1195 | − const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null); | |
| 1196 | − const [renamingTitle, setRenamingTitle] = useState(""); | |
| 1197 | − const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null); | |
| 1198 | − const [projectRenameTarget, setProjectRenameTarget] = useState<SidebarProjectGroupMember | null>( | |
| 1199 | − null, | |
| 1476 | + const orderedProjects = useMemo( | |
| 1477 | + () => | |
| 1478 | + orderItemsByPreferredIds({ | |
| 1479 | + items: projects, | |
| 1480 | + preferredIds: projectOrder, | |
| 1481 | + getId: getProjectOrderKey, | |
| 1482 | + getPreferenceIds: (project) => [ | |
| 1483 | + getProjectOrderKey(project), | |
| 1484 | + legacyProjectCwdPreferenceKey(project.workspaceRoot), | |
| 1485 | + ], | |
| 1486 | + }), | |
| 1487 | + [projectOrder, projects], | |
| 1488 | + ); | |
| 1489 | + const unsortedProjectGroups = useMemo( | |
| 1490 | + () => | |
| 1491 | + buildSidebarProjectSnapshots({ | |
| 1492 | + projects: sidebarProjectSortOrder === "manual" ? orderedProjects : projects, | |
| 1493 | + settings: projectGroupingSettings, | |
| 1494 | + primaryEnvironmentId, | |
| 1495 | + resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, | |
| 1496 | + }), | |
| 1497 | + [ | |
| 1498 | + environmentLabelById, | |
| 1499 | + orderedProjects, | |
| 1500 | + primaryEnvironmentId, | |
| 1501 | + projectGroupingSettings, | |
| 1502 | + projects, | |
| 1503 | + sidebarProjectSortOrder, | |
| 1504 | + ], | |
| 1200 | 1505 | ); |
| 1201 | − const [projectRenameTitle, setProjectRenameTitle] = useState(""); | |
| 1202 | − const [projectGroupingTarget, setProjectGroupingTarget] = | |
| 1203 | − useState<SidebarProjectGroupMember | null>(null); | |
| 1204 | − const [projectGroupingSelection, setProjectGroupingSelection] = useState< | |
| 1205 | − SidebarProjectGroupingMode | "inherit" | |
| 1206 | − >("inherit"); | |
| 1207 | − const renamingCommittedRef = useRef(false); | |
| 1208 | − const renamingInputRef = useRef<HTMLInputElement | null>(null); | |
| 1209 | − const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>()); | |
| 1210 | − const memberProjectByScopedKey = useMemo( | |
| 1506 | + const projectGroups = useMemo( | |
| 1507 | + () => sortLogicalProjectsForSidebar(unsortedProjectGroups, threads, sidebarProjectSortOrder), | |
| 1508 | + [sidebarProjectSortOrder, threads, unsortedProjectGroups], | |
| 1509 | + ); | |
| 1510 | + const serverProviders = useAtomValue(primaryServerProvidersAtom); | |
| 1511 | + const providerEntryByInstanceId = useMemo( | |
| 1512 | + () => | |
| 1513 | + new Map( | |
| 1514 | + deriveProviderInstanceEntries(serverProviders).map( | |
| 1515 | + (entry) => [entry.instanceId as string, entry] as const, | |
| 1516 | + ), | |
| 1517 | + ), | |
| 1518 | + [serverProviders], | |
| 1519 | + ); | |
| 1520 | + const projectCwdByKey = useMemo( | |
| 1211 | 1521 | () => |
| 1212 | 1522 | new Map( |
| 1213 | − project.memberProjects.map((member) => [ | |
| 1214 | − scopedProjectKey(scopeProjectRef(member.environmentId, member.id)), | |
| 1215 | − member, | |
| 1523 | + projects.map((project) => [ | |
| 1524 | + `${project.environmentId}:${project.id}`, | |
| 1525 | + project.workspaceRoot, | |
| 1216 | 1526 | ]), |
| 1217 | 1527 | ), |
| 1218 | − [project.memberProjects], | |
| 1528 | + [projects], | |
| 1219 | 1529 | ); |
| 1220 | − const memberThreadCountByPhysicalKey = useMemo(() => { | |
| 1221 | − const counts = new Map<string, number>( | |
| 1222 | − project.memberProjects.map((member) => [member.physicalProjectKey, 0] as const), | |
| 1223 | − ); | |
| 1224 | − for (const thread of projectThreads) { | |
| 1225 | − const member = memberProjectByScopedKey.get( | |
| 1226 | − scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), | |
| 1227 | − ); | |
| 1228 | − if (!member) { | |
| 1229 | − continue; | |
| 1230 | − } | |
| 1231 | − counts.set(member.physicalProjectKey, (counts.get(member.physicalProjectKey) ?? 0) + 1); | |
| 1232 | − } | |
| 1233 | − return counts; | |
| 1234 | − }, [memberProjectByScopedKey, project.memberProjects, projectThreads]); | |
| 1235 | − | |
| 1236 | − const { projectStatus, visibleProjectThreads, orderedProjectThreadKeys } = useMemo(() => { | |
| 1237 | − const lastVisitedAtByThreadKey = new Map( | |
| 1238 | − projectThreads.map((thread, index) => [ | |
| 1239 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1240 | − threadLastVisitedAts[index] ?? null, | |
| 1241 | − ]), | |
| 1242 | − ); | |
| 1243 | − const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => { | |
| 1244 | − const lastVisitedAt = lastVisitedAtByThreadKey.get( | |
| 1245 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1246 | − ); | |
| 1247 | − return resolveThreadStatusPill({ | |
| 1248 | − thread: { | |
| 1249 | − ...thread, | |
| 1250 | − ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}), | |
| 1251 | − }, | |
| 1252 | − }); | |
| 1253 | − }; | |
| 1254 | − const visibleProjectThreads = sortThreads( | |
| 1255 | − projectThreads.filter((thread) => thread.archivedAt === null), | |
| 1256 | − threadSortOrder, | |
| 1257 | − ); | |
| 1258 | − const projectStatus = resolveProjectStatusIndicator( | |
| 1259 | − visibleProjectThreads.map((thread) => resolveProjectThreadStatus(thread)), | |
| 1260 | − ); | |
| 1261 | − return { | |
| 1262 | − orderedProjectThreadKeys: visibleProjectThreads.map((thread) => | |
| 1263 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1530 | + const projectDisplayNameByKey = useMemo( | |
| 1531 | + () => | |
| 1532 | + new Map( | |
| 1533 | + projectGroups.flatMap((group) => | |
| 1534 | + group.memberProjects.map( | |
| 1535 | + (project) => [`${project.environmentId}:${project.id}`, group.displayName] as const, | |
| 1536 | + ), | |
| 1537 | + ), | |
| 1264 | 1538 | ), |
| 1265 | − projectStatus, | |
| 1266 | − visibleProjectThreads, | |
| 1267 | − }; | |
| 1268 | − }, [projectThreads, threadLastVisitedAts, threadSortOrder]); | |
| 1269 | − const pinnedCollapsedThread = useMemo(() => { | |
| 1270 | − const activeThreadKey = activeRouteThreadKey ?? undefined; | |
| 1271 | − if (!activeThreadKey || projectExpanded) { | |
| 1272 | − return null; | |
| 1273 | − } | |
| 1274 | − return ( | |
| 1275 | − visibleProjectThreads.find( | |
| 1276 | − (thread) => | |
| 1277 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey, | |
| 1278 | − ) ?? null | |
| 1279 | − ); | |
| 1280 | − }, [activeRouteThreadKey, projectExpanded, visibleProjectThreads]); | |
| 1281 | − | |
| 1282 | − const { | |
| 1283 | − hasOverflowingThreads, | |
| 1284 | − hiddenThreadStatus, | |
| 1285 | − renderedThreads, | |
| 1286 | − showEmptyThreadState, | |
| 1287 | − shouldShowThreadPanel, | |
| 1288 | − } = useMemo(() => { | |
| 1289 | − const lastVisitedAtByThreadKey = new Map( | |
| 1290 | − projectThreads.map((thread, index) => [ | |
| 1291 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1292 | − threadLastVisitedAts[index] ?? null, | |
| 1293 | − ]), | |
| 1294 | − ); | |
| 1295 | − const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => { | |
| 1296 | − const lastVisitedAt = lastVisitedAtByThreadKey.get( | |
| 1297 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1298 | − ); | |
| 1299 | − return resolveThreadStatusPill({ | |
| 1300 | − thread: { | |
| 1301 | − ...thread, | |
| 1302 | − ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}), | |
| 1303 | − }, | |
| 1539 | + [projectGroups], | |
| 1540 | + ); | |
| 1541 | + | |
| 1542 | + // now is quantized to the minute so effectiveSettled memoization doesn't | |
| 1543 | + // churn on every render; auto-settle thresholds are day-granular anyway. | |
| 1544 | + const nowMinute = useNowMinute(); | |
| 1545 | + // Snooze wake times are second-precise, so classifying with the quantized | |
| 1546 | + // minute would hold a woken thread on the shelf for up to a minute. The | |
| 1547 | + // tick is a plain counter bumped exactly at the next wake boundary (armed | |
| 1548 | + // below, after the partition knows the boundary); the partition reads a | |
| 1549 | + // fresh clock whenever it recomputes. | |
| 1550 | + const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); | |
| 1551 | + | |
| 1552 | + // PR states stream in per-row (rows own the VCS subscriptions); a merged or | |
| 1553 | + // closed PR auto-settles its thread on the next partition. | |
| 1554 | + const [changeRequestStateByKey, setChangeRequestStateByKey] = useState< | |
| 1555 | + ReadonlyMap<string, "open" | "closed" | "merged"> | |
| 1556 | + >(() => new Map()); | |
| 1557 | + const handleChangeRequestState = useCallback( | |
| 1558 | + (threadKey: string, state: "open" | "closed" | "merged" | null) => { | |
| 1559 | + setChangeRequestStateByKey((current) => { | |
| 1560 | + if ((current.get(threadKey) ?? null) === state) return current; | |
| 1561 | + const next = new Map(current); | |
| 1562 | + if (state === null) { | |
| 1563 | + next.delete(threadKey); | |
| 1564 | + } else { | |
| 1565 | + next.set(threadKey, state); | |
| 1566 | + } | |
| 1567 | + return next; | |
| 1304 | 1568 | }); |
| 1305 | − }; | |
| 1306 | − const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount; | |
| 1307 | − const previewThreads = | |
| 1308 | − isThreadListExpanded || !hasOverflowingThreads | |
| 1309 | − ? visibleProjectThreads | |
| 1310 | − : visibleProjectThreads.slice(0, sidebarThreadPreviewCount); | |
| 1311 | − const visibleThreadKeys = new Set( | |
| 1312 | − [...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map((thread) => | |
| 1313 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1314 | − ), | |
| 1315 | − ); | |
| 1316 | − const renderedThreads = pinnedCollapsedThread | |
| 1317 | − ? [pinnedCollapsedThread] | |
| 1318 | − : visibleProjectThreads.filter((thread) => | |
| 1319 | − visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 1320 | − ); | |
| 1321 | − const hiddenThreads = visibleProjectThreads.filter( | |
| 1322 | − (thread) => | |
| 1323 | − !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 1324 | − ); | |
| 1325 | − return { | |
| 1326 | − hasOverflowingThreads, | |
| 1327 | − hiddenThreadStatus: resolveProjectStatusIndicator( | |
| 1328 | − hiddenThreads.map((thread) => resolveProjectThreadStatus(thread)), | |
| 1329 | − ), | |
| 1330 | − renderedThreads, | |
| 1331 | − showEmptyThreadState: projectExpanded && visibleProjectThreads.length === 0, | |
| 1332 | − shouldShowThreadPanel: projectExpanded || pinnedCollapsedThread !== null, | |
| 1333 | − }; | |
| 1334 | − }, [ | |
| 1335 | − isThreadListExpanded, | |
| 1336 | − pinnedCollapsedThread, | |
| 1337 | − projectExpanded, | |
| 1338 | − projectThreads, | |
| 1339 | − sidebarThreadPreviewCount, | |
| 1340 | − threadLastVisitedAts, | |
| 1341 | − visibleProjectThreads, | |
| 1342 | − ]); | |
| 1343 | − | |
| 1344 | − const handleProjectButtonClick = useCallback( | |
| 1345 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 1346 | − if (suppressProjectClickForContextMenuRef.current) { | |
| 1347 | − suppressProjectClickForContextMenuRef.current = false; | |
| 1348 | − event.preventDefault(); | |
| 1349 | − event.stopPropagation(); | |
| 1350 | − return; | |
| 1351 | − } | |
| 1352 | − if (dragInProgressRef.current) { | |
| 1353 | − event.preventDefault(); | |
| 1354 | − event.stopPropagation(); | |
| 1355 | − return; | |
| 1356 | − } | |
| 1357 | − if (suppressProjectClickAfterDragRef.current) { | |
| 1358 | − suppressProjectClickAfterDragRef.current = false; | |
| 1359 | − event.preventDefault(); | |
| 1360 | − event.stopPropagation(); | |
| 1361 | − return; | |
| 1362 | − } | |
| 1363 | − if (useThreadSelectionStore.getState().hasSelection()) { | |
| 1364 | − clearSelection(); | |
| 1365 | − } | |
| 1366 | − setProjectExpanded(projectPreferenceKeys, !projectExpanded); | |
| 1367 | 1569 | }, |
| 1368 | − [ | |
| 1369 | − clearSelection, | |
| 1370 | − dragInProgressRef, | |
| 1371 | − projectExpanded, | |
| 1372 | − projectPreferenceKeys, | |
| 1373 | − setProjectExpanded, | |
| 1374 | − suppressProjectClickAfterDragRef, | |
| 1375 | − suppressProjectClickForContextMenuRef, | |
| 1376 | − ], | |
| 1570 | + [], | |
| 1377 | 1571 | ); |
| 1378 | 1572 | |
| 1379 | − const handleProjectButtonKeyDown = useCallback( | |
| 1380 | − (event: React.KeyboardEvent<HTMLButtonElement>) => { | |
| 1381 | − if (event.key !== "Enter" && event.key !== " ") return; | |
| 1382 | − event.preventDefault(); | |
| 1383 | − if (dragInProgressRef.current) { | |
| 1384 | − return; | |
| 1385 | − } | |
| 1386 | − setProjectExpanded(projectPreferenceKeys, !projectExpanded); | |
| 1387 | − }, | |
| 1388 | − [dragInProgressRef, projectExpanded, projectPreferenceKeys, setProjectExpanded], | |
| 1573 | + // Project scope: one menu above the list. Scoping filters the list without | |
| 1574 | + // making the header width depend on the number or length of project names. | |
| 1575 | + const [projectScopeKey, setProjectScopeKey] = useState<string | null>(null); | |
| 1576 | + const scopedProjectGroup = useMemo( | |
| 1577 | + () => | |
| 1578 | + projectScopeKey === null | |
| 1579 | + ? null | |
| 1580 | + : (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null), | |
| 1581 | + [projectGroups, projectScopeKey], | |
| 1389 | 1582 | ); |
| 1390 | − | |
| 1391 | − const handleProjectButtonPointerDownCapture = useCallback( | |
| 1392 | − (event: React.PointerEvent<HTMLButtonElement>) => { | |
| 1393 | − suppressProjectClickForContextMenuRef.current = false; | |
| 1394 | − if ( | |
| 1395 | − isContextMenuPointerDown({ | |
| 1396 | − button: event.button, | |
| 1397 | − ctrlKey: event.ctrlKey, | |
| 1398 | − isMac: isMacPlatform(navigator.platform), | |
| 1399 | − }) | |
| 1400 | − ) { | |
| 1401 | − event.stopPropagation(); | |
| 1402 | − } | |
| 1403 | − | |
| 1404 | − suppressProjectClickAfterDragRef.current = false; | |
| 1405 | − }, | |
| 1406 | − [suppressProjectClickAfterDragRef, suppressProjectClickForContextMenuRef], | |
| 1583 | + const scopedProjectKeys = useMemo( | |
| 1584 | + () => | |
| 1585 | + scopedProjectGroup === null | |
| 1586 | + ? null | |
| 1587 | + : new Set( | |
| 1588 | + scopedProjectGroup.memberProjectRefs.map( | |
| 1589 | + (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, | |
| 1590 | + ), | |
| 1591 | + ), | |
| 1592 | + [scopedProjectGroup], | |
| 1407 | 1593 | ); |
| 1594 | + useEffect(() => { | |
| 1595 | + if (projectScopeKey !== null && scopedProjectGroup === null) { | |
| 1596 | + setProjectScopeKey(null); | |
| 1597 | + } | |
| 1598 | + }, [projectScopeKey, scopedProjectGroup]); | |
| 1599 | + // Scope flips drop the selection: rows selected under the old scope may be | |
| 1600 | + // hidden now, and bulk actions must never count or touch invisible rows. | |
| 1601 | + useEffect(() => { | |
| 1602 | + clearSelection(); | |
| 1603 | + }, [clearSelection, projectScopeKey]); | |
| 1408 | 1604 | |
| 1409 | − const openProjectRenameDialog = useCallback((member: SidebarProjectGroupMember) => { | |
| 1410 | − setProjectRenameTarget(member); | |
| 1411 | − setProjectRenameTitle(member.title); | |
| 1412 | − }, []); | |
| 1605 | + const handleRemoveProjectMembers = useCallback( | |
| 1606 | + async (projectGroup: SidebarProjectSnapshot, members: readonly SidebarProjectGroupMember[]) => { | |
| 1607 | + const api = readLocalApi(); | |
| 1608 | + if (!api) return; | |
| 1413 | 1609 | |
| 1414 | − const openProjectGroupingDialog = useCallback( | |
| 1415 | − (member: SidebarProjectGroupMember) => { | |
| 1416 | − const overrideKey = deriveProjectGroupingOverrideKey(member); | |
| 1417 | − setProjectGroupingTarget(member); | |
| 1418 | − setProjectGroupingSelection( | |
| 1419 | − projectGroupingSettings.sidebarProjectGroupingOverrides?.[overrideKey] ?? "inherit", | |
| 1610 | + const memberKeys = new Set(members.map((member) => `${member.environmentId}:${member.id}`)); | |
| 1611 | + const projectThreads = threads.filter((thread) => | |
| 1612 | + memberKeys.has(`${thread.environmentId}:${thread.projectId}`), | |
| 1420 | 1613 | ); |
| 1421 | − }, | |
| 1422 | − [projectGroupingSettings.sidebarProjectGroupingOverrides], | |
| 1423 | − ); | |
| 1614 | + const isWholeGroup = members.length === projectGroup.memberProjects.length; | |
| 1615 | + const singleMember = members.length === 1 ? members[0]! : null; | |
| 1616 | + const targetLabel = singleMember?.title ?? projectGroup.displayName; | |
| 1617 | + const confirmed = await settlePromise(() => | |
| 1618 | + api.dialogs.confirm( | |
| 1619 | + projectThreads.length > 0 | |
| 1620 | + ? [ | |
| 1621 | + `Remove project "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`, | |
| 1622 | + ...(singleMember | |
| 1623 | + ? [ | |
| 1624 | + `Path: ${singleMember.workspaceRoot}`, | |
| 1625 | + ...(singleMember.environmentLabel | |
| 1626 | + ? [`Environment: ${singleMember.environmentLabel}`] | |
| 1627 | + : []), | |
| 1628 | + ] | |
| 1629 | + : [`This removes ${members.length} grouped project entries.`]), | |
| 1630 | + "This permanently clears conversation history for those threads.", | |
| 1631 | + isWholeGroup | |
| 1632 | + ? "This removes only the project entries, not the files on disk." | |
| 1633 | + : "Other entries in this grouped project are unaffected.", | |
| 1634 | + "This action cannot be undone.", | |
| 1635 | + ].join("\n") | |
| 1636 | + : [ | |
| 1637 | + `Remove project "${targetLabel}"?`, | |
| 1638 | + ...(singleMember | |
| 1639 | + ? [ | |
| 1640 | + `Path: ${singleMember.workspaceRoot}`, | |
| 1641 | + ...(singleMember.environmentLabel | |
| 1642 | + ? [`Environment: ${singleMember.environmentLabel}`] | |
| 1643 | + : []), | |
| 1644 | + ] | |
| 1645 | + : [`This removes ${members.length} grouped project entries.`]), | |
| 1646 | + isWholeGroup | |
| 1647 | + ? "This removes only the project entries, not the files on disk." | |
| 1648 | + : "Other entries in this grouped project are unaffected.", | |
| 1649 | + ].join("\n"), | |
| 1650 | + ), | |
| 1651 | + ); | |
| 1652 | + if (confirmed._tag === "Failure" || !confirmed.value) return; | |
| 1424 | 1653 | |
| 1425 | − const removeProject = useCallback( | |
| 1426 | − async (member: SidebarProjectGroupMember, options: { force?: boolean } = {}) => { | |
| 1427 | − const memberProjectRef = scopeProjectRef(member.environmentId, member.id); | |
| 1428 | − const result = await deleteProject({ | |
| 1429 | − environmentId: member.environmentId, | |
| 1430 | − input: { | |
| 1431 | − projectId: member.id, | |
| 1432 | − ...(options.force === true ? { force: true } : {}), | |
| 1433 | − }, | |
| 1434 | − }); | |
| 1435 | − if (result._tag === "Failure") { | |
| 1436 | − return result; | |
| 1437 | − } | |
| 1438 | 1654 | const draftStore = useComposerDraftStore.getState(); |
| 1439 | − const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef); | |
| 1440 | − if (projectDraftThread) { | |
| 1441 | − draftStore.clearDraftThread(projectDraftThread.draftId); | |
| 1442 | − } | |
| 1443 | − draftStore.clearProjectDraftThreadId(memberProjectRef); | |
| 1444 | − return result; | |
| 1445 | − }, | |
| 1446 | − [deleteProject], | |
| 1447 | − ); | |
| 1655 | + let shouldNavigate = false; | |
| 1656 | + for (const project of members) { | |
| 1657 | + const memberThreads = projectThreads.filter( | |
| 1658 | + (thread) => | |
| 1659 | + thread.environmentId === project.environmentId && thread.projectId === project.id, | |
| 1660 | + ); | |
| 1661 | + const projectRef = scopeProjectRef(project.environmentId, project.id); | |
| 1662 | + const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef); | |
| 1663 | + const memberRemovalNeedsNavigation = shouldNavigateAfterProjectRemoval({ | |
| 1664 | + routeTarget: routeTargetRef.current, | |
| 1665 | + projectThreads: memberThreads, | |
| 1666 | + projectDraftId: projectDraftThread?.draftId ?? null, | |
| 1667 | + }); | |
| 1448 | 1668 | |
| 1449 | − const handleRemoveProject = useCallback( | |
| 1450 | − async (member: SidebarProjectGroupMember) => { | |
| 1451 | − const api = readLocalApi(); | |
| 1452 | − if (!api) { | |
| 1453 | − return; | |
| 1454 | − } | |
| 1669 | + const result = await deleteProject({ | |
| 1670 | + environmentId: project.environmentId, | |
| 1671 | + input: { | |
| 1672 | + projectId: project.id, | |
| 1673 | + ...(memberThreads.length > 0 ? { force: true } : {}), | |
| 1674 | + }, | |
| 1675 | + }); | |
| 1676 | + if (result._tag === "Failure") { | |
| 1677 | + if (!isAtomCommandInterrupted(result)) { | |
| 1678 | + const error = squashAtomCommandFailure(result); | |
| 1679 | + toastManager.add( | |
| 1680 | + stackedThreadToast({ | |
| 1681 | + type: "error", | |
| 1682 | + title: `Failed to remove "${project.title}"`, | |
| 1683 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1684 | + }), | |
| 1685 | + ); | |
| 1686 | + } | |
| 1687 | + if (shouldNavigate) { | |
| 1688 | + void router.navigate({ to: "/" }); | |
| 1689 | + } | |
| 1690 | + return; | |
| 1691 | + } | |
| 1455 | 1692 | |
| 1456 | − const memberProjectRef = scopeProjectRef(member.environmentId, member.id); | |
| 1457 | − const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0; | |
| 1458 | − if (memberThreadCount > 0) { | |
| 1459 | − const warningToastId = toastManager.add( | |
| 1460 | − stackedThreadToast({ | |
| 1461 | − type: "warning", | |
| 1462 | − title: "Project is not empty", | |
| 1463 | − description: "Delete all threads in this project before removing it.", | |
| 1464 | − actionVariant: "destructive", | |
| 1465 | − actionProps: { | |
| 1466 | − children: "Delete anyway", | |
| 1467 | − onClick: () => { | |
| 1468 | − void (async () => { | |
| 1469 | − toastManager.close(warningToastId); | |
| 1470 | − await new Promise<void>((resolve) => { | |
| 1471 | − window.setTimeout(resolve, 180); | |
| 1472 | − }); | |
| 1473 | − | |
| 1474 | − const latestProjectThreads = Array.from( | |
| 1475 | − sidebarThreadByKeyRef.current.values(), | |
| 1476 | − ).filter( | |
| 1477 | − (thread) => | |
| 1478 | − thread.environmentId === memberProjectRef.environmentId && | |
| 1479 | − thread.projectId === memberProjectRef.projectId, | |
| 1480 | − ); | |
| 1481 | − const confirmed = await api.dialogs.confirm( | |
| 1482 | − latestProjectThreads.length > 0 | |
| 1483 | − ? [ | |
| 1484 | − `Remove project "${member.title}" and delete its ${latestProjectThreads.length} thread${ | |
| 1485 | − latestProjectThreads.length === 1 ? "" : "s" | |
| 1486 | − }?`, | |
| 1487 | − `Path: ${member.workspaceRoot}`, | |
| 1488 | − ...(member.environmentLabel | |
| 1489 | − ? [`Environment: ${member.environmentLabel}`] | |
| 1490 | − : []), | |
| 1491 | − "This permanently clears conversation history for those threads.", | |
| 1492 | − "This removes only this project entry.", | |
| 1493 | − "This action cannot be undone.", | |
| 1494 | − ].join("\n") | |
| 1495 | − : [ | |
| 1496 | − `Remove project "${member.title}"?`, | |
| 1497 | − `Path: ${member.workspaceRoot}`, | |
| 1498 | − ...(member.environmentLabel | |
| 1499 | − ? [`Environment: ${member.environmentLabel}`] | |
| 1500 | − : []), | |
| 1501 | − "This removes only this project entry.", | |
| 1502 | − ].join("\n"), | |
| 1503 | − ); | |
| 1504 | − if (!confirmed) { | |
| 1505 | − return; | |
| 1506 | − } | |
| 1693 | + shouldNavigate ||= memberRemovalNeedsNavigation; | |
| 1694 | + if (projectDraftThread) { | |
| 1695 | + draftStore.clearDraftThread(projectDraftThread.draftId); | |
| 1696 | + } | |
| 1697 | + draftStore.clearProjectDraftThreadId(projectRef); | |
| 1698 | + } | |
| 1507 | 1699 | |
| 1508 | − const result = await removeProject(member, { force: true }); | |
| 1509 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 1510 | − const error = squashAtomCommandFailure(result); | |
| 1511 | − toastManager.add( | |
| 1512 | − stackedThreadToast({ | |
| 1513 | − type: "error", | |
| 1514 | − title: `Failed to remove "${member.title}"`, | |
| 1515 | − description: | |
| 1516 | − error instanceof Error | |
| 1517 | − ? error.message | |
| 1518 | − : "Unknown error removing project.", | |
| 1519 | − }), | |
| 1520 | − ); | |
| 1521 | − } | |
| 1522 | − })().catch((error) => { | |
| 1523 | − const message = | |
| 1524 | − error instanceof Error ? error.message : "Unknown error removing project."; | |
| 1525 | − console.error("Failed to remove project", { | |
| 1526 | − projectId: member.id, | |
| 1527 | − environmentId: member.environmentId, | |
| 1528 | − ...safeErrorLogAttributes(error), | |
| 1529 | − }); | |
| 1530 | − toastManager.add( | |
| 1531 | − stackedThreadToast({ | |
| 1532 | − type: "error", | |
| 1533 | − title: `Failed to remove "${member.title}"`, | |
| 1534 | − description: message, | |
| 1535 | − }), | |
| 1536 | − ); | |
| 1537 | − }); | |
| 1538 | − }, | |
| 1539 | − }, | |
| 1540 | − }), | |
| 1541 | − ); | |
| 1542 | − return; | |
| 1700 | + if (shouldNavigate) { | |
| 1701 | + void router.navigate({ to: "/" }); | |
| 1543 | 1702 | } |
| 1703 | + }, | |
| 1704 | + [deleteProject, router, threads], | |
| 1705 | + ); | |
| 1544 | 1706 | |
| 1545 | − const message = [ | |
| 1546 | − `Remove project "${member.title}"?`, | |
| 1547 | − `Path: ${member.workspaceRoot}`, | |
| 1548 | − ...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []), | |
| 1549 | − "This removes only this project entry.", | |
| 1550 | − ].join("\n"); | |
| 1551 | − const confirmed = await api.dialogs.confirm(message); | |
| 1552 | − if (!confirmed) { | |
| 1707 | + const renameProjectMember = useCallback( | |
| 1708 | + async (member: SidebarProjectGroupMember, nextTitle: string) => { | |
| 1709 | + const title = nextTitle.trim(); | |
| 1710 | + if (!title) { | |
| 1711 | + toastManager.add({ type: "warning", title: "Project title cannot be empty" }); | |
| 1553 | 1712 | return; |
| 1554 | 1713 | } |
| 1555 | − | |
| 1556 | − const result = await removeProject(member); | |
| 1714 | + if (title === member.title) return; | |
| 1715 | + const result = await updateProject({ | |
| 1716 | + environmentId: member.environmentId, | |
| 1717 | + input: { projectId: member.id, title }, | |
| 1718 | + }); | |
| 1557 | 1719 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 1558 | 1720 | const error = squashAtomCommandFailure(result); |
| 1559 | − const message = error instanceof Error ? error.message : "Unknown error removing project."; | |
| 1560 | − console.error("Failed to remove project", { | |
| 1561 | − projectId: member.id, | |
| 1562 | − environmentId: member.environmentId, | |
| 1563 | − ...safeErrorLogAttributes(error), | |
| 1564 | − }); | |
| 1565 | 1721 | toastManager.add( |
| 1566 | 1722 | stackedThreadToast({ |
| 1567 | 1723 | type: "error", |
| 1568 | − title: `Failed to remove "${member.title}"`, | |
| 1569 | − description: message, | |
| 1724 | + title: "Failed to rename project", | |
| 1725 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 1570 | 1726 | }), |
| 1571 | 1727 | ); |
| 1572 | 1728 | } |
| 1573 | 1729 | }, |
| 1574 | − [memberThreadCountByPhysicalKey, removeProject], | |
| 1730 | + [updateProject], | |
| 1731 | + ); | |
| 1732 | + | |
| 1733 | + const updateProjectGroupingPreference = useCallback( | |
| 1734 | + (member: SidebarProjectGroupMember, selection: SidebarProjectGroupingMode | "inherit") => { | |
| 1735 | + const overrideKey = deriveProjectGroupingOverrideKey(member); | |
| 1736 | + const nextOverrides = { ...projectGroupingSettings.sidebarProjectGroupingOverrides }; | |
| 1737 | + if (selection === "inherit") { | |
| 1738 | + delete nextOverrides[overrideKey]; | |
| 1739 | + } else { | |
| 1740 | + nextOverrides[overrideKey] = selection; | |
| 1741 | + } | |
| 1742 | + updateSettings({ sidebarProjectGroupingOverrides: nextOverrides }); | |
| 1743 | + }, | |
| 1744 | + [projectGroupingSettings.sidebarProjectGroupingOverrides, updateSettings], | |
| 1575 | 1745 | ); |
| 1576 | 1746 | |
| 1577 | − const handleProjectButtonContextMenu = useCallback( | |
| 1578 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 1747 | + const handleProjectActions = useCallback( | |
| 1748 | + (event: ReactMouseEvent<HTMLButtonElement>, projectGroup: SidebarProjectSnapshot) => { | |
| 1579 | 1749 | event.preventDefault(); |
| 1580 | − suppressProjectClickForContextMenuRef.current = true; | |
| 1581 | − void (async () => { | |
| 1582 | − const api = readLocalApi(); | |
| 1583 | − if (!api) return; | |
| 1750 | + event.stopPropagation(); | |
| 1751 | + setProjectScopeMenuOpen(false); | |
| 1752 | + window.requestAnimationFrame(() => setProjectActionsTarget(projectGroup)); | |
| 1753 | + }, | |
| 1754 | + [], | |
| 1755 | + ); | |
| 1584 | 1756 | |
| 1585 | − const actionHandlers = new Map<string, () => Promise<void> | void>(); | |
| 1586 | − const makeLeaf = ( | |
| 1587 | − action: "rename" | "grouping" | "copy-path" | "delete", | |
| 1588 | − member: SidebarProjectGroupMember, | |
| 1589 | − options?: { | |
| 1590 | − destructive?: boolean; | |
| 1591 | − disabled?: boolean; | |
| 1592 | − }, | |
| 1593 | − ): ContextMenuItem<string> => { | |
| 1594 | − const id = `${action}:${member.physicalProjectKey}`; | |
| 1595 | − actionHandlers.set(id, () => { | |
| 1596 | − switch (action) { | |
| 1597 | − case "rename": | |
| 1598 | − openProjectRenameDialog(member); | |
| 1599 | − return; | |
| 1600 | − case "grouping": | |
| 1601 | − openProjectGroupingDialog(member); | |
| 1602 | − return; | |
| 1603 | − case "copy-path": | |
| 1604 | − copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot }); | |
| 1605 | − return; | |
| 1606 | − case "delete": | |
| 1607 | − return handleRemoveProject(member); | |
| 1608 | − } | |
| 1609 | − }); | |
| 1757 | + // Settled threads stay in the live shell stream (settled ≠ archived), so | |
| 1758 | + // the partition works directly off live shells: no archived-snapshot | |
| 1759 | + // merging, no optimistic holds. Archived threads remain hidden here — | |
| 1760 | + // archive keeps its original "remove from sidebar" meaning. | |
| 1761 | + const serverConfigs = useAtomValue(environmentServerConfigsAtom); | |
| 1762 | + const { | |
| 1763 | + pinnedThreads, | |
| 1764 | + reorderablePinnedKeys, | |
| 1765 | + activeThreads, | |
| 1766 | + snoozedThreads, | |
| 1767 | + settledThreads, | |
| 1768 | + snoozeNow, | |
| 1769 | + } = useMemo(() => { | |
| 1770 | + const now = `${nowMinute}:00.000Z`; | |
| 1771 | + // Snooze classification uses a REAL clock, not the quantized minute: | |
| 1772 | + // wake times are second-precise and a woken thread must not linger on | |
| 1773 | + // the shelf for the rest of the minute. snoozeWakeTick re-runs this | |
| 1774 | + // memo exactly at the next wake boundary. | |
| 1775 | + void snoozeWakeTick; | |
| 1776 | + const preciseNow = new Date().toISOString(); | |
| 1777 | + const visible = threads.filter( | |
| 1778 | + (thread) => | |
| 1779 | + thread.archivedAt === null && | |
| 1780 | + (scopedProjectKeys === null || | |
| 1781 | + scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)), | |
| 1782 | + ); | |
| 1783 | + const pinned: EnvironmentThreadShell[] = []; | |
| 1784 | + const active: EnvironmentThreadShell[] = []; | |
| 1785 | + const snoozed: EnvironmentThreadShell[] = []; | |
| 1786 | + const settled: EnvironmentThreadShell[] = []; | |
| 1787 | + for (const thread of visible) { | |
| 1788 | + // Threads on servers without the settlement capability (old server, | |
| 1789 | + // or descriptor not loaded yet) never classify as settled: the user | |
| 1790 | + // could neither un-settle nor pin them, so auto-settling them would | |
| 1791 | + // strand rows in a tail with no working affordances. | |
| 1792 | + const supportsSettlement = | |
| 1793 | + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true; | |
| 1794 | + const supportsSnooze = | |
| 1795 | + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; | |
| 1796 | + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); | |
| 1797 | + const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null; | |
| 1798 | + // Snooze outranks everything, including a pin: "hide until Tuesday" | |
| 1799 | + // temporarily suspends "keep on top". The pin survives underneath — | |
| 1800 | + // and so does its pinOrderKey, so on wake the thread reappears at | |
| 1801 | + // its exact slot in the pinned block. (For unpinned threads | |
| 1802 | + // this is also the snooze-beats-auto-settle rule: the wake time is a | |
| 1803 | + // stronger statement about when the thread matters again.) | |
| 1804 | + if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) { | |
| 1805 | + snoozed.push(thread); | |
| 1806 | + // A pin otherwise overrides the lifecycle: pinned threads never | |
| 1807 | + // auto-settle out of sight. (The decider clears settled state on | |
| 1808 | + // pin and the pin on settle, so pin-vs-settled conflicts only | |
| 1809 | + // arise from stale or raced writes.) | |
| 1810 | + } else if (thread.pinnedAt != null) { | |
| 1811 | + pinned.push(thread); | |
| 1812 | + } else if ( | |
| 1813 | + supportsSettlement && | |
| 1814 | + effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState }) | |
| 1815 | + ) { | |
| 1816 | + settled.push(thread); | |
| 1817 | + } else { | |
| 1818 | + active.push(thread); | |
| 1819 | + } | |
| 1820 | + } | |
| 1821 | + // One shared rule on every platform (see sortPinnedThreadsByOrderKey): | |
| 1822 | + // user-arranged keys first, keyless threads in creation order below. | |
| 1823 | + // Server capability only gates DRAGGING — it must not influence the | |
| 1824 | + // sort, or mixed-version fleets would render different pinned orders on | |
| 1825 | + // web and mobile from the same data. | |
| 1826 | + return { | |
| 1827 | + pinnedThreads: sortPinnedThreadsForSidebar(pinned), | |
| 1828 | + reorderablePinnedKeys: new Set( | |
| 1829 | + pinned | |
| 1830 | + .filter( | |
| 1831 | + (thread) => | |
| 1832 | + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadPinReorder === | |
| 1833 | + true, | |
| 1834 | + ) | |
| 1835 | + .map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 1836 | + ), | |
| 1837 | + activeThreads: sortThreadsForSidebar(active), | |
| 1838 | + // Soonest wake first: "what comes back next" is the shelf's question. | |
| 1839 | + snoozedThreads: snoozed.toSorted( | |
| 1840 | + (left, right) => | |
| 1841 | + firstValidTimestampMs(left.snoozedUntil ?? null) - | |
| 1842 | + firstValidTimestampMs(right.snoozedUntil ?? null), | |
| 1843 | + ), | |
| 1844 | + settledThreads: sortSettledThreadsForSidebar(settled), | |
| 1845 | + snoozeNow: preciseNow, | |
| 1846 | + }; | |
| 1847 | + }, [ | |
| 1848 | + autoSettleAfterDays, | |
| 1849 | + changeRequestStateByKey, | |
| 1850 | + nowMinute, | |
| 1851 | + scopedProjectKeys, | |
| 1852 | + serverConfigs, | |
| 1853 | + snoozeWakeTick, | |
| 1854 | + threads, | |
| 1855 | + ]); | |
| 1610 | 1856 | |
| 1611 | − return { | |
| 1612 | − id, | |
| 1613 | − label: formatProjectMemberActionLabel(member, project.groupedProjectCount), | |
| 1614 | − ...(options?.destructive ? { destructive: true } : {}), | |
| 1615 | − ...(options?.disabled ? { disabled: true } : {}), | |
| 1616 | − }; | |
| 1617 | − }; | |
| 1618 | − | |
| 1619 | − const buildTargetedItem = ( | |
| 1620 | − action: "rename" | "grouping" | "copy-path" | "delete", | |
| 1621 | − label: string, | |
| 1622 | − options?: { | |
| 1623 | − destructive?: boolean; | |
| 1624 | − isDisabled?: (member: SidebarProjectGroupMember) => boolean; | |
| 1625 | − }, | |
| 1626 | − ): ContextMenuItem<string> => { | |
| 1627 | − if (project.memberProjects.length === 1) { | |
| 1628 | − const singleMember = project.memberProjects[0]!; | |
| 1629 | − return { | |
| 1630 | − ...makeLeaf(action, singleMember, { | |
| 1631 | − ...(options?.destructive ? { destructive: true } : {}), | |
| 1632 | − ...(options?.isDisabled?.(singleMember) ? { disabled: true } : {}), | |
| 1633 | − }), | |
| 1634 | − label, | |
| 1635 | − ...(action === "delete" ? { icon: "trash" } : {}), | |
| 1636 | − }; | |
| 1637 | − } | |
| 1857 | + const threadSearchInputRef = useRef<HTMLInputElement>(null); | |
| 1858 | + const [threadSearchQuery, setThreadSearchQuery] = useState(""); | |
| 1859 | + const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0); | |
| 1860 | + const isSearchingThreads = threadSearchQuery.trim().length > 0; | |
| 1861 | + const searchableThreads = useMemo( | |
| 1862 | + () => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads], | |
| 1863 | + [activeThreads, pinnedThreads, settledThreads, snoozedThreads], | |
| 1864 | + ); | |
| 1865 | + const threadSearchResults = useMemo( | |
| 1866 | + () => searchSidebarThreadsByTitle(searchableThreads, threadSearchQuery), | |
| 1867 | + [searchableThreads, threadSearchQuery], | |
| 1868 | + ); | |
| 1869 | + const threadSearchResultOrderKey = threadSearchResults | |
| 1870 | + .map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))) | |
| 1871 | + .join("\0"); | |
| 1638 | 1872 | |
| 1639 | − return { | |
| 1640 | − id: `${action}:submenu`, | |
| 1641 | − label, | |
| 1642 | − ...(action === "delete" ? { icon: "trash" } : {}), | |
| 1643 | − children: project.memberProjects.map((member) => | |
| 1644 | − makeLeaf(action, member, { | |
| 1645 | − ...(options?.destructive ? { destructive: true } : {}), | |
| 1646 | − ...(options?.isDisabled?.(member) ? { disabled: true } : {}), | |
| 1647 | − }), | |
| 1648 | − ), | |
| 1649 | − }; | |
| 1650 | − }; | |
| 1873 | + useEffect(() => { | |
| 1874 | + setActiveSearchResultIndex(0); | |
| 1875 | + }, [threadSearchResultOrderKey]); | |
| 1651 | 1876 | |
| 1652 | − const clicked = await api.contextMenu.show( | |
| 1653 | − [ | |
| 1654 | − buildTargetedItem("rename", "Rename"), | |
| 1655 | − buildTargetedItem("grouping", "Group into..."), | |
| 1656 | − buildTargetedItem("copy-path", "Copy Path"), | |
| 1657 | − buildTargetedItem("delete", "Remove", { | |
| 1658 | − destructive: true, | |
| 1659 | − }), | |
| 1660 | − ], | |
| 1661 | − { | |
| 1662 | − x: event.clientX, | |
| 1663 | − y: event.clientY, | |
| 1664 | − }, | |
| 1877 | + useEffect(() => { | |
| 1878 | + if (!isSearchingThreads) return; | |
| 1879 | + document | |
| 1880 | + .getElementById(`sidebar-thread-search-result-${activeSearchResultIndex}`) | |
| 1881 | + ?.scrollIntoView({ block: "nearest" }); | |
| 1882 | + }, [activeSearchResultIndex, isSearchingThreads, threadSearchResultOrderKey]); | |
| 1883 | + | |
| 1884 | + // Arm a timeout for the earliest upcoming wake so the shelf empties the | |
| 1885 | + // moment a snooze expires instead of on the next minute tick. Sorted | |
| 1886 | + // soonest-first, so entry 0 is the boundary. | |
| 1887 | + useEffect(() => { | |
| 1888 | + const nextWakeAtMs = | |
| 1889 | + snoozedThreads.length > 0 && snoozedThreads[0]?.snoozedUntil != null | |
| 1890 | + ? Date.parse(snoozedThreads[0].snoozedUntil) | |
| 1891 | + : Number.NaN; | |
| 1892 | + if (Number.isNaN(nextWakeAtMs)) return; | |
| 1893 | + // setTimeout delays are signed 32-bit: anything larger overflows and | |
| 1894 | + // fires immediately, turning a far-future wake (event-condition snoozes | |
| 1895 | + // synced from elsewhere) into a tight re-arm loop. Clamped, the timer | |
| 1896 | + // just re-arms every ~24.8 days until the wake is in range. | |
| 1897 | + const delayMs = Math.min(Math.max(0, nextWakeAtMs - Date.now()) + 50, 2_147_483_647); | |
| 1898 | + const id = window.setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs); | |
| 1899 | + return () => window.clearTimeout(id); | |
| 1900 | + }, [snoozedThreads]); | |
| 1901 | + | |
| 1902 | + // The settled tail renders in pages: history shouldn't dominate the | |
| 1903 | + // sidebar, and the common lookups are recent. Expansion resets when the | |
| 1904 | + // filter context changes so a scope/search flip never inherits a deep | |
| 1905 | + // page state. | |
| 1906 | + const [settledVisibleCount, setSettledVisibleCount] = useState(SETTLED_TAIL_INITIAL_COUNT); | |
| 1907 | + const settledResetKey = projectScopeKey ?? "all"; | |
| 1908 | + const lastSettledResetKeyRef = useRef(settledResetKey); | |
| 1909 | + if (lastSettledResetKeyRef.current !== settledResetKey) { | |
| 1910 | + lastSettledResetKeyRef.current = settledResetKey; | |
| 1911 | + setSettledVisibleCount(SETTLED_TAIL_INITIAL_COUNT); | |
| 1912 | + } | |
| 1913 | + const visibleSettledThreads = useMemo(() => { | |
| 1914 | + if (settledThreads.length <= settledVisibleCount) return settledThreads; | |
| 1915 | + const visible = settledThreads.slice(0, settledVisibleCount); | |
| 1916 | + // The open thread must never hide under "Show more": navigating into a | |
| 1917 | + // deep settled thread (search, deep link) pulls its row into the visible | |
| 1918 | + // tail so the highlight and the un-settle affordance stay reachable. | |
| 1919 | + if (routeThreadKey !== null) { | |
| 1920 | + const routeThread = settledThreads | |
| 1921 | + .slice(settledVisibleCount) | |
| 1922 | + .find( | |
| 1923 | + (thread) => | |
| 1924 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, | |
| 1665 | 1925 | ); |
| 1926 | + if (routeThread !== undefined) visible.push(routeThread); | |
| 1927 | + } | |
| 1928 | + return visible; | |
| 1929 | + }, [routeThreadKey, settledThreads, settledVisibleCount]); | |
| 1930 | + const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length; | |
| 1931 | + const showMoreSettled = useCallback( | |
| 1932 | + () => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT), | |
| 1933 | + [], | |
| 1934 | + ); | |
| 1935 | + const [settledShelfExpanded, setSettledShelfExpanded] = useState(true); | |
| 1936 | + const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []); | |
| 1937 | + const renderedSettledThreads = useMemo(() => { | |
| 1938 | + if (settledShelfExpanded) return visibleSettledThreads; | |
| 1939 | + if (routeThreadKey === null) return []; | |
| 1940 | + const routeThread = visibleSettledThreads.find( | |
| 1941 | + (thread) => | |
| 1942 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, | |
| 1943 | + ); | |
| 1944 | + return routeThread === undefined ? [] : [routeThread]; | |
| 1945 | + }, [routeThreadKey, settledShelfExpanded, visibleSettledThreads]); | |
| 1946 | + | |
| 1947 | + // The snoozed shelf is collapsed by default: out of the way, never gone. | |
| 1948 | + // Collapsed threads don't render (and so don't participate in jump | |
| 1949 | + // shortcuts or multi-select), matching the settled tail's paging model. | |
| 1950 | + const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false); | |
| 1951 | + const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []); | |
| 1952 | + const visibleSnoozedThreads = useMemo(() => { | |
| 1953 | + if (snoozedShelfExpanded) return snoozedThreads; | |
| 1954 | + // The open thread must never vanish behind the collapsed shelf: a | |
| 1955 | + // snoozed thread reached by route (deep link, open before snoozing | |
| 1956 | + // elsewhere) keeps its row — with highlight and wake affordance — same | |
| 1957 | + // exception the settled tail's "Show more" makes. | |
| 1958 | + if (routeThreadKey === null) return []; | |
| 1959 | + const routeThread = snoozedThreads.find( | |
| 1960 | + (thread) => | |
| 1961 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, | |
| 1962 | + ); | |
| 1963 | + return routeThread === undefined ? [] : [routeThread]; | |
| 1964 | + }, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]); | |
| 1666 | 1965 | |
| 1667 | − if (!clicked) { | |
| 1668 | − return; | |
| 1669 | − } | |
| 1670 | − | |
| 1671 | − await actionHandlers.get(clicked)?.(); | |
| 1672 | − })(); | |
| 1673 | − }, | |
| 1674 | − [ | |
| 1675 | − copyPathToClipboard, | |
| 1676 | − handleRemoveProject, | |
| 1677 | − openProjectGroupingDialog, | |
| 1678 | − openProjectRenameDialog, | |
| 1679 | − project.groupedProjectCount, | |
| 1680 | − project.memberProjects, | |
| 1681 | − suppressProjectClickForContextMenuRef, | |
| 1682 | − ], | |
| 1966 | + const orderedThreads = useMemo( | |
| 1967 | + () => [...pinnedThreads, ...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads], | |
| 1968 | + [pinnedThreads, activeThreads, visibleSnoozedThreads, renderedSettledThreads], | |
| 1969 | + ); | |
| 1970 | + const orderedThreadKeys = useMemo( | |
| 1971 | + () => | |
| 1972 | + orderedThreads.map((thread) => | |
| 1973 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1974 | + ), | |
| 1975 | + [orderedThreads], | |
| 1976 | + ); | |
| 1977 | + // Rows call back into the click handler without carrying the ordered list as | |
| 1978 | + // a prop — a fresh array identity per shell update would defeat every row's | |
| 1979 | + // memoization. The ref keeps shift-range-select working against the list as | |
| 1980 | + // rendered at click time. | |
| 1981 | + const orderedThreadKeysRef = useRef(orderedThreadKeys); | |
| 1982 | + orderedThreadKeysRef.current = orderedThreadKeys; | |
| 1983 | + const threadByKey = useMemo( | |
| 1984 | + () => | |
| 1985 | + new Map( | |
| 1986 | + orderedThreads.map( | |
| 1987 | + (thread) => | |
| 1988 | + [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, | |
| 1989 | + ), | |
| 1990 | + ), | |
| 1991 | + [orderedThreads], | |
| 1992 | + ); | |
| 1993 | + // Handlers read these through refs: depending on per-update Map/Set | |
| 1994 | + // identities would give every row a fresh callback prop on each shell | |
| 1995 | + // event and defeat row memoization during streaming. | |
| 1996 | + const threadByKeyRef = useRef(threadByKey); | |
| 1997 | + threadByKeyRef.current = threadByKey; | |
| 1998 | + // handleNewThread is inherently unstable (depends on the projects list); | |
| 1999 | + // a ref keeps it out of attemptSettle's dependency array. | |
| 2000 | + const handleNewThreadRef = useRef(newThreadContext.handleNewThread); | |
| 2001 | + handleNewThreadRef.current = newThreadContext.handleNewThread; | |
| 2002 | + const settledThreadKeys = useMemo( | |
| 2003 | + () => | |
| 2004 | + new Set( | |
| 2005 | + settledThreads.map((thread) => | |
| 2006 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2007 | + ), | |
| 2008 | + ), | |
| 2009 | + [settledThreads], | |
| 1683 | 2010 | ); |
| 2011 | + const settledThreadKeysRef = useRef(settledThreadKeys); | |
| 2012 | + settledThreadKeysRef.current = settledThreadKeys; | |
| 2013 | + const snoozedThreadKeys = useMemo( | |
| 2014 | + () => | |
| 2015 | + new Set( | |
| 2016 | + snoozedThreads.map((thread) => | |
| 2017 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2018 | + ), | |
| 2019 | + ), | |
| 2020 | + [snoozedThreads], | |
| 2021 | + ); | |
| 2022 | + const snoozedThreadKeysRef = useRef(snoozedThreadKeys); | |
| 2023 | + snoozedThreadKeysRef.current = snoozedThreadKeys; | |
| 2024 | + | |
| 2025 | + const jumpLabelByKey = useMemo(() => { | |
| 2026 | + const mapping = new Map<string, string>(); | |
| 2027 | + for (const [index, threadKey] of orderedThreadKeys.entries()) { | |
| 2028 | + const jumpCommand = threadJumpCommandForIndex(index); | |
| 2029 | + if (!jumpCommand) break; | |
| 2030 | + const label = shortcutLabelForCommand(keybindings, jumpCommand); | |
| 2031 | + if (label) mapping.set(threadKey, label); | |
| 2032 | + } | |
| 2033 | + return mapping; | |
| 2034 | + }, [keybindings, orderedThreadKeys]); | |
| 2035 | + const [showJumpHints, setShowJumpHints] = useState(false); | |
| 1684 | 2036 | |
| 2037 | + // Settled threads are live shells, so opening one is plain navigation: | |
| 2038 | + // history stays readable without un-settling, and sending a message or | |
| 2039 | + // starting a session un-settles server-side. | |
| 1685 | 2040 | const navigateToThread = useCallback( |
| 1686 | 2041 | (threadRef: ScopedThreadRef) => { |
| 1687 | 2042 | if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { |
| @@ -1699,145 +2054,636 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec · 11 unmodified lines | ||
| 1699 | 2054 | [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor], |
| 1700 | 2055 | ); |
| 1701 | 2056 | |
| 1702 | − const handleThreadClick = useCallback( | |
| 1703 | − ( | |
| 1704 | − event: React.MouseEvent, | |
| 1705 | − threadRef: ScopedThreadRef, | |
| 1706 | − orderedProjectThreadKeys: readonly string[], | |
| 1707 | − ) => { | |
| 1708 | − const isMac = isMacPlatform(navigator.platform); | |
| 1709 | − const isModClick = isMac ? event.metaKey : event.ctrlKey; | |
| 1710 | − const isShiftClick = event.shiftKey; | |
| 1711 | − const threadKey = scopedThreadKey(threadRef); | |
| 1712 | − const currentSelectionCount = useThreadSelectionStore.getState().selectedThreadKeys.size; | |
| 1713 | − | |
| 1714 | − if (isModClick) { | |
| 2057 | + const clearThreadSearch = useCallback(() => { | |
| 2058 | + setThreadSearchQuery(""); | |
| 2059 | + setActiveSearchResultIndex(0); | |
| 2060 | + }, []); | |
| 2061 | + const selectThreadSearchResult = useCallback( | |
| 2062 | + (thread: EnvironmentThreadShell) => { | |
| 2063 | + clearThreadSearch(); | |
| 2064 | + navigateToThread(scopeThreadRef(thread.environmentId, thread.id)); | |
| 2065 | + }, | |
| 2066 | + [clearThreadSearch, navigateToThread], | |
| 2067 | + ); | |
| 2068 | + const handleThreadSearchKeyDown = useCallback( | |
| 2069 | + (event: ReactKeyboardEvent<HTMLInputElement>) => { | |
| 2070 | + // IME composition (Japanese/Chinese input) uses the same keys; committing | |
| 2071 | + // a candidate must not move the highlight or navigate away mid-compose. | |
| 2072 | + if (event.nativeEvent.isComposing || event.keyCode === 229) return; | |
| 2073 | + if (event.key === "Escape" && isSearchingThreads) { | |
| 1715 | 2074 | event.preventDefault(); |
| 1716 | − toggleThreadSelection(threadKey); | |
| 2075 | + event.stopPropagation(); | |
| 2076 | + clearThreadSearch(); | |
| 1717 | 2077 | return; |
| 1718 | 2078 | } |
| 1719 | − | |
| 1720 | − if (isShiftClick) { | |
| 2079 | + if (threadSearchResults.length === 0) return; | |
| 2080 | + if (event.key === "ArrowDown") { | |
| 1721 | 2081 | event.preventDefault(); |
| 1722 | − rangeSelectTo(threadKey, orderedProjectThreadKeys); | |
| 2082 | + setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length); | |
| 1723 | 2083 | return; |
| 1724 | 2084 | } |
| 1725 | − | |
| 1726 | − // Ignore the trailing click of a plain double-click so it doesn't navigate | |
| 1727 | − // while a double-click is starting an inline rename. Placed after the | |
| 1728 | − // modifier branches so cmd/shift selection still processes every click. | |
| 1729 | − if (isTrailingDoubleClick(event.detail)) { | |
| 2085 | + if (event.key === "ArrowUp") { | |
| 2086 | + event.preventDefault(); | |
| 2087 | + setActiveSearchResultIndex( | |
| 2088 | + (index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length, | |
| 2089 | + ); | |
| 1730 | 2090 | return; |
| 1731 | 2091 | } |
| 1732 | − | |
| 1733 | − if (currentSelectionCount > 0) { | |
| 1734 | − clearSelection(); | |
| 1735 | − } | |
| 1736 | − setSelectionAnchor(threadKey); | |
| 1737 | − if (isMobile) { | |
| 1738 | − setOpenMobile(false); | |
| 2092 | + if (event.key === "Enter") { | |
| 2093 | + event.preventDefault(); | |
| 2094 | + const result = threadSearchResults[activeSearchResultIndex]; | |
| 2095 | + if (result) selectThreadSearchResult(result); | |
| 1739 | 2096 | } |
| 1740 | − void router.navigate({ | |
| 1741 | − to: "/$environmentId/$threadId", | |
| 1742 | − params: buildThreadRouteParams(threadRef), | |
| 1743 | − }); | |
| 1744 | 2097 | }, |
| 1745 | 2098 | [ |
| 1746 | − clearSelection, | |
| 1747 | − isMobile, | |
| 1748 | − rangeSelectTo, | |
| 1749 | − router, | |
| 1750 | − setOpenMobile, | |
| 1751 | − setSelectionAnchor, | |
| 1752 | − toggleThreadSelection, | |
| 2099 | + activeSearchResultIndex, | |
| 2100 | + clearThreadSearch, | |
| 2101 | + isSearchingThreads, | |
| 2102 | + selectThreadSearchResult, | |
| 2103 | + threadSearchResults, | |
| 1753 | 2104 | ], |
| 1754 | 2105 | ); |
| 1755 | 2106 | |
| 1756 | − const handleMultiSelectContextMenu = useCallback( | |
| 1757 | − async (position: { x: number; y: number }) => { | |
| 1758 | − const api = readLocalApi(); | |
| 1759 | − if (!api) return; | |
| 1760 | − const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys]; | |
| 1761 | − if (threadKeys.length === 0) return; | |
| 1762 | − const count = threadKeys.length; | |
| 1763 | − const selectedThreadEntries = threadKeys.flatMap((threadKey) => { | |
| 1764 | − const threadRef = parseScopedThreadKey(threadKey); | |
| 1765 | − const thread = threadRef ? readThreadShell(threadRef) : null; | |
| 1766 | − return threadRef && thread ? [{ threadKey, threadRef, thread }] : []; | |
| 1767 | − }); | |
| 1768 | − const hasRunningThread = selectedThreadEntries.some( | |
| 1769 | − ({ thread }) => thread.session?.status === "running" && thread.session.activeTurnId != null, | |
| 1770 | − ); | |
| 1771 | − | |
| 1772 | − const clicked = await api.contextMenu.show( | |
| 1773 | − buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }), | |
| 1774 | − position, | |
| 1775 | − ); | |
| 1776 | − | |
| 1777 | − if (clicked === "mark-unread") { | |
| 1778 | − for (const { threadKey, thread } of selectedThreadEntries) { | |
| 1779 | − markThreadUnread(threadKey, thread.latestTurn?.completedAt); | |
| 2107 | + const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null); | |
| 2108 | + const [renamingTitle, setRenamingTitle] = useState(""); | |
| 2109 | + const startThreadRename = useCallback((threadRef: ScopedThreadRef, title: string) => { | |
| 2110 | + setRenamingThreadKey(scopedThreadKey(threadRef)); | |
| 2111 | + setRenamingTitle(title); | |
| 2112 | + }, []); | |
| 2113 | + const cancelThreadRename = useCallback(() => setRenamingThreadKey(null), []); | |
| 2114 | + const commitThreadRename = useCallback( | |
| 2115 | + (threadRef: ScopedThreadRef, title: string, originalTitle: string) => { | |
| 2116 | + void (async () => { | |
| 2117 | + const trimmed = title.trim(); | |
| 2118 | + setRenamingThreadKey(null); | |
| 2119 | + if (trimmed.length === 0) { | |
| 2120 | + toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); | |
| 2121 | + return; | |
| 1780 | 2122 | } |
| 1781 | − clearSelection(); | |
| 2123 | + if (trimmed === originalTitle) return; | |
| 2124 | + const result = await updateThreadMetadata({ | |
| 2125 | + environmentId: threadRef.environmentId, | |
| 2126 | + input: { threadId: threadRef.threadId, title: trimmed }, | |
| 2127 | + }); | |
| 2128 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2129 | + const error = squashAtomCommandFailure(result); | |
| 2130 | + toastManager.add( | |
| 2131 | + stackedThreadToast({ | |
| 2132 | + type: "error", | |
| 2133 | + title: "Failed to rename thread", | |
| 2134 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2135 | + }), | |
| 2136 | + ); | |
| 2137 | + } | |
| 2138 | + })(); | |
| 2139 | + }, | |
| 2140 | + [updateThreadMetadata], | |
| 2141 | + ); | |
| 2142 | + | |
| 2143 | + const handleThreadClick = useCallback( | |
| 2144 | + (event: ReactMouseEvent, threadRef: ScopedThreadRef) => { | |
| 2145 | + const isMac = isMacPlatform(navigator.platform); | |
| 2146 | + const isModClick = isMac ? event.metaKey : event.ctrlKey; | |
| 2147 | + const threadKey = scopedThreadKey(threadRef); | |
| 2148 | + if (isModClick) { | |
| 2149 | + event.preventDefault(); | |
| 2150 | + toggleThreadSelection(threadKey); | |
| 2151 | + return; | |
| 2152 | + } | |
| 2153 | + if (event.shiftKey) { | |
| 2154 | + event.preventDefault(); | |
| 2155 | + rangeSelectTo(threadKey, orderedThreadKeysRef.current); | |
| 1782 | 2156 | return; |
| 1783 | 2157 | } |
| 2158 | + if (isTrailingDoubleClick(event.detail)) { | |
| 2159 | + return; | |
| 2160 | + } | |
| 2161 | + navigateToThread(threadRef); | |
| 2162 | + }, | |
| 2163 | + [navigateToThread, rangeSelectTo, toggleThreadSelection], | |
| 2164 | + ); | |
| 2165 | + | |
| 2166 | + // A settle per thread at a time: double clicks and repeated menu picks | |
| 2167 | + // must not dispatch a second settle that fails and toasts a false error. | |
| 2168 | + const settlingThreadKeysRef = useRef(new Set<string>()); | |
| 2169 | + // Parking the thread you're looking at (settle or snooze) moves you | |
| 2170 | + // forward: the next remaining card (never a settled or snoozed row, never | |
| 2171 | + // one leaving in the same batch), or a fresh draft in this project when it | |
| 2172 | + // was the last active one. Callers snapshot the plan BEFORE the command | |
| 2173 | + // mutates the partition; background parks never navigate (null plan). | |
| 2174 | + const planForwardNavigation = useCallback( | |
| 2175 | + (threadKey: string, coParkingKeys?: ReadonlySet<string>): (() => void) | null => { | |
| 2176 | + if (routeThreadKeyRef.current !== threadKey) return null; | |
| 2177 | + const shell = threadByKeyRef.current.get(threadKey); | |
| 2178 | + const orderedKeys = orderedThreadKeysRef.current; | |
| 2179 | + const settledKeys = settledThreadKeysRef.current; | |
| 2180 | + const snoozedKeys = snoozedThreadKeysRef.current; | |
| 2181 | + const currentIndex = orderedKeys.indexOf(threadKey); | |
| 2182 | + const nextCardKey = | |
| 2183 | + currentIndex === -1 | |
| 2184 | + ? null | |
| 2185 | + : ([...orderedKeys.slice(currentIndex + 1), ...orderedKeys.slice(0, currentIndex)].find( | |
| 2186 | + (key) => !settledKeys.has(key) && !snoozedKeys.has(key) && !coParkingKeys?.has(key), | |
| 2187 | + ) ?? null); | |
| 2188 | + const nextThread = nextCardKey ? threadByKeyRef.current.get(nextCardKey) : null; | |
| 2189 | + return nextThread | |
| 2190 | + ? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id)) | |
| 2191 | + : shell | |
| 2192 | + ? () => | |
| 2193 | + void handleNewThreadRef.current(scopeProjectRef(shell.environmentId, shell.projectId)) | |
| 2194 | + : () => void router.navigate({ to: "/" }); | |
| 2195 | + }, | |
| 2196 | + [navigateToThread, router], | |
| 2197 | + ); | |
| 1784 | 2198 | |
| 1785 | − if (clicked === "archive") { | |
| 1786 | − if (appSettingsConfirmThreadArchive) { | |
| 1787 | − const confirmed = await api.dialogs.confirm( | |
| 1788 | − `Archive ${count} thread${count === 1 ? "" : "s"}?`, | |
| 2199 | + const attemptSettle = useCallback( | |
| 2200 | + (threadRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet<string> } = {}) => { | |
| 2201 | + void (async () => { | |
| 2202 | + const threadKey = scopedThreadKey(threadRef); | |
| 2203 | + if (settlingThreadKeysRef.current.has(threadKey)) return; | |
| 2204 | + settlingThreadKeysRef.current.add(threadKey); | |
| 2205 | + try { | |
| 2206 | + const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); | |
| 2207 | + const result = await settleThread(threadRef); | |
| 2208 | + if (result._tag === "Failure") { | |
| 2209 | + // Never navigate away from a thread that did not settle. | |
| 2210 | + if (!isAtomCommandInterrupted(result)) { | |
| 2211 | + const error = squashAtomCommandFailure(result); | |
| 2212 | + toastManager.add( | |
| 2213 | + stackedThreadToast({ | |
| 2214 | + type: "error", | |
| 2215 | + title: "Failed to settle thread", | |
| 2216 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2217 | + }), | |
| 2218 | + ); | |
| 2219 | + } | |
| 2220 | + return; | |
| 2221 | + } | |
| 2222 | + // Only move forward if the user is still on the settled thread — | |
| 2223 | + // a navigation made during the await wins over ours. | |
| 2224 | + if (routeThreadKeyRef.current === threadKey) { | |
| 2225 | + navigateAfterSettle?.(); | |
| 2226 | + } | |
| 2227 | + } finally { | |
| 2228 | + settlingThreadKeysRef.current.delete(threadKey); | |
| 2229 | + } | |
| 2230 | + })(); | |
| 2231 | + }, | |
| 2232 | + [planForwardNavigation, settleThread], | |
| 2233 | + ); | |
| 2234 | + const attemptUnsettle = useCallback( | |
| 2235 | + (threadRef: ScopedThreadRef) => { | |
| 2236 | + void (async () => { | |
| 2237 | + const result = await unsettleThread(threadRef); | |
| 2238 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2239 | + const error = squashAtomCommandFailure(result); | |
| 2240 | + toastManager.add( | |
| 2241 | + stackedThreadToast({ | |
| 2242 | + type: "error", | |
| 2243 | + title: "Failed to un-settle thread", | |
| 2244 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2245 | + }), | |
| 1789 | 2246 | ); |
| 1790 | − if (!confirmed) return; | |
| 1791 | 2247 | } |
| 1792 | − | |
| 1793 | − const archiveOutcome = await archiveSelectedThreadEntries({ | |
| 1794 | − entries: selectedThreadEntries, | |
| 1795 | − archive: ({ threadRef }, onArchived) => archiveThread(threadRef, { onArchived }), | |
| 1796 | − }); | |
| 1797 | − for (const failure of archiveOutcome.followupFailures) { | |
| 1798 | − if (isAtomCommandInterrupted(failure)) continue; | |
| 1799 | − const error = squashAtomCommandFailure(failure); | |
| 2248 | + })(); | |
| 2249 | + }, | |
| 2250 | + [unsettleThread], | |
| 2251 | + ); | |
| 2252 | + const attemptUnsnooze = useCallback( | |
| 2253 | + (threadRef: ScopedThreadRef) => { | |
| 2254 | + void (async () => { | |
| 2255 | + const result = await unsnoozeThread(threadRef); | |
| 2256 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2257 | + const error = squashAtomCommandFailure(result); | |
| 2258 | + toastManager.add( | |
| 2259 | + stackedThreadToast({ | |
| 2260 | + type: "error", | |
| 2261 | + title: "Failed to wake thread", | |
| 2262 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2263 | + }), | |
| 2264 | + ); | |
| 2265 | + } | |
| 2266 | + })(); | |
| 2267 | + }, | |
| 2268 | + [unsnoozeThread], | |
| 2269 | + ); | |
| 2270 | + // Drag-to-reorder for the pinned block. A drop computes ONE fractional key | |
| 2271 | + // for the moved thread and sends it to that thread's own server (see | |
| 2272 | + // planPinnedReorder for the keyless-neighbor materialization case). The | |
| 2273 | + // optimistic order keeps the card where it was dropped until the | |
| 2274 | + // confirming event round-trips; canonical order matching it releases the | |
| 2275 | + // override, and a failed write clears it (the card snaps back) with a toast. | |
| 2276 | + // ANY membership change (new pin, unpin, snooze/wake) also releases it: | |
| 2277 | + // the override can't say where members it never saw belong, and holding it | |
| 2278 | + // would misplace them and launder the stale order into later drags. | |
| 2279 | + const pinnedDndSensors = useSensors( | |
| 2280 | + useSensor(PointerSensor, { activationConstraint: { distance: 6 } }), | |
| 2281 | + ); | |
| 2282 | + const [optimisticPinnedOrder, setOptimisticPinnedOrder] = useState<{ | |
| 2283 | + readonly order: readonly string[]; | |
| 2284 | + /** pinOrderKey per thread as of the drop, so ANY landed write (ours | |
| 2285 | + confirming, or a concurrent one from another client) releases the | |
| 2286 | + override rather than fighting canonical state. */ | |
| 2287 | + readonly keysAtDrop: ReadonlyMap<string, string | null>; | |
| 2288 | + } | null>(null); | |
| 2289 | + const orderedPinnedThreads = useMemo(() => { | |
| 2290 | + if (optimisticPinnedOrder === null) return pinnedThreads; | |
| 2291 | + return orderItemsByPreferredIds({ | |
| 2292 | + items: pinnedThreads, | |
| 2293 | + preferredIds: optimisticPinnedOrder.order, | |
| 2294 | + getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2295 | + }); | |
| 2296 | + }, [optimisticPinnedOrder, pinnedThreads]); | |
| 2297 | + useEffect(() => { | |
| 2298 | + if (optimisticPinnedOrder === null) return; | |
| 2299 | + const canonical = pinnedThreads.filter((thread) => | |
| 2300 | + reorderablePinnedKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 2301 | + ); | |
| 2302 | + const canonicalKeys = canonical.map((thread) => | |
| 2303 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2304 | + ); | |
| 2305 | + // The override represents one drop against one snapshot of the world. | |
| 2306 | + // Release it as soon as the world moves on in any way: membership | |
| 2307 | + // changed (pin/unpin/snooze/wake — the override can't say where members | |
| 2308 | + // it never saw belong), a key changed (our write confirming, or a | |
| 2309 | + // concurrent client's reorder that must win), or canonical already | |
| 2310 | + // matches. Holding it longer would misplace newcomers and launder the | |
| 2311 | + // stale order into later drags. | |
| 2312 | + const membershipChanged = | |
| 2313 | + canonicalKeys.length !== optimisticPinnedOrder.order.length || | |
| 2314 | + canonicalKeys.some((key) => !optimisticPinnedOrder.order.includes(key)); | |
| 2315 | + const anyKeyLanded = canonical.some( | |
| 2316 | + (thread, index) => | |
| 2317 | + optimisticPinnedOrder.keysAtDrop.get(canonicalKeys[index]!) !== | |
| 2318 | + (thread.pinOrderKey ?? null), | |
| 2319 | + ); | |
| 2320 | + const orderConfirmed = | |
| 2321 | + !membershipChanged && | |
| 2322 | + canonicalKeys.every((key, index) => key === optimisticPinnedOrder.order[index]); | |
| 2323 | + if (membershipChanged || anyKeyLanded || orderConfirmed) { | |
| 2324 | + setOptimisticPinnedOrder(null); | |
| 2325 | + } | |
| 2326 | + }, [optimisticPinnedOrder, pinnedThreads, reorderablePinnedKeys]); | |
| 2327 | + const attemptPin = useCallback( | |
| 2328 | + (threadRef: ScopedThreadRef) => { | |
| 2329 | + void (async () => { | |
| 2330 | + // Fresh pins take the top of the arranged run: pinThread computes a | |
| 2331 | + // key before the smallest key across ALL pinned shells — including | |
| 2332 | + // snoozed pins hidden from this list, whose keys are still part of | |
| 2333 | + // the run — so the new pin can't land beneath a hidden head. | |
| 2334 | + const result = await pinThread(threadRef); | |
| 2335 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2336 | + const error = squashAtomCommandFailure(result); | |
| 2337 | + toastManager.add( | |
| 2338 | + stackedThreadToast({ | |
| 2339 | + type: "error", | |
| 2340 | + title: "Failed to pin thread", | |
| 2341 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2342 | + }), | |
| 2343 | + ); | |
| 2344 | + } | |
| 2345 | + })(); | |
| 2346 | + }, | |
| 2347 | + [pinThread], | |
| 2348 | + ); | |
| 2349 | + const attemptUnpin = useCallback( | |
| 2350 | + (threadRef: ScopedThreadRef) => { | |
| 2351 | + void (async () => { | |
| 2352 | + const result = await unpinThread(threadRef); | |
| 2353 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2354 | + const error = squashAtomCommandFailure(result); | |
| 1800 | 2355 | toastManager.add( |
| 1801 | 2356 | stackedThreadToast({ |
| 1802 | 2357 | type: "error", |
| 1803 | − title: "Thread archived, but navigation failed", | |
| 2358 | + title: "Failed to unpin thread", | |
| 1804 | 2359 | description: error instanceof Error ? error.message : "An error occurred.", |
| 1805 | 2360 | }), |
| 1806 | 2361 | ); |
| 1807 | 2362 | } |
| 1808 | − if (archiveOutcome.mutationFailure) { | |
| 1809 | − removeFromSelection(archiveOutcome.archivedThreadKeys); | |
| 1810 | − if (!isAtomCommandInterrupted(archiveOutcome.mutationFailure)) { | |
| 1811 | − const error = squashAtomCommandFailure(archiveOutcome.mutationFailure); | |
| 2363 | + })(); | |
| 2364 | + }, | |
| 2365 | + [unpinThread], | |
| 2366 | + ); | |
| 2367 | + | |
| 2368 | + const handlePinnedDragEnd = useCallback( | |
| 2369 | + (event: DragEndEvent) => { | |
| 2370 | + const activeKey = String(event.active.id); | |
| 2371 | + const overKey = event.over === null ? null : String(event.over.id); | |
| 2372 | + if (overKey === null || activeKey === overKey) return; | |
| 2373 | + const reorderable = orderedPinnedThreads.filter((thread) => | |
| 2374 | + reorderablePinnedKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 2375 | + ); | |
| 2376 | + const keys = reorderable.map((thread) => | |
| 2377 | + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2378 | + ); | |
| 2379 | + const fromIndex = keys.indexOf(activeKey); | |
| 2380 | + const toIndex = keys.indexOf(overKey); | |
| 2381 | + if (fromIndex === -1 || toIndex === -1) return; | |
| 2382 | + const newOrder = arrayMove([...keys], fromIndex, toIndex); | |
| 2383 | + const threadByKey = new Map(reorderable.map((thread, index) => [keys[index]!, thread])); | |
| 2384 | + const keysAtDrop = new Map( | |
| 2385 | + reorderable.map((thread, index) => [keys[index]!, thread.pinOrderKey ?? null]), | |
| 2386 | + ); | |
| 2387 | + const assignments = planPinnedReorder({ | |
| 2388 | + orderedIds: newOrder, | |
| 2389 | + keysById: keysAtDrop, | |
| 2390 | + movedId: activeKey, | |
| 2391 | + }); | |
| 2392 | + if (assignments.length === 0) return; | |
| 2393 | + setOptimisticPinnedOrder({ order: newOrder, keysAtDrop }); | |
| 2394 | + void (async () => { | |
| 2395 | + // Sequential, stop on first failure. There is deliberately no | |
| 2396 | + // rollback: every key write is a complete, valid placement on its | |
| 2397 | + // own, so a partial materialization leaves a sensible order (and | |
| 2398 | + // the next drag repairs the rest) — unwinding writes across | |
| 2399 | + // servers would trade that for real inconsistency windows. | |
| 2400 | + for (const assignment of assignments) { | |
| 2401 | + const thread = threadByKey.get(assignment.id); | |
| 2402 | + if (thread === undefined) continue; | |
| 2403 | + const result = await reorderPinnedThread( | |
| 2404 | + scopeThreadRef(thread.environmentId, thread.id), | |
| 2405 | + assignment.orderKey, | |
| 2406 | + ); | |
| 2407 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2408 | + setOptimisticPinnedOrder(null); | |
| 2409 | + const error = squashAtomCommandFailure(result); | |
| 1812 | 2410 | toastManager.add( |
| 1813 | 2411 | stackedThreadToast({ |
| 1814 | 2412 | type: "error", |
| 1815 | − title: "Failed to archive threads", | |
| 2413 | + title: "Failed to reorder pinned threads", | |
| 1816 | 2414 | description: error instanceof Error ? error.message : "An error occurred.", |
| 1817 | 2415 | }), |
| 1818 | 2416 | ); |
| 2417 | + return; | |
| 1819 | 2418 | } |
| 1820 | − return; | |
| 1821 | 2419 | } |
| 1822 | − removeFromSelection(threadKeys); | |
| 1823 | − return; | |
| 2420 | + })(); | |
| 2421 | + }, | |
| 2422 | + [orderedPinnedThreads, reorderPinnedThread, reorderablePinnedKeys], | |
| 2423 | + ); | |
| 2424 | + // One snooze per thread at a time — same double-dispatch guard as settle. | |
| 2425 | + const snoozingThreadKeysRef = useRef(new Set<string>()); | |
| 2426 | + const performSnooze = useCallback( | |
| 2427 | + async ( | |
| 2428 | + threadRef: ScopedThreadRef, | |
| 2429 | + preset: SnoozePreset, | |
| 2430 | + opts: { coSnoozingKeys?: ReadonlySet<string> } = {}, | |
| 2431 | + ) => { | |
| 2432 | + const threadKey = scopedThreadKey(threadRef); | |
| 2433 | + if (snoozingThreadKeysRef.current.has(threadKey)) { | |
| 2434 | + return { status: "skipped" } as const; | |
| 1824 | 2435 | } |
| 2436 | + snoozingThreadKeysRef.current.add(threadKey); | |
| 2437 | + try { | |
| 2438 | + // Snoozing the open thread moves you forward, same as settle — | |
| 2439 | + // both park the thread you're done with for now. | |
| 2440 | + const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys); | |
| 2441 | + const result = await snoozeThread(threadRef, preset.snoozedUntil); | |
| 2442 | + if (result._tag === "Failure") { | |
| 2443 | + // Never navigate away from a thread that did not snooze. | |
| 2444 | + return isAtomCommandInterrupted(result) | |
| 2445 | + ? ({ status: "interrupted" } as const) | |
| 2446 | + : ({ status: "failure", error: squashAtomCommandFailure(result) } as const); | |
| 2447 | + } | |
| 2448 | + // Only move forward if the user is still on the snoozed thread — | |
| 2449 | + // a navigation made during the await wins over ours. | |
| 2450 | + if (routeThreadKeyRef.current === threadKey) { | |
| 2451 | + navigateAfterSnooze?.(); | |
| 2452 | + } | |
| 2453 | + return { status: "success" } as const; | |
| 2454 | + } finally { | |
| 2455 | + snoozingThreadKeysRef.current.delete(threadKey); | |
| 2456 | + } | |
| 2457 | + }, | |
| 2458 | + [planForwardNavigation, snoozeThread], | |
| 2459 | + ); | |
| 2460 | + const attemptSnooze = useCallback( | |
| 2461 | + ( | |
| 2462 | + threadRef: ScopedThreadRef, | |
| 2463 | + preset: SnoozePreset, | |
| 2464 | + opts: { coSnoozingKeys?: ReadonlySet<string> } = {}, | |
| 2465 | + ) => { | |
| 2466 | + void (async () => { | |
| 2467 | + const outcome = await performSnooze(threadRef, preset, opts); | |
| 2468 | + if (outcome.status === "failure") { | |
| 2469 | + toastManager.add( | |
| 2470 | + stackedThreadToast({ | |
| 2471 | + type: "error", | |
| 2472 | + title: "Failed to snooze thread", | |
| 2473 | + description: | |
| 2474 | + outcome.error instanceof Error ? outcome.error.message : "An error occurred.", | |
| 2475 | + }), | |
| 2476 | + ); | |
| 2477 | + return; | |
| 2478 | + } | |
| 2479 | + if (outcome.status !== "success") return; | |
| 2480 | + // Snooze hides the row, so the toast is the only confirmation — | |
| 2481 | + // and the Undo is the escape hatch for a mis-click. | |
| 2482 | + toastManager.add( | |
| 2483 | + stackedThreadToast({ | |
| 2484 | + type: "success", | |
| 2485 | + title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`, | |
| 2486 | + timeout: 5_000, | |
| 2487 | + actionProps: { | |
| 2488 | + children: "Undo", | |
| 2489 | + onClick: () => attemptUnsnooze(threadRef), | |
| 2490 | + }, | |
| 2491 | + }), | |
| 2492 | + ); | |
| 2493 | + })(); | |
| 2494 | + }, | |
| 2495 | + [attemptUnsnooze, performSnooze, timestampFormat], | |
| 2496 | + ); | |
| 1825 | 2497 | |
| 1826 | − if (clicked !== "delete") return; | |
| 1827 | − | |
| 1828 | − if (appSettingsConfirmThreadDelete) { | |
| 1829 | − const confirmed = await api.dialogs.confirm( | |
| 2498 | + const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection); | |
| 2499 | + const handleMultiSelectContextMenu = useCallback( | |
| 2500 | + async (position: { x: number; y: number }) => { | |
| 2501 | + const api = readLocalApi(); | |
| 2502 | + if (!api) return; | |
| 2503 | + // One exact actionable set: keys whose rows are actually rendered | |
| 2504 | + // right now. Selections can outlive their rows (settled-tail paging, | |
| 2505 | + // thread deletion elsewhere) and the menu labels must count only what | |
| 2506 | + // the actions will touch. | |
| 2507 | + const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys].filter( | |
| 2508 | + (threadKey) => threadByKeyRef.current.has(threadKey), | |
| 2509 | + ); | |
| 2510 | + if (threadKeys.length === 0) return; | |
| 2511 | + const count = threadKeys.length; | |
| 2512 | + // Snooze (N) is offered when every selected thread can actually take | |
| 2513 | + // it — a mixed selection with blocked-on-you work would half-apply. | |
| 2514 | + const selectionNow = new Date(); | |
| 2515 | + const selectedThreads = threadKeys.flatMap((threadKey) => { | |
| 2516 | + const thread = threadByKeyRef.current.get(threadKey); | |
| 2517 | + return thread ? [thread] : []; | |
| 2518 | + }); | |
| 2519 | + const canSnoozeSelection = selectedThreads.every( | |
| 2520 | + (thread) => | |
| 2521 | + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true && | |
| 2522 | + canSnooze(thread, { now: selectionNow.toISOString() }), | |
| 2523 | + ); | |
| 2524 | + const titleRegenerationThreads = selectedThreads.filter( | |
| 2525 | + (thread) => | |
| 2526 | + serverConfigs.get(thread.environmentId)?.environment.capabilities | |
| 2527 | + .threadTitleRegeneration === true, | |
| 2528 | + ); | |
| 2529 | + const regeneratableTitleThreads = titleRegenerationThreads.filter( | |
| 2530 | + (thread) => thread.titleRegeneration == null, | |
| 2531 | + ); | |
| 2532 | + const titleRegenerationMenuItem = buildBulkTitleRegenerationContextMenuItem({ | |
| 2533 | + supportedCount: titleRegenerationThreads.length, | |
| 2534 | + actionableCount: regeneratableTitleThreads.length, | |
| 2535 | + }); | |
| 2536 | + const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); | |
| 2537 | + const clicked = await settlePromise(() => | |
| 2538 | + api.contextMenu.show( | |
| 1830 | 2539 | [ |
| 1831 | − `Delete ${count} thread${count === 1 ? "" : "s"}?`, | |
| 1832 | − "This permanently clears conversation history for these threads.", | |
| 1833 | − ].join("\n"), | |
| 2540 | + { id: "settle", label: `Settle (${count})` }, | |
| 2541 | + ...(canSnoozeSelection | |
| 2542 | + ? [ | |
| 2543 | + { | |
| 2544 | + id: "snooze", | |
| 2545 | + label: `Snooze (${count})`, | |
| 2546 | + children: snoozePresets.map((preset) => ({ | |
| 2547 | + id: `snooze:${preset.id}`, | |
| 2548 | + label: `${preset.label} (${preset.whenLabel})`, | |
| 2549 | + })), | |
| 2550 | + }, | |
| 2551 | + ] | |
| 2552 | + : []), | |
| 2553 | + ...(titleRegenerationMenuItem ? [titleRegenerationMenuItem] : []), | |
| 2554 | + { id: "mark-unread", label: `Mark unread (${count})` }, | |
| 2555 | + { id: "delete", label: `Delete (${count})`, destructive: true }, | |
| 2556 | + ], | |
| 2557 | + position, | |
| 2558 | + ), | |
| 2559 | + ); | |
| 2560 | + if (clicked._tag === "Failure") return; | |
| 2561 | + if (clicked.value?.startsWith("snooze:")) { | |
| 2562 | + const preset = snoozePresets.find( | |
| 2563 | + (candidate) => `snooze:${candidate.id}` === clicked.value, | |
| 1834 | 2564 | ); |
| 1835 | − if (!confirmed) return; | |
| 1836 | − } | |
| 2565 | + if (preset) { | |
| 2566 | + // Post-snooze navigation must skip threads snoozing in this same | |
| 2567 | + // batch — they are all leaving the card block together. | |
| 2568 | + const coSnoozingKeys = new Set(threadKeys); | |
| 2569 | + clearSelection(); | |
| 2570 | + const outcomes = await Promise.all( | |
| 2571 | + selectedThreads.map(async (thread) => { | |
| 2572 | + const threadRef = scopeThreadRef(thread.environmentId, thread.id); | |
| 2573 | + const outcome = await performSnooze(threadRef, preset, { coSnoozingKeys }); | |
| 2574 | + return { outcome, threadRef }; | |
| 2575 | + }), | |
| 2576 | + ); | |
| 2577 | + const snoozedThreadRefs = outcomes.flatMap(({ outcome, threadRef }) => | |
| 2578 | + outcome.status === "success" ? [threadRef] : [], | |
| 2579 | + ); | |
| 2580 | + const failures = outcomes.flatMap(({ outcome }) => | |
| 2581 | + outcome.status === "failure" ? [outcome.error] : [], | |
| 2582 | + ); | |
| 1837 | 2583 | |
| 1838 | − const deletedThreadKeys = new Set(threadKeys); | |
| 1839 | − for (const { threadRef } of selectedThreadEntries) { | |
| 1840 | − const result = await deleteThread(threadRef, { | |
| 2584 | + if (snoozedThreadRefs.length > 0) { | |
| 2585 | + const snoozedCount = snoozedThreadRefs.length; | |
| 2586 | + const failedCount = failures.length; | |
| 2587 | + toastManager.add( | |
| 2588 | + stackedThreadToast({ | |
| 2589 | + type: failedCount > 0 ? "warning" : "success", | |
| 2590 | + title: | |
| 2591 | + failedCount > 0 | |
| 2592 | + ? `Snoozed ${snoozedCount} of ${selectedThreads.length} threads` | |
| 2593 | + : `Snoozed ${snoozedCount} thread${snoozedCount === 1 ? "" : "s"}`, | |
| 2594 | + description: | |
| 2595 | + failedCount > 0 | |
| 2596 | + ? `${failedCount} thread${failedCount === 1 ? "" : "s"} couldn't be snoozed.` | |
| 2597 | + : undefined, | |
| 2598 | + timeout: 5_000, | |
| 2599 | + actionProps: { | |
| 2600 | + children: "Undo", | |
| 2601 | + onClick: () => { | |
| 2602 | + for (const threadRef of snoozedThreadRefs) attemptUnsnooze(threadRef); | |
| 2603 | + }, | |
| 2604 | + }, | |
| 2605 | + }), | |
| 2606 | + ); | |
| 2607 | + } else if (failures.length > 0) { | |
| 2608 | + const firstError = failures[0]; | |
| 2609 | + toastManager.add( | |
| 2610 | + stackedThreadToast({ | |
| 2611 | + type: "error", | |
| 2612 | + title: "Failed to snooze threads", | |
| 2613 | + description: | |
| 2614 | + firstError instanceof Error ? firstError.message : "An error occurred.", | |
| 2615 | + }), | |
| 2616 | + ); | |
| 2617 | + } | |
| 2618 | + } | |
| 2619 | + return; | |
| 2620 | + } | |
| 2621 | + if (clicked.value === "regenerate-title") { | |
| 2622 | + for (const thread of regeneratableTitleThreads) { | |
| 2623 | + const result = await updateThreadMetadata({ | |
| 2624 | + environmentId: thread.environmentId, | |
| 2625 | + input: { threadId: thread.id, regenerateTitle: true }, | |
| 2626 | + }); | |
| 2627 | + if (result._tag === "Success") continue; | |
| 2628 | + if (!isAtomCommandInterrupted(result)) { | |
| 2629 | + const error = squashAtomCommandFailure(result); | |
| 2630 | + toastManager.add( | |
| 2631 | + stackedThreadToast({ | |
| 2632 | + type: "error", | |
| 2633 | + title: "Failed to regenerate thread titles", | |
| 2634 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2635 | + }), | |
| 2636 | + ); | |
| 2637 | + } | |
| 2638 | + return; | |
| 2639 | + } | |
| 2640 | + clearSelection(); | |
| 2641 | + return; | |
| 2642 | + } | |
| 2643 | + if (clicked.value === "settle") { | |
| 2644 | + // Post-settle navigation must skip threads settling in this same | |
| 2645 | + // batch — they are all leaving the card block together. Rows that | |
| 2646 | + // are already explicitly settled are skipped: nothing to do on a | |
| 2647 | + // valid mixed selection. Pinned rows ARE included: the decider | |
| 2648 | + // clears the pin as part of settling, so they park like the rest. | |
| 2649 | + const coSettlingKeys = new Set(threadKeys); | |
| 2650 | + for (const threadKey of threadKeys) { | |
| 2651 | + const thread = threadByKeyRef.current.get(threadKey); | |
| 2652 | + if (!thread || thread.settledOverride === "settled") continue; | |
| 2653 | + attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys }); | |
| 2654 | + } | |
| 2655 | + clearSelection(); | |
| 2656 | + return; | |
| 2657 | + } | |
| 2658 | + if (clicked.value === "mark-unread") { | |
| 2659 | + for (const threadKey of threadKeys) { | |
| 2660 | + const thread = threadByKeyRef.current.get(threadKey); | |
| 2661 | + markThreadUnread(threadKey, thread?.latestTurn?.completedAt); | |
| 2662 | + } | |
| 2663 | + clearSelection(); | |
| 2664 | + return; | |
| 2665 | + } | |
| 2666 | + if (clicked.value !== "delete") return; | |
| 2667 | + if (confirmThreadDelete) { | |
| 2668 | + const confirmed = await settlePromise(() => | |
| 2669 | + api.dialogs.confirm( | |
| 2670 | + [ | |
| 2671 | + `Delete ${count} thread${count === 1 ? "" : "s"}?`, | |
| 2672 | + "This permanently clears conversation history for these threads.", | |
| 2673 | + ].join("\n"), | |
| 2674 | + ), | |
| 2675 | + ); | |
| 2676 | + if (confirmed._tag === "Failure" || !confirmed.value) return; | |
| 2677 | + } | |
| 2678 | + // Grown as deletions actually land, never seeded with the whole batch: | |
| 2679 | + // orphaned-worktree detection must only discount threads that are | |
| 2680 | + // really gone, or the first delete would treat still-alive batch mates | |
| 2681 | + // as deleted and remove a worktree they still point at. | |
| 2682 | + const deletedThreadKeys = new Set<string>(); | |
| 2683 | + for (const threadKey of threadKeys) { | |
| 2684 | + const thread = threadByKeyRef.current.get(threadKey); | |
| 2685 | + if (!thread) continue; | |
| 2686 | + const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id), { | |
| 1841 | 2687 | deletedThreadKeys, |
| 1842 | 2688 | }); |
| 1843 | 2689 | if (result._tag === "Failure") { |
| @@ -1853,1784 +2699,1013 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec · 9 unmodified lines | ||
| 1853 | 2699 | } |
| 1854 | 2700 | return; |
| 1855 | 2701 | } |
| 2702 | + deletedThreadKeys.add(threadKey); | |
| 1856 | 2703 | } |
| 1857 | 2704 | removeFromSelection(threadKeys); |
| 1858 | 2705 | }, |
| 1859 | 2706 | [ |
| 1860 | − appSettingsConfirmThreadArchive, | |
| 1861 | − appSettingsConfirmThreadDelete, | |
| 1862 | − archiveThread, | |
| 2707 | + attemptSettle, | |
| 2708 | + attemptSnooze, | |
| 1863 | 2709 | clearSelection, |
| 2710 | + confirmThreadDelete, | |
| 1864 | 2711 | deleteThread, |
| 1865 | 2712 | markThreadUnread, |
| 2713 | + performSnooze, | |
| 1866 | 2714 | removeFromSelection, |
| 2715 | + serverConfigs, | |
| 2716 | + attemptUnsnooze, | |
| 2717 | + updateThreadMetadata, | |
| 2718 | + timestampFormat, | |
| 1867 | 2719 | ], |
| 1868 | 2720 | ); |
| 1869 | 2721 | |
| 1870 | − const createThreadForProjectMember = useCallback( | |
| 1871 | − (member: SidebarProjectGroupMember) => { | |
| 1872 | − if (isMobile) { | |
| 1873 | − setOpenMobile(false); | |
| 1874 | − } | |
| 1875 | − void (async () => { | |
| 1876 | − // No options: branch, worktree, and env mode come from the user's | |
| 1877 | − // configured defaults, never from the currently viewed thread. | |
| 1878 | − const result = await settlePromise(() => | |
| 1879 | − handleNewThread(scopeProjectRef(member.environmentId, member.id)), | |
| 1880 | − ); | |
| 1881 | − if (result._tag === "Failure") { | |
| 1882 | − const error = squashAtomCommandFailure(result); | |
| 1883 | − toastManager.add( | |
| 1884 | − stackedThreadToast({ | |
| 1885 | − type: "error", | |
| 1886 | − title: "Could not create thread", | |
| 1887 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 1888 | − }), | |
| 1889 | − ); | |
| 1890 | − } | |
| 1891 | − })(); | |
| 1892 | − }, | |
| 1893 | − [handleNewThread, isMobile, setOpenMobile], | |
| 1894 | − ); | |
| 1895 | − | |
| 1896 | − const handleCreateThreadClick = useCallback( | |
| 1897 | − (event: React.MouseEvent<HTMLButtonElement>) => { | |
| 1898 | − event.preventDefault(); | |
| 1899 | − event.stopPropagation(); | |
| 1900 | − | |
| 1901 | − if (project.memberProjects.length === 1) { | |
| 1902 | − createThreadForProjectMember(project.memberProjects[0]!); | |
| 1903 | − return; | |
| 1904 | − } | |
| 1905 | − | |
| 2722 | + const handleThreadContextMenu = useCallback( | |
| 2723 | + (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { | |
| 1906 | 2724 | void (async () => { |
| 1907 | 2725 | const api = readLocalApi(); |
| 1908 | − if (!api) { | |
| 2726 | + if (!api) return; | |
| 2727 | + const threadKey = scopedThreadKey(threadRef); | |
| 2728 | + const selectionState = useThreadSelectionStore.getState(); | |
| 2729 | + if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { | |
| 2730 | + await handleMultiSelectContextMenu(position); | |
| 1909 | 2731 | return; |
| 1910 | 2732 | } |
| 1911 | − const clickedResult = await settlePromise(() => | |
| 2733 | + const thread = threadByKeyRef.current.get(threadKey); | |
| 2734 | + if (!thread) return; | |
| 2735 | + const threadWorkspacePath = | |
| 2736 | + thread.worktreePath ?? | |
| 2737 | + projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? | |
| 2738 | + null; | |
| 2739 | + // Un-settle works on every settled row: for explicit settles it | |
| 2740 | + // clears the override, for auto-settled rows it pins the thread | |
| 2741 | + // active until real activity clears the pin. Environments without | |
| 2742 | + // the settlement capability get no lifecycle items at all. | |
| 2743 | + const supportsSettlement = | |
| 2744 | + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === | |
| 2745 | + true; | |
| 2746 | + const supportsSnooze = | |
| 2747 | + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; | |
| 2748 | + const supportsPinning = | |
| 2749 | + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadPinning === true; | |
| 2750 | + const supportsTitleRegeneration = | |
| 2751 | + serverConfigs.get(thread.environmentId)?.environment.capabilities | |
| 2752 | + .threadTitleRegeneration === true; | |
| 2753 | + const isRegeneratingTitle = thread.titleRegeneration != null; | |
| 2754 | + const isSettled = settledThreadKeysRef.current.has(threadKey); | |
| 2755 | + const isSnoozed = snoozedThreadKeysRef.current.has(threadKey); | |
| 2756 | + const isPinned = thread.pinnedAt != null; | |
| 2757 | + // Presets resolve at menu-open time (same as the popover). | |
| 2758 | + const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); | |
| 2759 | + const clicked = await settlePromise(() => | |
| 1912 | 2760 | api.contextMenu.show( |
| 1913 | − project.memberProjects.map((member) => ({ | |
| 1914 | − id: member.physicalProjectKey, | |
| 1915 | − label: formatProjectMemberActionLabel(member, project.groupedProjectCount), | |
| 1916 | − })), | |
| 1917 | − { | |
| 1918 | − x: event.clientX, | |
| 1919 | − y: event.clientY, | |
| 1920 | − }, | |
| 2761 | + buildThreadActionMenuItems({ | |
| 2762 | + branch: thread.branch ?? null, | |
| 2763 | + isPinned, | |
| 2764 | + isSettled, | |
| 2765 | + isSnoozed, | |
| 2766 | + canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), | |
| 2767 | + isRegeneratingTitle, | |
| 2768 | + supports: { | |
| 2769 | + settlement: supportsSettlement, | |
| 2770 | + snooze: supportsSnooze, | |
| 2771 | + pinning: supportsPinning, | |
| 2772 | + titleRegeneration: supportsTitleRegeneration, | |
| 2773 | + }, | |
| 2774 | + snoozePresets, | |
| 2775 | + }), | |
| 2776 | + position, | |
| 1921 | 2777 | ), |
| 1922 | 2778 | ); |
| 1923 | − if (clickedResult._tag === "Failure") { | |
| 1924 | − const error = squashAtomCommandFailure(clickedResult); | |
| 1925 | − toastManager.add( | |
| 1926 | − stackedThreadToast({ | |
| 1927 | − type: "error", | |
| 1928 | − title: "Could not choose environment", | |
| 1929 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 1930 | − }), | |
| 2779 | + if (clicked._tag === "Failure") return; | |
| 2780 | + if (clicked.value?.startsWith("snooze:")) { | |
| 2781 | + const preset = snoozePresets.find( | |
| 2782 | + (candidate) => `snooze:${candidate.id}` === clicked.value, | |
| 1931 | 2783 | ); |
| 2784 | + if (preset) attemptSnooze(threadRef, preset); | |
| 1932 | 2785 | return; |
| 1933 | 2786 | } |
| 1934 | − const clicked = clickedResult.value; | |
| 1935 | − if (!clicked) { | |
| 1936 | − return; | |
| 2787 | + switch (clicked.value) { | |
| 2788 | + case "new-thread-on-branch": { | |
| 2789 | + // Explicit branch carry-over: reuse the thread's worktree when it | |
| 2790 | + // has one, otherwise its branch on the local checkout. | |
| 2791 | + const result = await settlePromise(() => | |
| 2792 | + handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId), { | |
| 2793 | + branch: thread.branch, | |
| 2794 | + worktreePath: thread.worktreePath, | |
| 2795 | + envMode: thread.worktreePath ? "worktree" : "local", | |
| 2796 | + startFromOrigin: false, | |
| 2797 | + }), | |
| 2798 | + ); | |
| 2799 | + if (result._tag === "Failure") { | |
| 2800 | + const error = squashAtomCommandFailure(result); | |
| 2801 | + toastManager.add( | |
| 2802 | + stackedThreadToast({ | |
| 2803 | + type: "error", | |
| 2804 | + title: "Could not create thread", | |
| 2805 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2806 | + }), | |
| 2807 | + ); | |
| 2808 | + } | |
| 2809 | + return; | |
| 2810 | + } | |
| 2811 | + case "settle": | |
| 2812 | + attemptSettle(threadRef); | |
| 2813 | + return; | |
| 2814 | + case "unsettle": | |
| 2815 | + attemptUnsettle(threadRef); | |
| 2816 | + return; | |
| 2817 | + case "unsnooze": | |
| 2818 | + attemptUnsnooze(threadRef); | |
| 2819 | + return; | |
| 2820 | + case "pin": | |
| 2821 | + attemptPin(threadRef); | |
| 2822 | + return; | |
| 2823 | + case "unpin": | |
| 2824 | + attemptUnpin(threadRef); | |
| 2825 | + return; | |
| 2826 | + case "rename": | |
| 2827 | + startThreadRename(threadRef, thread.title); | |
| 2828 | + return; | |
| 2829 | + case "regenerate-title": { | |
| 2830 | + if (isRegeneratingTitle) return; | |
| 2831 | + const result = await updateThreadMetadata({ | |
| 2832 | + environmentId: threadRef.environmentId, | |
| 2833 | + input: { threadId: threadRef.threadId, regenerateTitle: true }, | |
| 2834 | + }); | |
| 2835 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2836 | + const error = squashAtomCommandFailure(result); | |
| 2837 | + toastManager.add( | |
| 2838 | + stackedThreadToast({ | |
| 2839 | + type: "error", | |
| 2840 | + title: "Failed to regenerate thread title", | |
| 2841 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2842 | + }), | |
| 2843 | + ); | |
| 2844 | + } | |
| 2845 | + return; | |
| 2846 | + } | |
| 2847 | + case "mark-unread": | |
| 2848 | + markThreadUnread(threadKey, thread.latestTurn?.completedAt); | |
| 2849 | + return; | |
| 2850 | + case "copy-path": | |
| 2851 | + if (!threadWorkspacePath) { | |
| 2852 | + toastManager.add( | |
| 2853 | + stackedThreadToast({ | |
| 2854 | + type: "error", | |
| 2855 | + title: "Path unavailable", | |
| 2856 | + description: "This thread does not have a workspace path to copy.", | |
| 2857 | + }), | |
| 2858 | + ); | |
| 2859 | + return; | |
| 2860 | + } | |
| 2861 | + copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); | |
| 2862 | + return; | |
| 2863 | + case "copy-branch": | |
| 2864 | + if (thread.branch) { | |
| 2865 | + copyBranchToClipboard(thread.branch, { branch: thread.branch }); | |
| 2866 | + } | |
| 2867 | + return; | |
| 2868 | + case "delete": { | |
| 2869 | + if (confirmThreadDelete) { | |
| 2870 | + const confirmed = await settlePromise(() => | |
| 2871 | + api.dialogs.confirm( | |
| 2872 | + [ | |
| 2873 | + `Delete thread "${thread.title}"?`, | |
| 2874 | + "This permanently clears conversation history for this thread.", | |
| 2875 | + ].join("\n"), | |
| 2876 | + ), | |
| 2877 | + ); | |
| 2878 | + if (confirmed._tag === "Failure" || !confirmed.value) return; | |
| 2879 | + } | |
| 2880 | + const result = await deleteThread(threadRef); | |
| 2881 | + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2882 | + const error = squashAtomCommandFailure(result); | |
| 2883 | + toastManager.add( | |
| 2884 | + stackedThreadToast({ | |
| 2885 | + type: "error", | |
| 2886 | + title: "Failed to delete thread", | |
| 2887 | + description: error instanceof Error ? error.message : "An error occurred.", | |
| 2888 | + }), | |
| 2889 | + ); | |
| 2890 | + return; | |
| 2891 | + } | |
| 2892 | + return; | |
| 2893 | + } | |
| 2894 | + default: | |
| 2895 | + return; | |
| 1937 | 2896 | } |
| 1938 | − const targetMember = project.memberProjects.find( | |
| 1939 | − (member) => member.physicalProjectKey === clicked, | |
| 1940 | − ); | |
| 1941 | − if (!targetMember) { | |
| 1942 | − return; | |
| 1943 | − } | |
| 1944 | − createThreadForProjectMember(targetMember); | |
| 1945 | − })(); | |
| 1946 | − }, | |
| 1947 | − [createThreadForProjectMember, project.groupedProjectCount, project.memberProjects], | |
| 1948 | − ); | |
| 1949 | − | |
| 1950 | − const attemptArchiveThread = useCallback( | |
| 1951 | − async (threadRef: ScopedThreadRef) => { | |
| 1952 | − const result = await archiveThread(threadRef); | |
| 1953 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 1954 | − const error = squashAtomCommandFailure(result); | |
| 1955 | − toastManager.add( | |
| 1956 | − stackedThreadToast({ | |
| 1957 | − type: "error", | |
| 1958 | − title: "Failed to archive thread", | |
| 1959 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 1960 | − }), | |
| 1961 | − ); | |
| 1962 | − } | |
| 1963 | − }, | |
| 1964 | − [archiveThread], | |
| 1965 | − ); | |
| 1966 | − | |
| 1967 | − const cancelRename = useCallback(() => { | |
| 1968 | − setRenamingThreadKey(null); | |
| 1969 | − renamingInputRef.current = null; | |
| 1970 | − }, []); | |
| 1971 | − | |
| 1972 | − const startThreadRename = useCallback((threadKey: string, title: string) => { | |
| 1973 | − setRenamingThreadKey(threadKey); | |
| 1974 | − setRenamingTitle(title); | |
| 1975 | − renamingCommittedRef.current = false; | |
| 1976 | − }, []); | |
| 1977 | − | |
| 1978 | − const commitRename = useCallback( | |
| 1979 | − async (threadRef: ScopedThreadRef, newTitle: string, originalTitle: string) => { | |
| 1980 | − const threadKey = scopedThreadKey(threadRef); | |
| 1981 | − const finishRename = () => { | |
| 1982 | − setRenamingThreadKey((current) => { | |
| 1983 | − if (current !== threadKey) return current; | |
| 1984 | − renamingInputRef.current = null; | |
| 1985 | − return null; | |
| 1986 | − }); | |
| 1987 | − }; | |
| 1988 | − | |
| 1989 | − const trimmed = newTitle.trim(); | |
| 1990 | − if (trimmed.length === 0) { | |
| 1991 | − toastManager.add({ | |
| 1992 | − type: "warning", | |
| 1993 | − title: "Thread title cannot be empty", | |
| 1994 | − }); | |
| 1995 | − finishRename(); | |
| 1996 | − return; | |
| 1997 | − } | |
| 1998 | − if (trimmed === originalTitle) { | |
| 1999 | − finishRename(); | |
| 2000 | − return; | |
| 2001 | − } | |
| 2002 | − const result = await updateThreadMetadata({ | |
| 2003 | − environmentId: threadRef.environmentId, | |
| 2004 | − input: { | |
| 2005 | − threadId: threadRef.threadId, | |
| 2006 | − title: trimmed, | |
| 2007 | − }, | |
| 2008 | − }); | |
| 2009 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2010 | − const error = squashAtomCommandFailure(result); | |
| 2011 | − toastManager.add( | |
| 2012 | − stackedThreadToast({ | |
| 2013 | − type: "error", | |
| 2014 | − title: "Failed to rename thread", | |
| 2015 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2016 | − }), | |
| 2017 | − ); | |
| 2018 | − } | |
| 2019 | − finishRename(); | |
| 2020 | − }, | |
| 2021 | − [updateThreadMetadata], | |
| 2022 | − ); | |
| 2023 | − | |
| 2024 | − const closeProjectRenameDialog = useCallback(() => { | |
| 2025 | − setProjectRenameTarget(null); | |
| 2026 | − setProjectRenameTitle(""); | |
| 2027 | − }, []); | |
| 2028 | − | |
| 2029 | − const submitProjectRename = useCallback(async () => { | |
| 2030 | − if (!projectRenameTarget) { | |
| 2031 | − return; | |
| 2032 | − } | |
| 2033 | − | |
| 2034 | − const trimmed = projectRenameTitle.trim(); | |
| 2035 | − if (trimmed.length === 0) { | |
| 2036 | − toastManager.add({ | |
| 2037 | − type: "warning", | |
| 2038 | − title: "Project title cannot be empty", | |
| 2039 | − }); | |
| 2040 | − return; | |
| 2041 | − } | |
| 2042 | − | |
| 2043 | − if (trimmed === projectRenameTarget.title) { | |
| 2044 | − closeProjectRenameDialog(); | |
| 2045 | − return; | |
| 2046 | − } | |
| 2047 | − | |
| 2048 | − const result = await updateProject({ | |
| 2049 | − environmentId: projectRenameTarget.environmentId, | |
| 2050 | − input: { | |
| 2051 | − projectId: projectRenameTarget.id, | |
| 2052 | − title: trimmed, | |
| 2053 | − }, | |
| 2054 | − }); | |
| 2055 | − if (result._tag === "Success") { | |
| 2056 | − closeProjectRenameDialog(); | |
| 2057 | − } else if (!isAtomCommandInterrupted(result)) { | |
| 2058 | − const error = squashAtomCommandFailure(result); | |
| 2059 | − toastManager.add( | |
| 2060 | − stackedThreadToast({ | |
| 2061 | − type: "error", | |
| 2062 | − title: "Failed to rename project", | |
| 2063 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2064 | − }), | |
| 2065 | − ); | |
| 2066 | − } | |
| 2067 | − }, [closeProjectRenameDialog, projectRenameTarget, projectRenameTitle, updateProject]); | |
| 2068 | − | |
| 2069 | − const closeProjectGroupingDialog = useCallback(() => { | |
| 2070 | − setProjectGroupingTarget(null); | |
| 2071 | − setProjectGroupingSelection("inherit"); | |
| 2072 | − }, []); | |
| 2073 | − | |
| 2074 | − const saveProjectGroupingPreference = useCallback(() => { | |
| 2075 | − if (!projectGroupingTarget) { | |
| 2076 | − return; | |
| 2077 | − } | |
| 2078 | − | |
| 2079 | − const overrideKey = deriveProjectGroupingOverrideKey(projectGroupingTarget); | |
| 2080 | − const nextOverrides = { | |
| 2081 | − ...projectGroupingSettings.sidebarProjectGroupingOverrides, | |
| 2082 | − }; | |
| 2083 | − if (projectGroupingSelection === "inherit") { | |
| 2084 | − delete nextOverrides[overrideKey]; | |
| 2085 | − } else { | |
| 2086 | − nextOverrides[overrideKey] = projectGroupingSelection; | |
| 2087 | − } | |
| 2088 | − updateSettings({ | |
| 2089 | − sidebarProjectGroupingOverrides: nextOverrides, | |
| 2090 | − }); | |
| 2091 | − closeProjectGroupingDialog(); | |
| 2092 | − }, [ | |
| 2093 | − closeProjectGroupingDialog, | |
| 2094 | − projectGroupingSelection, | |
| 2095 | − projectGroupingSettings.sidebarProjectGroupingOverrides, | |
| 2096 | − projectGroupingTarget, | |
| 2097 | − updateSettings, | |
| 2098 | − ]); | |
| 2099 | − | |
| 2100 | − const handleThreadContextMenu = useCallback( | |
| 2101 | − async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { | |
| 2102 | − const api = readLocalApi(); | |
| 2103 | − if (!api) return; | |
| 2104 | − const threadKey = scopedThreadKey(threadRef); | |
| 2105 | − const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null; | |
| 2106 | − if (!thread) return; | |
| 2107 | − const threadProject = memberProjectByScopedKey.get( | |
| 2108 | − scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), | |
| 2109 | − ); | |
| 2110 | − const threadWorkspacePath = | |
| 2111 | − thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null; | |
| 2112 | − const clicked = await api.contextMenu.show( | |
| 2113 | − [ | |
| 2114 | − ...(thread.branch | |
| 2115 | − ? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }] | |
| 2116 | − : []), | |
| 2117 | − { id: "rename", label: "Rename thread" }, | |
| 2118 | − { id: "mark-unread", label: "Mark unread" }, | |
| 2119 | − { id: "copy-path", label: "Copy Path" }, | |
| 2120 | − { id: "copy-thread-id", label: "Copy Thread ID" }, | |
| 2121 | − { id: "delete", label: "Delete", destructive: true, icon: "trash" }, | |
| 2122 | − ], | |
| 2123 | − position, | |
| 2124 | − ); | |
| 2125 | − | |
| 2126 | − if (clicked === "new-thread-on-branch") { | |
| 2127 | − // Explicit branch carry-over: reuse the thread's worktree when it | |
| 2128 | − // has one, otherwise its branch on the local checkout. | |
| 2129 | − const result = await settlePromise(() => | |
| 2130 | − handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), { | |
| 2131 | − branch: thread.branch, | |
| 2132 | − worktreePath: thread.worktreePath, | |
| 2133 | − envMode: thread.worktreePath ? "worktree" : "local", | |
| 2134 | − startFromOrigin: false, | |
| 2135 | − }), | |
| 2136 | − ); | |
| 2137 | − if (result._tag === "Failure") { | |
| 2138 | − const error = squashAtomCommandFailure(result); | |
| 2139 | − toastManager.add( | |
| 2140 | − stackedThreadToast({ | |
| 2141 | − type: "error", | |
| 2142 | − title: "Could not create thread", | |
| 2143 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2144 | − }), | |
| 2145 | − ); | |
| 2146 | − } | |
| 2147 | − return; | |
| 2148 | − } | |
| 2149 | − | |
| 2150 | − if (clicked === "rename") { | |
| 2151 | − startThreadRename(threadKey, thread.title); | |
| 2152 | − return; | |
| 2153 | − } | |
| 2154 | − | |
| 2155 | − if (clicked === "mark-unread") { | |
| 2156 | − markThreadUnread(threadKey, thread.latestTurn?.completedAt); | |
| 2157 | − return; | |
| 2158 | − } | |
| 2159 | − if (clicked === "copy-path") { | |
| 2160 | − if (!threadWorkspacePath) { | |
| 2161 | − toastManager.add( | |
| 2162 | − stackedThreadToast({ | |
| 2163 | − type: "error", | |
| 2164 | − title: "Path unavailable", | |
| 2165 | − description: "This thread does not have a workspace path to copy.", | |
| 2166 | − }), | |
| 2167 | − ); | |
| 2168 | − return; | |
| 2169 | − } | |
| 2170 | − copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); | |
| 2171 | − return; | |
| 2172 | − } | |
| 2173 | − if (clicked === "copy-thread-id") { | |
| 2174 | − copyThreadIdToClipboard(thread.id, { threadId: thread.id }); | |
| 2175 | − return; | |
| 2176 | − } | |
| 2177 | − if (clicked !== "delete") return; | |
| 2178 | − if (appSettingsConfirmThreadDelete) { | |
| 2179 | − const confirmed = await api.dialogs.confirm( | |
| 2180 | − [ | |
| 2181 | − `Delete thread "${thread.title}"?`, | |
| 2182 | − "This permanently clears conversation history for this thread.", | |
| 2183 | − ].join("\n"), | |
| 2184 | − ); | |
| 2185 | − if (!confirmed) { | |
| 2186 | − return; | |
| 2187 | − } | |
| 2188 | − } | |
| 2189 | − const result = await deleteThread(threadRef); | |
| 2190 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2191 | − const error = squashAtomCommandFailure(result); | |
| 2192 | − toastManager.add( | |
| 2193 | − stackedThreadToast({ | |
| 2194 | − type: "error", | |
| 2195 | − title: "Failed to delete thread", | |
| 2196 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2197 | − }), | |
| 2198 | − ); | |
| 2199 | − } | |
| 2200 | − }, | |
| 2201 | − [ | |
| 2202 | − appSettingsConfirmThreadDelete, | |
| 2203 | − copyPathToClipboard, | |
| 2204 | − copyThreadIdToClipboard, | |
| 2205 | − deleteThread, | |
| 2206 | − handleNewThread, | |
| 2207 | − markThreadUnread, | |
| 2208 | − memberProjectByScopedKey, | |
| 2209 | − project.workspaceRoot, | |
| 2210 | − startThreadRename, | |
| 2211 | − ], | |
| 2212 | − ); | |
| 2213 | − | |
| 2214 | − return ( | |
| 2215 | − <> | |
| 2216 | − <div className="group/project-header relative"> | |
| 2217 | − <SidebarMenuButton | |
| 2218 | − ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined} | |
| 2219 | − className={`pr-8 group-hover/project-header:bg-sidebar-row-hover group-hover/project-header:text-sidebar-foreground max-sm:pr-14 ${ | |
| 2220 | − isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "" | |
| 2221 | − }`} | |
| 2222 | − {...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})} | |
| 2223 | − {...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})} | |
| 2224 | − onPointerDownCapture={handleProjectButtonPointerDownCapture} | |
| 2225 | − onClick={handleProjectButtonClick} | |
| 2226 | − onKeyDown={handleProjectButtonKeyDown} | |
| 2227 | − onContextMenu={handleProjectButtonContextMenu} | |
| 2228 | − > | |
| 2229 | − {!projectExpanded && projectStatus ? ( | |
| 2230 | − <Tooltip> | |
| 2231 | − <TooltipTrigger | |
| 2232 | − render={ | |
| 2233 | − <span | |
| 2234 | − aria-label={projectStatus.label} | |
| 2235 | − className={`-ml-0.5 relative inline-flex size-3.5 shrink-0 items-center justify-center ${projectStatus.colorClass}`} | |
| 2236 | − /> | |
| 2237 | − } | |
| 2238 | − > | |
| 2239 | − <span className="absolute inset-0 flex items-center justify-center transition-opacity duration-150 group-hover/project-header:opacity-0"> | |
| 2240 | − <span | |
| 2241 | − className={`size-[9px] rounded-full ${projectStatus.dotClass} ${ | |
| 2242 | − projectStatus.pulse ? "animate-status-pulse" : "" | |
| 2243 | − }`} | |
| 2244 | − /> | |
| 2245 | − </span> | |
| 2246 | − <ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-icon-muted opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" /> | |
| 2247 | − </TooltipTrigger> | |
| 2248 | − <TooltipPopup side="top">{projectStatus.label}</TooltipPopup> | |
| 2249 | − </Tooltip> | |
| 2250 | − ) : ( | |
| 2251 | − <ChevronRightIcon | |
| 2252 | − className={`-ml-0.5 size-3.5 shrink-0 text-muted-foreground/70 transition-transform duration-150 ${ | |
| 2253 | − projectExpanded ? "rotate-90" : "" | |
| 2254 | − }`} | |
| 2255 | − /> | |
| 2256 | − )} | |
| 2257 | − <ProjectFavicon environmentId={project.environmentId} cwd={project.workspaceRoot} /> | |
| 2258 | − <span className="flex min-w-0 flex-1 items-center gap-2"> | |
| 2259 | − <span className="truncate text-sm font-medium text-sidebar-foreground/90"> | |
| 2260 | − {project.displayName} | |
| 2261 | − </span> | |
| 2262 | − {project.groupedProjectCount > 1 ? ( | |
| 2263 | − <span className="shrink-0 text-secondary-label text-[10px]"> | |
| 2264 | − {project.groupedProjectCount} projects | |
| 2265 | − </span> | |
| 2266 | − ) : null} | |
| 2267 | − </span> | |
| 2268 | − </SidebarMenuButton> | |
| 2269 | − {/* Environment badge – visible by default, crossfades with the | |
| 2270 | − "new thread" button on hover using the same pointer-events + | |
| 2271 | − opacity pattern as the thread row archive/timestamp swap. */} | |
| 2272 | − {project.environmentPresence === "remote-only" && ( | |
| 2273 | − <Tooltip> | |
| 2274 | − <TooltipTrigger | |
| 2275 | − render={ | |
| 2276 | − <span | |
| 2277 | − aria-label={ | |
| 2278 | − project.allRemoteMembersAreDesktopLocal | |
| 2279 | − ? "Local sandbox project" | |
| 2280 | − : "Remote project" | |
| 2281 | − } | |
| 2282 | − className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center rounded-md text-icon-muted transition-opacity duration-150 max-sm:right-7 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0 max-sm:group-hover/project-header:opacity-100 max-sm:group-focus-within/project-header:opacity-100" | |
| 2283 | − /> | |
| 2284 | − } | |
| 2285 | − > | |
| 2286 | − {project.allRemoteMembersAreDesktopLocal ? ( | |
| 2287 | − <ContainerIcon className="size-3" /> | |
| 2288 | − ) : ( | |
| 2289 | − <CloudIcon className="size-3" /> | |
| 2290 | − )} | |
| 2291 | − </TooltipTrigger> | |
| 2292 | − <TooltipPopup side="top"> | |
| 2293 | − {project.allRemoteMembersAreDesktopLocal | |
| 2294 | − ? `Local sandbox: ${project.remoteEnvironmentLabels.join(", ")}` | |
| 2295 | − : `Remote environment: ${project.remoteEnvironmentLabels.join(", ")}`} | |
| 2296 | − </TooltipPopup> | |
| 2297 | − </Tooltip> | |
| 2298 | − )} | |
| 2299 | − <Tooltip> | |
| 2300 | − <TooltipTrigger | |
| 2301 | − render={ | |
| 2302 | − <div className="pointer-events-none absolute top-[calc(50%+1px)] right-0.5 -translate-y-1/2 opacity-0 transition-opacity duration-150 max-sm:pointer-events-auto max-sm:opacity-100 group-hover/project-header:pointer-events-auto group-hover/project-header:opacity-100 group-focus-within/project-header:pointer-events-auto group-focus-within/project-header:opacity-100"> | |
| 2303 | − <button | |
| 2304 | − type="button" | |
| 2305 | − aria-label={`Create new thread in ${project.displayName}`} | |
| 2306 | − data-testid="new-thread-button" | |
| 2307 | − className={SIDEBAR_ICON_ACTION_BUTTON_CLASS} | |
| 2308 | − onClick={handleCreateThreadClick} | |
| 2309 | − > | |
| 2310 | − <SquarePenIcon className="size-3.5" /> | |
| 2311 | − </button> | |
| 2312 | − </div> | |
| 2313 | − } | |
| 2314 | − /> | |
| 2315 | − <TooltipPopup side="top"> | |
| 2316 | − {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"} | |
| 2317 | − </TooltipPopup> | |
| 2318 | − </Tooltip> | |
| 2319 | − </div> | |
| 2320 | − | |
| 2321 | − <SidebarProjectThreadList | |
| 2322 | − projectKey={project.projectKey} | |
| 2323 | − projectExpanded={projectExpanded} | |
| 2324 | − hasOverflowingThreads={hasOverflowingThreads} | |
| 2325 | − hiddenThreadStatus={hiddenThreadStatus} | |
| 2326 | − orderedProjectThreadKeys={orderedProjectThreadKeys} | |
| 2327 | − renderedThreads={renderedThreads} | |
| 2328 | − showEmptyThreadState={showEmptyThreadState} | |
| 2329 | − shouldShowThreadPanel={shouldShowThreadPanel} | |
| 2330 | − isThreadListExpanded={isThreadListExpanded} | |
| 2331 | − projectCwd={project.workspaceRoot} | |
| 2332 | − activeRouteThreadKey={activeRouteThreadKey} | |
| 2333 | − threadJumpLabelByKey={threadJumpLabelByKey} | |
| 2334 | − appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive} | |
| 2335 | − renamingThreadKey={renamingThreadKey} | |
| 2336 | − renamingTitle={renamingTitle} | |
| 2337 | − setRenamingTitle={setRenamingTitle} | |
| 2338 | − startThreadRename={startThreadRename} | |
| 2339 | − renamingInputRef={renamingInputRef} | |
| 2340 | − renamingCommittedRef={renamingCommittedRef} | |
| 2341 | − confirmingArchiveThreadKey={confirmingArchiveThreadKey} | |
| 2342 | − setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey} | |
| 2343 | − confirmArchiveButtonRefs={confirmArchiveButtonRefs} | |
| 2344 | − attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} | |
| 2345 | − handleThreadClick={handleThreadClick} | |
| 2346 | − navigateToThread={navigateToThread} | |
| 2347 | − handleMultiSelectContextMenu={handleMultiSelectContextMenu} | |
| 2348 | − handleThreadContextMenu={handleThreadContextMenu} | |
| 2349 | − clearSelection={clearSelection} | |
| 2350 | − commitRename={commitRename} | |
| 2351 | − cancelRename={cancelRename} | |
| 2352 | − attemptArchiveThread={attemptArchiveThread} | |
| 2353 | − openPrLink={openPrLink} | |
| 2354 | − expandThreadListForProject={expandThreadListForProject} | |
| 2355 | − collapseThreadListForProject={collapseThreadListForProject} | |
| 2356 | − /> | |
| 2357 | − | |
| 2358 | − <Dialog | |
| 2359 | − open={projectRenameTarget !== null} | |
| 2360 | − onOpenChange={(open) => { | |
| 2361 | − if (!open) { | |
| 2362 | − closeProjectRenameDialog(); | |
| 2363 | − } | |
| 2364 | − }} | |
| 2365 | − > | |
| 2366 | − <DialogPopup className="max-w-lg"> | |
| 2367 | − <DialogHeader> | |
| 2368 | − <DialogTitle>Rename project</DialogTitle> | |
| 2369 | − <DialogDescription> | |
| 2370 | − {projectRenameTarget | |
| 2371 | − ? `Update the title for ${projectRenameTarget.workspaceRoot}.` | |
| 2372 | − : "Update the project title."} | |
| 2373 | − </DialogDescription> | |
| 2374 | − </DialogHeader> | |
| 2375 | − <DialogPanel className="space-y-4"> | |
| 2376 | − <div className="grid gap-1.5"> | |
| 2377 | − <span className="text-xs font-medium text-foreground">Project title</span> | |
| 2378 | − <Input | |
| 2379 | − aria-label="Project title" | |
| 2380 | − value={projectRenameTitle} | |
| 2381 | − onChange={(event) => setProjectRenameTitle(event.target.value)} | |
| 2382 | − onKeyDown={(event) => { | |
| 2383 | − if (event.key === "Enter") { | |
| 2384 | − event.preventDefault(); | |
| 2385 | − void submitProjectRename(); | |
| 2386 | − } | |
| 2387 | − }} | |
| 2388 | − /> | |
| 2389 | − </div> | |
| 2390 | − {projectRenameTarget?.environmentLabel ? ( | |
| 2391 | − <p className="text-xs text-muted-foreground"> | |
| 2392 | − Environment: {projectRenameTarget.environmentLabel} | |
| 2393 | − </p> | |
| 2394 | − ) : null} | |
| 2395 | − </DialogPanel> | |
| 2396 | − <DialogFooter> | |
| 2397 | − <Button variant="outline" onClick={closeProjectRenameDialog}> | |
| 2398 | − Cancel | |
| 2399 | − </Button> | |
| 2400 | − <Button onClick={() => void submitProjectRename()}>Save</Button> | |
| 2401 | − </DialogFooter> | |
| 2402 | − </DialogPopup> | |
| 2403 | − </Dialog> | |
| 2404 | − | |
| 2405 | − <Dialog | |
| 2406 | − open={projectGroupingTarget !== null} | |
| 2407 | − onOpenChange={(open) => { | |
| 2408 | − if (!open) { | |
| 2409 | − closeProjectGroupingDialog(); | |
| 2410 | − } | |
| 2411 | − }} | |
| 2412 | − > | |
| 2413 | − <DialogPopup className="max-w-lg"> | |
| 2414 | − <DialogHeader> | |
| 2415 | − <DialogTitle>Project grouping</DialogTitle> | |
| 2416 | − <DialogDescription> | |
| 2417 | − {projectGroupingTarget | |
| 2418 | − ? `Choose how ${projectGroupingTarget.workspaceRoot} should be grouped in the sidebar.` | |
| 2419 | − : "Choose how this project should be grouped in the sidebar."} | |
| 2420 | − </DialogDescription> | |
| 2421 | − </DialogHeader> | |
| 2422 | − <DialogPanel className="space-y-4"> | |
| 2423 | − <div className="grid gap-1.5"> | |
| 2424 | − <span className="text-xs font-medium text-foreground">Grouping rule</span> | |
| 2425 | − <Select | |
| 2426 | − value={projectGroupingSelection} | |
| 2427 | − onValueChange={(value) => { | |
| 2428 | − if ( | |
| 2429 | − value === "inherit" || | |
| 2430 | − value === "repository" || | |
| 2431 | − value === "repository_path" || | |
| 2432 | − value === "separate" | |
| 2433 | − ) { | |
| 2434 | − setProjectGroupingSelection(value); | |
| 2435 | − } | |
| 2436 | − }} | |
| 2437 | − > | |
| 2438 | − <SelectTrigger className="w-full" aria-label="Project grouping rule"> | |
| 2439 | − <SelectValue> | |
| 2440 | − {projectGroupingSelection === "inherit" | |
| 2441 | − ? `Use global default (${PROJECT_GROUPING_MODE_LABELS[projectGroupingSettings.sidebarProjectGroupingMode]})` | |
| 2442 | − : PROJECT_GROUPING_MODE_LABELS[projectGroupingSelection]} | |
| 2443 | − </SelectValue> | |
| 2444 | − </SelectTrigger> | |
| 2445 | − <SelectPopup align="end" alignItemWithTrigger={false}> | |
| 2446 | − <SelectItem hideIndicator value="inherit"> | |
| 2447 | − Use global default | |
| 2448 | − </SelectItem> | |
| 2449 | − <SelectItem hideIndicator value="repository"> | |
| 2450 | − {PROJECT_GROUPING_MODE_LABELS.repository} | |
| 2451 | − </SelectItem> | |
| 2452 | − <SelectItem hideIndicator value="repository_path"> | |
| 2453 | − {PROJECT_GROUPING_MODE_LABELS.repository_path} | |
| 2454 | − </SelectItem> | |
| 2455 | − <SelectItem hideIndicator value="separate"> | |
| 2456 | − {PROJECT_GROUPING_MODE_LABELS.separate} | |
| 2457 | − </SelectItem> | |
| 2458 | − </SelectPopup> | |
| 2459 | − </Select> | |
| 2460 | − </div> | |
| 2461 | − <p className="text-xs text-muted-foreground"> | |
| 2462 | − {projectGroupingSelection === "inherit" | |
| 2463 | − ? projectGroupingModeDescription(projectGroupingSettings.sidebarProjectGroupingMode) | |
| 2464 | − : projectGroupingModeDescription(projectGroupingSelection)} | |
| 2465 | − </p> | |
| 2466 | − </DialogPanel> | |
| 2467 | − <DialogFooter> | |
| 2468 | − <Button variant="outline" onClick={closeProjectGroupingDialog}> | |
| 2469 | − Cancel | |
1949 more lines aren’t shown here.
| @@ -1,3711 +0,0 @@ | ||
| 1 | −import { autoAnimate } from "@formkit/auto-animate"; | |
| 2 | −import { useAtomValue } from "@effect/atom-react"; | |
| 3 | −import { | |
| 4 | − DndContext, | |
| 5 | − PointerSensor, | |
| 6 | − closestCenter, | |
| 7 | − useSensor, | |
| 8 | − useSensors, | |
| 9 | − type DragEndEvent, | |
| 10 | −} from "@dnd-kit/core"; | |
| 11 | −import { | |
| 12 | − SortableContext, | |
| 13 | − arrayMove, | |
| 14 | − useSortable, | |
| 15 | − verticalListSortingStrategy, | |
| 16 | −} from "@dnd-kit/sortable"; | |
| 17 | −import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers"; | |
| 18 | −import { CSS } from "@dnd-kit/utilities"; | |
| 19 | −import { | |
| 20 | − canSnooze, | |
| 21 | − effectiveSettled, | |
| 22 | − effectiveSnoozed, | |
| 23 | − threadWokeAt, | |
| 24 | −} from "@t3tools/client-runtime/state/thread-settled"; | |
| 25 | −import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; | |
| 26 | −import { | |
| 27 | − scopeProjectRef, | |
| 28 | − scopeThreadRef, | |
| 29 | − scopedThreadKey, | |
| 30 | −} from "@t3tools/client-runtime/environment"; | |
| 31 | −import type { ScopedThreadRef, SidebarProjectGroupingMode } from "@t3tools/contracts"; | |
| 32 | −import type { TimestampFormat } from "@t3tools/contracts/settings"; | |
| 33 | −import { | |
| 34 | − AlarmClockIcon, | |
| 35 | − AlarmClockOffIcon, | |
| 36 | − CheckIcon, | |
| 37 | − ChevronDownIcon, | |
| 38 | − CircleAlertIcon, | |
| 39 | − CircleCheckIcon, | |
| 40 | − CircleDashedIcon, | |
| 41 | − ClockIcon, | |
| 42 | − CopyIcon, | |
| 43 | − FolderIcon, | |
| 44 | − FolderPlusIcon, | |
| 45 | − GitBranchIcon, | |
| 46 | − EllipsisIcon, | |
| 47 | − MessageSquareIcon, | |
| 48 | − PinIcon, | |
| 49 | − PlusIcon, | |
| 50 | − SearchIcon, | |
| 51 | − ServerIcon, | |
| 52 | − SquarePenIcon, | |
| 53 | − TerminalIcon, | |
| 54 | − Trash2Icon, | |
| 55 | − Undo2Icon, | |
| 56 | − XIcon, | |
| 57 | −} from "lucide-react"; | |
| 58 | −import { | |
| 59 | − memo, | |
| 60 | − useCallback, | |
| 61 | − useEffect, | |
| 62 | − useMemo, | |
| 63 | − useRef, | |
| 64 | − useState, | |
| 65 | − type KeyboardEvent as ReactKeyboardEvent, | |
| 66 | − type MouseEvent as ReactMouseEvent, | |
| 67 | − type ReactNode, | |
| 68 | −} from "react"; | |
| 69 | −import { useParams, useRouter } from "@tanstack/react-router"; | |
| 70 | − | |
| 71 | −import { | |
| 72 | − isAtomCommandInterrupted, | |
| 73 | − settlePromise, | |
| 74 | − squashAtomCommandFailure, | |
| 75 | −} from "@t3tools/client-runtime/state/runtime"; | |
| 76 | −import { isElectron } from "../env"; | |
| 77 | −import { | |
| 78 | − resolveShortcutCommand, | |
| 79 | − shortcutLabelForCommand, | |
| 80 | − shouldShowThreadJumpHintsForModifiers, | |
| 81 | − threadJumpCommandForIndex, | |
| 82 | − threadJumpIndexFromCommand, | |
| 83 | − threadTraversalDirectionFromCommand, | |
| 84 | −} from "../keybindings"; | |
| 85 | −import { useShortcutModifierState } from "../shortcutModifierState"; | |
| 86 | −import { isTerminalFocused } from "../lib/terminalFocus"; | |
| 87 | −import { isModelPickerOpen } from "../modelPickerVisibility"; | |
| 88 | −import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; | |
| 89 | −import { isMacPlatform } from "~/lib/utils"; | |
| 90 | −import { useOpenPrLink } from "../lib/openPullRequestLink"; | |
| 91 | −import { readLocalApi } from "../localApi"; | |
| 92 | −import { | |
| 93 | − deriveProjectGroupingOverrideKey, | |
| 94 | − getProjectOrderKey, | |
| 95 | − selectProjectGroupingSettings, | |
| 96 | −} from "../logicalProject"; | |
| 97 | −import { | |
| 98 | − buildSidebarProjectSnapshots, | |
| 99 | − type SidebarProjectGroupMember, | |
| 100 | − type SidebarProjectSnapshot, | |
| 101 | −} from "../sidebarProjectGrouping"; | |
| 102 | −import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; | |
| 103 | −import { useThreadSelectionStore } from "../threadSelectionStore"; | |
| 104 | −import { useThreadActions } from "../hooks/useThreadActions"; | |
| 105 | −import { useHandleNewThread } from "../hooks/useHandleNewThread"; | |
| 106 | −import { openCommandPalette } from "../commandPaletteBus"; | |
| 107 | −import { startNewThreadFromContext } from "../lib/chatThreadActions"; | |
| 108 | −import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings"; | |
| 109 | −import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; | |
| 110 | −import { useNowMinute } from "../hooks/useNowMinute"; | |
| 111 | −import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; | |
| 112 | −import { useProjects, useThreadShells } from "../state/entities"; | |
| 113 | −import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server"; | |
| 114 | −import { vcsEnvironment } from "../state/vcs"; | |
| 115 | −import { threadEnvironment } from "../state/threads"; | |
| 116 | −import { projectEnvironment } from "../state/projects"; | |
| 117 | −import { useEnvironmentQuery } from "../state/query"; | |
| 118 | −import { useAtomCommand } from "../state/use-atom-command"; | |
| 119 | −import { | |
| 120 | − buildThreadRouteParams, | |
| 121 | − resolveActiveThreadRouteRef, | |
| 122 | − resolveThreadRouteTarget, | |
| 123 | −} from "../threadRoutes"; | |
| 124 | −import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat"; | |
| 125 | −import type { SidebarThreadSummary } from "../types"; | |
| 126 | −import { cn } from "~/lib/utils"; | |
| 127 | −import { buildThreadActionMenuItems } from "./threadActionMenu.logic"; | |
| 128 | −import { | |
| 129 | − buildBulkTitleRegenerationContextMenuItem, | |
| 130 | − formatWorkingDurationLabel, | |
| 131 | − firstValidTimestampMs, | |
| 132 | − hasUnseenCompletion, | |
| 133 | − isTrailingDoubleClick, | |
| 134 | − orderItemsByPreferredIds, | |
| 135 | − planPinnedReorder, | |
| 136 | − resolveAdjacentThreadId, | |
| 137 | − resolveSettledTimestamp, | |
| 138 | − resolveSidebarV2Status, | |
| 139 | − searchSidebarThreadsByTitle, | |
| 140 | − resolveWorkingStartedAt, | |
| 141 | − shouldNavigateAfterProjectRemoval, | |
| 142 | − sortLogicalProjectsForSidebar, | |
| 143 | − sortPinnedThreadsForSidebarV2, | |
| 144 | − sortSettledThreadsForSidebarV2, | |
| 145 | − sortThreadsForSidebarV2, | |
| 146 | −} from "./Sidebar.logic"; | |
| 147 | −import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic"; | |
| 148 | −import { | |
| 149 | − prStatusIndicator, | |
| 150 | − resolveThreadPr, | |
| 151 | − settledPrHoverColorClass, | |
| 152 | − terminalStatusFromRunningIds, | |
| 153 | − type TerminalStatusIndicator, | |
| 154 | −} from "./ThreadStatusIndicators"; | |
| 155 | −import { | |
| 156 | − resolveSnoozePresets, | |
| 157 | − snoozeWakeDescription, | |
| 158 | − snoozeWakeLabel, | |
| 159 | − type SnoozePreset, | |
| 160 | −} from "./Sidebar.snooze"; | |
| 161 | −import { ProjectFavicon } from "./ProjectFavicon"; | |
| 162 | −import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon"; | |
| 163 | −import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils"; | |
| 164 | −import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances"; | |
| 165 | −import { primaryServerProvidersAtom } from "../state/server"; | |
| 166 | −import { useThreadRunningTerminalIds } from "../state/terminalSessions"; | |
| 167 | −import { stackedThreadToast, toastManager } from "./ui/toast"; | |
| 168 | −import { Button } from "./ui/button"; | |
| 169 | −import { | |
| 170 | − Dialog, | |
| 171 | − DialogDescription, | |
| 172 | − DialogFooter, | |
| 173 | − DialogHeader, | |
| 174 | − DialogPanel, | |
| 175 | − DialogPopup, | |
| 176 | − DialogTitle, | |
| 177 | −} from "./ui/dialog"; | |
| 178 | −import { Input } from "./ui/input"; | |
| 179 | −import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; | |
| 180 | −import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; | |
| 181 | −import { SidebarContent, SidebarGroup, SidebarMenuButton, useSidebar } from "./ui/sidebar"; | |
| 182 | −import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; | |
| 183 | −import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover"; | |
| 184 | −import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; | |
| 185 | −import { useComposerDraftStore } from "../composerDraftStore"; | |
| 186 | − | |
| 187 | −// Settled-tail paging: recent history is the common lookup; the deep tail | |
| 188 | −// stays behind an explicit Show more. | |
| 189 | −const SETTLED_TAIL_INITIAL_COUNT = 10; | |
| 190 | −const SETTLED_TAIL_PAGE_COUNT = 25; | |
| 191 | −const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = { | |
| 192 | − repository: "Group by repository", | |
| 193 | − repository_path: "Group by repository path", | |
| 194 | − separate: "Keep separate", | |
| 195 | −}; | |
| 196 | − | |
| 197 | −function compactSidebarTimeLabel(label: string): string { | |
| 198 | − if (label === "just now") return "now"; | |
| 199 | − return label.endsWith(" ago") ? label.slice(0, -4) : label; | |
| 200 | −} | |
| 201 | − | |
| 202 | −function threadTimeLabel(thread: SidebarThreadSummary): string { | |
| 203 | − const timestamp = thread.latestUserMessageAt ?? thread.updatedAt; | |
| 204 | − return compactSidebarTimeLabel(formatRelativeTimeLabel(timestamp)); | |
| 205 | −} | |
| 206 | − | |
| 207 | −// Settled rows read "how long ago did this wrap up", matching their sort | |
| 208 | −// key: both go through resolveSettledTimestamp so label and order can't | |
| 209 | −// disagree. | |
| 210 | −function settledTimeLabel(thread: SidebarThreadSummary): string { | |
| 211 | − const timestamp = resolveSettledTimestamp(thread); | |
| 212 | − return timestamp === null ? "" : compactSidebarTimeLabel(formatRelativeTimeLabel(timestamp)); | |
| 213 | −} | |
| 214 | − | |
| 215 | −// Floats at the row's right edge, vertically centered, while the jump | |
| 216 | −// modifier is held. An overlay pill instead of an inline slot: the hint | |
| 217 | −// must neither displace the status/time label (holding ⌘ used to blank | |
| 218 | −// out "Working") nor shift any layout when it appears. pointer-events-none | |
| 219 | −// so it never swallows clicks meant for the settle/un-settle buttons it | |
| 220 | −// can overlap. | |
| 221 | −function JumpHintBadge(props: { label: string }) { | |
| 222 | − return ( | |
| 223 | − <span | |
| 224 | − aria-hidden | |
| 225 | − className="pointer-events-none absolute right-1.5 top-1/2 z-10 inline-flex h-5 -translate-y-1/2 items-center rounded-full border border-border/80 bg-background/95 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm" | |
| 226 | − > | |
| 227 | − {props.label} | |
| 228 | − </span> | |
| 229 | − ); | |
| 230 | −} | |
| 231 | − | |
| 232 | −// Self-ticking so only this span re-renders each second, not the whole row. | |
| 233 | −function WorkingDuration(props: { startedAt: string | null }) { | |
| 234 | − const startedMs = props.startedAt !== null ? Date.parse(props.startedAt) : Number.NaN; | |
| 235 | − const [, setTick] = useState(0); | |
| 236 | − useEffect(() => { | |
| 237 | − if (Number.isNaN(startedMs)) return; | |
| 238 | − const id = window.setInterval(() => setTick((tick) => tick + 1), 1_000); | |
| 239 | − return () => window.clearInterval(id); | |
| 240 | − }, [startedMs]); | |
| 241 | − if (Number.isNaN(startedMs)) return null; | |
| 242 | − return ( | |
| 243 | − <span className="font-mono tabular-nums"> | |
| 244 | − {formatWorkingDurationLabel(Date.now() - startedMs)} | |
| 245 | − </span> | |
| 246 | − ); | |
| 247 | −} | |
| 248 | − | |
| 249 | −function terminalProcessLabel(count: number): string { | |
| 250 | − return `${count} terminal ${count === 1 ? "process" : "processes"} running`; | |
| 251 | −} | |
| 252 | − | |
| 253 | −function SidebarV2ThreadTooltip({ | |
| 254 | − thread, | |
| 255 | − projectTitle, | |
| 256 | − projectCwd, | |
| 257 | − environmentLabel, | |
| 258 | − driverKind, | |
| 259 | − modelInstanceId, | |
| 260 | − modelLabel, | |
| 261 | − branchMismatch, | |
| 262 | − terminalStatus, | |
| 263 | − terminalProcessCount, | |
| 264 | −}: { | |
| 265 | − thread: SidebarThreadSummary; | |
| 266 | − projectTitle: string | null; | |
| 267 | − projectCwd: string | null; | |
| 268 | − environmentLabel: string | null; | |
| 269 | − driverKind: ProviderInstanceEntry["driverKind"] | null; | |
| 270 | − modelInstanceId: string; | |
| 271 | − modelLabel: string; | |
| 272 | − branchMismatch: { | |
| 273 | − threadBranch: string; | |
| 274 | − currentBranch: string; | |
| 275 | − } | null; | |
| 276 | − terminalStatus: TerminalStatusIndicator | null; | |
| 277 | − terminalProcessCount: number; | |
| 278 | −}) { | |
| 279 | − return ( | |
| 280 | − <TooltipPopup | |
| 281 | − side="right" | |
| 282 | − align="start" | |
| 283 | − sideOffset={4} | |
| 284 | − variant="glass" | |
| 285 | − className="max-w-80 text-left whitespace-normal [&_[data-slot=tooltip-viewport]]:p-0" | |
| 286 | − > | |
| 287 | − <div className="flex min-w-0 max-w-80 flex-col gap-2 p-[var(--floating-content-inset)]"> | |
| 288 | − <div className="min-w-0 truncate text-xs leading-none font-medium text-foreground"> | |
| 289 | − {thread.title} | |
| 290 | − </div> | |
| 291 | − <div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground"> | |
| 292 | − {projectTitle ? ( | |
| 293 | − <div className="flex min-w-0 items-center gap-2"> | |
| 294 | − <ProjectFavicon | |
| 295 | − environmentId={thread.environmentId} | |
| 296 | − cwd={projectCwd ?? ""} | |
| 297 | − className="size-3 shrink-0 stroke-muted-foreground" | |
| 298 | − /> | |
| 299 | − <div className="min-w-0 truncate text-foreground/75">{projectTitle}</div> | |
| 300 | − </div> | |
| 301 | − ) : null} | |
| 302 | − {environmentLabel ? ( | |
| 303 | − <div className="flex min-w-0 items-center gap-2"> | |
| 304 | − <ServerIcon className="size-3 shrink-0 stroke-muted-foreground" /> | |
| 305 | − <div className="min-w-0 truncate text-foreground/75">{environmentLabel}</div> | |
| 306 | − </div> | |
| 307 | − ) : null} | |
| 308 | − {thread.branch ? ( | |
| 309 | − <div className="flex min-w-0 items-center gap-2"> | |
| 310 | − <GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" /> | |
| 311 | − <div className="min-w-0 truncate text-foreground/75">{thread.branch}</div> | |
| 312 | − </div> | |
| 313 | − ) : null} | |
| 314 | − {branchMismatch ? ( | |
| 315 | − <div className="flex min-w-0 items-start gap-2 text-warning"> | |
| 316 | − <CircleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" /> | |
| 317 | − <div className="min-w-0 flex-1 wrap-break-word leading-5"> | |
| 318 | − You're currently checked out on another branch. | |
| 319 | − </div> | |
| 320 | − </div> | |
| 321 | − ) : null} | |
| 322 | − {driverKind ? ( | |
| 323 | − <div className="flex min-w-0 items-center gap-2"> | |
| 324 | − <ProviderInstanceIcon | |
| 325 | − driverKind={driverKind} | |
| 326 | − displayName={thread.session?.providerName ?? modelInstanceId} | |
| 327 | − iconClassName="size-3 shrink-0 grayscale opacity-60" | |
| 328 | − /> | |
| 329 | − <div className="min-w-0 truncate text-foreground/75">{modelLabel}</div> | |
| 330 | − </div> | |
| 331 | − ) : null} | |
| 332 | − {terminalStatus ? ( | |
| 333 | − <div className="flex min-w-0 items-center gap-2"> | |
| 334 | − <TerminalIcon | |
| 335 | − aria-hidden | |
| 336 | − className={cn("size-3 shrink-0", terminalStatus.colorClass)} | |
| 337 | − /> | |
| 338 | − <div className="min-w-0 truncate text-foreground/75"> | |
| 339 | − {terminalProcessLabel(terminalProcessCount)} | |
| 340 | − </div> | |
| 341 | − </div> | |
| 342 | − ) : null} | |
| 343 | − {thread.session?.lastError ? ( | |
| 344 | − <div className="flex min-w-0 items-center gap-2 text-red-600 dark:text-red-400"> | |
| 345 | − <CircleAlertIcon className="size-3 shrink-0 stroke-current" /> | |
| 346 | − <div className="min-w-0 truncate">Error occurred</div> | |
| 347 | − </div> | |
| 348 | − ) : null} | |
| 349 | − </div> | |
| 350 | − </div> | |
| 351 | − </TooltipPopup> | |
| 352 | − ); | |
| 353 | −} | |
| 354 | − | |
| 355 | −/** | |
| 356 | − * Hover entry point for snooze: a clock button opening the preset menu. | |
| 357 | − * Controlled by the row (which also uses the open state to pin its hover | |
| 358 | − * actions while the menu is up). | |
| 359 | − */ | |
| 360 | −function SnoozePopoverButton(props: { | |
| 361 | − open: boolean; | |
| 362 | − onOpenChange: (open: boolean) => void; | |
| 363 | − onSnooze: (preset: SnoozePreset) => void; | |
| 364 | − timestampFormat: TimestampFormat; | |
| 365 | −}) { | |
| 366 | − const { open, onOpenChange, onSnooze, timestampFormat } = props; | |
| 367 | − // Presets resolve at open time so "In 1 hour" is relative to the click, | |
| 368 | − // not to when the row mounted. | |
| 369 | − const presets = useMemo( | |
| 370 | − () => (open ? resolveSnoozePresets(new Date(), timestampFormat) : []), | |
| 371 | − [open, timestampFormat], | |
| 372 | − ); | |
| 373 | − return ( | |
| 374 | − <Popover open={open} onOpenChange={onOpenChange}> | |
| 375 | − <PopoverTrigger | |
| 376 | − render={ | |
| 377 | − <button | |
| 378 | − type="button" | |
| 379 | − aria-label="Snooze thread" | |
| 380 | − onClick={(event) => event.stopPropagation()} | |
| 381 | − onDoubleClick={(event) => event.stopPropagation()} | |
| 382 | − className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" | |
| 383 | − /> | |
| 384 | − } | |
| 385 | − > | |
| 386 | − <ClockIcon className="size-3" /> | |
| 387 | − </PopoverTrigger> | |
| 388 | − <PopoverPopup side="bottom" align="end" className="w-56" viewportClassName="p-1"> | |
| 389 | − {presets.map((preset) => ( | |
| 390 | − <button | |
| 391 | − key={preset.id} | |
| 392 | − type="button" | |
| 393 | − onClick={(event) => { | |
| 394 | − event.stopPropagation(); | |
| 395 | − onOpenChange(false); | |
| 396 | − onSnooze(preset); | |
| 397 | − }} | |
| 398 | − className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-foreground/90 hover:bg-accent hover:text-foreground" | |
| 399 | − > | |
| 400 | − <span className="flex-1">{preset.label}</span> | |
| 401 | − <span className="font-mono text-[10px] text-muted-foreground/60 tabular-nums"> | |
| 402 | − {preset.whenLabel} | |
| 403 | − </span> | |
| 404 | − </button> | |
| 405 | − ))} | |
| 406 | − </PopoverPopup> | |
| 407 | − </Popover> | |
| 408 | − ); | |
| 409 | −} | |
| 410 | − | |
| 411 | −// Subset of useSortable applied to a pinned card's root <li>. Listeners go | |
| 412 | −// on the whole card (no dedicated handle): the pointer sensor's distance | |
| 413 | −// constraint keeps plain clicks working, and we skip dnd-kit's aria | |
| 414 | −// attributes since there is no keyboard sensor and the card body already | |
| 415 | −// carries its own button semantics. | |
| 416 | −type SortablePinnedRowBag = Pick< | |
| 417 | − ReturnType<typeof useSortable>, | |
| 418 | − "listeners" | "setNodeRef" | "transform" | "transition" | "isDragging" | |
| 419 | −>; | |
| 420 | − | |
| 421 | −function SortablePinnedThreadRow(props: { | |
| 422 | − id: string; | |
| 423 | − children: (bag: SortablePinnedRowBag) => ReactNode; | |
| 424 | −}) { | |
| 425 | − const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ | |
| 426 | − id: props.id, | |
| 427 | − }); | |
| 428 | − return props.children({ listeners, setNodeRef, transform, transition, isDragging }); | |
| 429 | −} | |
| 430 | − | |
| 431 | −const SidebarV2Row = memo(function SidebarV2Row(props: { | |
| 432 | − thread: SidebarThreadSummary; | |
| 433 | − variant: "card" | "slim"; | |
| 434 | − // Slim rows are either settled (action: un-settle) or merely quiet | |
| 435 | − // (seen Ready threads — action: settle). | |
| 436 | − variantAction: "settle" | "unsettle" | "unsnooze"; | |
| 437 | − // False on environments whose server predates thread.settle/unsettle: | |
| 438 | − // the lifecycle affordances hide entirely rather than fail on click. | |
| 439 | − settlementSupported: boolean; | |
| 440 | − // Same contract for thread.snooze/unsnooze. | |
| 441 | − snoozeSupported: boolean; | |
| 442 | − // Renders the pin glyph. Pinned cards keep the full settle/snooze quick | |
| 443 | − // actions: settling clears the pin server-side, and snoozing hides the | |
| 444 | − // card until wake with the pin intact underneath. The glyph is also the | |
| 445 | − // in-row pin state cue (the pinned block has no header), so it always | |
| 446 | − // shows while pinned; it only becomes a clickable unpin quick-action once | |
| 447 | − // the pinning capability is confirmed, and stays a passive marker while | |
| 448 | − // the descriptor is not loaded. Pinning itself lives in the context menu. | |
| 449 | − pinningSupported: boolean; | |
| 450 | − isPinned: boolean; | |
| 451 | − // Present only on pinned cards whose server supports reordering: dnd-kit | |
| 452 | − // sortable bag applied to the card root so the whole card drags (the | |
| 453 | − // pointer sensor's distance constraint keeps plain clicks working). | |
| 454 | − sortable?: SortablePinnedRowBag | undefined; | |
| 455 | − // Compact wake countdown ("2h") for rows in the snoozed shelf. | |
| 456 | − snoozeWakeLabelText: string | null; | |
| 457 | − // When a snooze ended (timer or early wake); drives the Woke pill until | |
| 458 | − // the user visits the thread. | |
| 459 | − wokeAt: string | null; | |
| 460 | − isActive: boolean; | |
| 461 | − jumpLabel: string | null; | |
| 462 | − currentEnvironmentId: string | null; | |
| 463 | − environmentLabel: string | null; | |
| 464 | − projectCwd: string | null; | |
| 465 | − projectTitle: string | null; | |
| 466 | − providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>; | |
| 467 | − timestampFormat: TimestampFormat; | |
| 468 | − onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; | |
| 469 | − onThreadActivate: (threadRef: ScopedThreadRef) => void; | |
| 470 | − onStartRename: (threadRef: ScopedThreadRef, title: string) => void; | |
| 471 | − onRenameTitleChange: (title: string) => void; | |
| 472 | − onCommitRename: (threadRef: ScopedThreadRef, title: string, originalTitle: string) => void; | |
| 473 | − onCancelRename: () => void; | |
| 474 | − isRenaming: boolean; | |
| 475 | − renamingTitle: string; | |
| 476 | − onContextMenu: (threadRef: ScopedThreadRef, position: { x: number; y: number }) => void; | |
| 477 | − onSettle: (threadRef: ScopedThreadRef) => void; | |
| 478 | − onUnsettle: (threadRef: ScopedThreadRef) => void; | |
| 479 | − onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void; | |
| 480 | − onUnsnooze: (threadRef: ScopedThreadRef) => void; | |
| 481 | − onUnpin: (threadRef: ScopedThreadRef) => void; | |
| 482 | − onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void; | |
| 483 | − onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void; | |
| 484 | −}) { | |
| 485 | − const { | |
| 486 | − isRenaming, | |
| 487 | − onChangeRequestState, | |
| 488 | − onCancelRename, | |
| 489 | − onCommitRename, | |
| 490 | − onContextMenu, | |
| 491 | − onAcknowledgeWoke, | |
| 492 | − onRenameTitleChange, | |
| 493 | − onSettle, | |
| 494 | − onSnooze, | |
| 495 | − onStartRename, | |
| 496 | − onThreadActivate, | |
| 497 | − onThreadClick, | |
| 498 | − onUnsettle, | |
| 499 | − onUnsnooze, | |
| 500 | − onUnpin, | |
| 501 | − renamingTitle, | |
| 502 | − thread, | |
| 503 | − variant, | |
| 504 | − variantAction, | |
| 505 | − } = props; | |
| 506 | − const threadRef = useMemo( | |
| 507 | − () => scopeThreadRef(thread.environmentId, thread.id), | |
| 508 | − [thread.environmentId, thread.id], | |
| 509 | − ); | |
| 510 | − const threadKey = scopedThreadKey(threadRef); | |
| 511 | − const isRegeneratingTitle = thread.titleRegeneration != null; | |
| 512 | − const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); | |
| 513 | − const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); | |
| 514 | − const openPrLink = useOpenPrLink(); | |
| 515 | − const runningTerminalIds = useThreadRunningTerminalIds({ | |
| 516 | − environmentId: thread.environmentId, | |
| 517 | − threadId: thread.id, | |
| 518 | − }); | |
| 519 | − const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); | |
| 520 | − const terminalProcessCount = runningTerminalIds.length; | |
| 521 | − | |
| 522 | − const gitCwd = thread.worktreePath ?? props.projectCwd; | |
| 523 | − const gitStatus = useEnvironmentQuery( | |
| 524 | − (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null | |
| 525 | − ? vcsEnvironment.status({ | |
| 526 | − environmentId: thread.environmentId, | |
| 527 | − input: { cwd: gitCwd }, | |
| 528 | − }) | |
| 529 | − : null, | |
| 530 | − ); | |
| 531 | − const pr = resolveThreadPr({ | |
| 532 | − threadBranch: thread.branch, | |
| 533 | − gitStatus: gitStatus.data, | |
| 534 | − }); | |
| 535 | − const prState = pr?.state ?? null; | |
| 536 | − | |
| 537 | − // Same semantics as v1 (never-visited counts as read): flipping the beta | |
| 538 | − // flag must not light up every historical thread as unread. | |
| 539 | − const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); | |
| 540 | − const status = resolveSidebarV2Status(thread); | |
| 541 | − // A woken thread reappears at its original position (the sort is | |
| 542 | − // deliberately static), so the pill has to carry the weight. Snoozing is | |
| 543 | − // an explicit act, so the pill clears only when the user re-engages: | |
| 544 | − // reading a completion-triggered wake, clicking the pill, sending a | |
| 545 | − // message, settling, archiving — or finishing the work outright (merged | |
| 546 | − // or closed PR). Timer wakes survive a mere visit. An unparseable visit | |
| 547 | − // timestamp counts as never-visited — corrupt local data must not eat | |
| 548 | − // the wake signal. | |
| 549 | − const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt); | |
| 550 | − const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt); | |
| 551 | − const isWoke = | |
| 552 | − wokeAtDate !== null && | |
| 553 | − (lastVisitedDate === null || lastVisitedDate < wokeAtDate) && | |
| 554 | − prState !== "merged" && | |
| 555 | − prState !== "closed"; | |
| 556 | − // In-flight rows (working, or waiting on approval/input) fade as a whole: | |
| 557 | − // there is nothing for the user to do yet, so prominence is reserved for | |
| 558 | − // rows that need a human — done (unread), read-but-unsettled, failed, and | |
| 559 | − // freshly woken. The status label keeps its hue, so waiting rows stay | |
| 560 | − // findable. In-flight rows recede the same as read-ready ones (inbox-zero: | |
| 561 | − // working threads aren't your problem yet) — only the colored status label | |
| 562 | − // stands out. | |
| 563 | − const isInFlight = | |
| 564 | − status === "working" || status === "monitoring" || status === "approval" || status === "input"; | |
| 565 | − const shouldRecede = | |
| 566 | − (status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected; | |
| 567 | − // Status hues follow the system-wide convention set by sidebar v1 and the | |
| 568 | − // mobile Live Activity/widgets (amber approval, indigo input, sky working) | |
| 569 | − // so a thread reads the same color everywhere it surfaces. | |
| 570 | − const topStatus = | |
| 571 | − status === "working" | |
| 572 | − ? { | |
| 573 | − label: "Working", | |
| 574 | − icon: "working" as const, | |
| 575 | − // No shimmer: a label that animates forever is noise in a sidebar | |
| 576 | − // full of them (and repaints every vsync on high-refresh displays). | |
| 577 | − // Working is a background state, so it rests at the dim end of what | |
| 578 | − // the old pulse cycled through; only the thread you have open gets | |
| 579 | − // the label at full strength. | |
| 580 | − className: cn("text-sky-600 dark:text-sky-400", !props.isActive && "opacity-75"), | |
| 581 | − } | |
| 582 | − : status === "monitoring" | |
| 583 | − ? { | |
| 584 | − // Monitoring is calm background presence, not active progress | |
| 585 | − // (monitoring-pill D6), so it keeps the label at full strength. | |
| 586 | − label: "Monitoring", | |
| 587 | − icon: null, | |
| 588 | − className: "text-sky-600 dark:text-sky-400", | |
| 589 | − } | |
| 590 | − : status === "approval" | |
| 591 | − ? { | |
| 592 | − label: "Approval", | |
| 593 | − icon: null, | |
| 594 | − className: "text-amber-700 dark:text-amber-300", | |
| 595 | − } | |
| 596 | − : status === "input" | |
| 597 | − ? { | |
| 598 | − label: "Input", | |
| 599 | − icon: null, | |
| 600 | − className: "text-indigo-600 dark:text-indigo-300", | |
| 601 | − } | |
| 602 | − : status === "failed" | |
| 603 | − ? { | |
| 604 | − label: "Failed", | |
| 605 | − icon: null, | |
| 606 | − className: "text-red-700 dark:text-red-300", | |
| 607 | − } | |
| 608 | − : isWoke | |
| 609 | − ? { | |
| 610 | − label: "Woke", | |
| 611 | − icon: "woke" as const, | |
| 612 | − className: "text-amber-700 dark:text-amber-300", | |
| 613 | − } | |
| 614 | − : isUnread | |
| 615 | − ? { | |
| 616 | − label: "Done", | |
| 617 | − icon: "done" as const, | |
| 618 | − className: "text-emerald-700 dark:text-emerald-300", | |
| 619 | − } | |
| 620 | − : null; | |
| 621 | − const isWokeStatus = topStatus?.icon === "woke"; | |
| 622 | − | |
| 623 | − const branchMismatch = resolveLocalCheckoutBranchMismatch({ | |
| 624 | − effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", | |
| 625 | − activeWorktreePath: thread.worktreePath, | |
| 626 | − activeThreadBranch: thread.branch, | |
| 627 | − currentGitBranch: gitStatus.data?.refName ?? null, | |
| 628 | − }); | |
| 629 | − const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider); | |
| 630 | − const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined; | |
| 631 | − // Report the PR state up: the parent partitions rows with effectiveSettled, | |
| 632 | − // and a merged/closed PR auto-settles a thread — data only rows have. | |
| 633 | − useEffect(() => { | |
| 634 | − onChangeRequestState(threadKey, prState); | |
| 635 | − }, [onChangeRequestState, prState, threadKey]); | |
| 636 | − | |
| 637 | − const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; | |
| 638 | − const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; | |
| 639 | − const driverKind = providerEntry?.driverKind ?? null; | |
| 640 | − const selectedModel = providerEntry?.models.find( | |
| 641 | − (model) => model.slug === thread.modelSelection.model, | |
| 642 | − ); | |
| 643 | − const modelLabel = selectedModel | |
| 644 | − ? getTriggerDisplayModelLabel(selectedModel) | |
| 645 | − : thread.modelSelection.model; | |
| 646 | − | |
| 647 | − const isRemote = | |
| 648 | − props.currentEnvironmentId !== null && thread.environmentId !== props.currentEnvironmentId; | |
| 649 | − | |
| 650 | − const detailsTooltip = ( | |
| 651 | − <SidebarV2ThreadTooltip | |
| 652 | − thread={thread} | |
| 653 | − projectTitle={props.projectTitle} | |
| 654 | − projectCwd={props.projectCwd} | |
| 655 | − environmentLabel={props.environmentLabel} | |
| 656 | − driverKind={driverKind} | |
| 657 | − modelInstanceId={modelInstanceId} | |
| 658 | − modelLabel={modelLabel} | |
| 659 | − branchMismatch={branchMismatch} | |
| 660 | − terminalStatus={terminalStatus} | |
| 661 | − terminalProcessCount={terminalProcessCount} | |
| 662 | − /> | |
| 663 | − ); | |
| 664 | − | |
| 665 | − const handleClick = useCallback( | |
| 666 | − (event: ReactMouseEvent) => { | |
| 667 | − onThreadClick(event, threadRef); | |
| 668 | − }, | |
| 669 | − [onThreadClick, threadRef], | |
| 670 | − ); | |
| 671 | − const handleAcknowledgeWokeClick = useCallback( | |
| 672 | − (event: ReactMouseEvent) => { | |
| 673 | − event.preventDefault(); | |
| 674 | − event.stopPropagation(); | |
| 675 | − if (props.wokeAt === null) return; | |
| 676 | − onAcknowledgeWoke(threadRef, props.wokeAt); | |
| 677 | − }, | |
| 678 | − [onAcknowledgeWoke, props.wokeAt, threadRef], | |
| 679 | − ); | |
| 680 | − const handleContextMenu = useCallback( | |
| 681 | − (event: ReactMouseEvent) => { | |
| 682 | − event.preventDefault(); | |
| 683 | − onContextMenu(threadRef, { x: event.clientX, y: event.clientY }); | |
| 684 | − }, | |
| 685 | − [onContextMenu, threadRef], | |
| 686 | − ); | |
| 687 | − const handleKeyDown = useCallback( | |
| 688 | − (event: ReactKeyboardEvent) => { | |
| 689 | − if (event.target !== event.currentTarget) return; | |
| 690 | − if (event.key !== "Enter" && event.key !== " ") return; | |
| 691 | − event.preventDefault(); | |
| 692 | − onThreadActivate(threadRef); | |
| 693 | − }, | |
| 694 | − [onThreadActivate, threadRef], | |
| 695 | − ); | |
| 696 | − const handleDoubleClick = useCallback( | |
| 697 | − (event: ReactMouseEvent) => { | |
| 698 | − if (isRenaming || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { | |
| 699 | − return; | |
| 700 | − } | |
| 701 | − if ((event.target as HTMLElement).closest("button, a, input")) return; | |
| 702 | − event.preventDefault(); | |
| 703 | − onStartRename(threadRef, thread.title); | |
| 704 | − }, | |
| 705 | − [isRenaming, onStartRename, thread.title, threadRef], | |
| 706 | − ); | |
| 707 | − const renameCommittedRef = useRef(false); | |
| 708 | − useEffect(() => { | |
| 709 | − if (isRenaming) renameCommittedRef.current = false; | |
| 710 | − }, [isRenaming]); | |
| 711 | − const handleRenameKeyDown = useCallback( | |
| 712 | − (event: ReactKeyboardEvent<HTMLInputElement>) => { | |
| 713 | − event.stopPropagation(); | |
| 714 | − if (event.key === "Enter") { | |
| 715 | − event.preventDefault(); | |
| 716 | − renameCommittedRef.current = true; | |
| 717 | − onCommitRename(threadRef, renamingTitle, thread.title); | |
| 718 | − } else if (event.key === "Escape") { | |
| 719 | − event.preventDefault(); | |
| 720 | − renameCommittedRef.current = true; | |
| 721 | − onCancelRename(); | |
| 722 | − } | |
| 723 | − }, | |
| 724 | − [onCancelRename, onCommitRename, renamingTitle, thread.title, threadRef], | |
| 725 | − ); | |
| 726 | − const handleRenameBlur = useCallback(() => { | |
| 727 | − if (!renameCommittedRef.current) { | |
| 728 | − onCommitRename(threadRef, renamingTitle, thread.title); | |
| 729 | − } | |
| 730 | − }, [onCommitRename, renamingTitle, thread.title, threadRef]); | |
| 731 | − const handleSettleClick = useCallback( | |
| 732 | − (event: ReactMouseEvent) => { | |
| 733 | − event.preventDefault(); | |
| 734 | − event.stopPropagation(); | |
| 735 | − onSettle(threadRef); | |
| 736 | − }, | |
| 737 | − [onSettle, threadRef], | |
| 738 | − ); | |
| 739 | − const handleUnsettleClick = useCallback( | |
| 740 | − (event: ReactMouseEvent) => { | |
| 741 | − event.preventDefault(); | |
| 742 | − event.stopPropagation(); | |
| 743 | − onUnsettle(threadRef); | |
| 744 | − }, | |
| 745 | − [onUnsettle, threadRef], | |
| 746 | − ); | |
| 747 | − const handleUnsnoozeClick = useCallback( | |
| 748 | − (event: ReactMouseEvent) => { | |
| 749 | − event.preventDefault(); | |
| 750 | − event.stopPropagation(); | |
| 751 | − onUnsnooze(threadRef); | |
| 752 | − }, | |
| 753 | − [onUnsnooze, threadRef], | |
| 754 | − ); | |
| 755 | − const handleUnpinClick = useCallback( | |
| 756 | − (event: ReactMouseEvent) => { | |
| 757 | − event.preventDefault(); | |
| 758 | − event.stopPropagation(); | |
| 759 | − onUnpin(threadRef); | |
| 760 | − }, | |
| 761 | − [onUnpin, threadRef], | |
| 762 | − ); | |
| 763 | − const handleSnoozePreset = useCallback( | |
| 764 | − (preset: SnoozePreset) => { | |
| 765 | − onSnooze(threadRef, preset); | |
| 766 | − }, | |
| 767 | − [onSnooze, threadRef], | |
| 768 | − ); | |
| 769 | − // While the snooze popover is open the pointer leaves the row, which | |
| 770 | − // would fade the hover actions out from under the open menu; pin them. | |
| 771 | − const [snoozeMenuOpenRaw, setSnoozeMenuOpen] = useState(false); | |
| 772 | − // Snooze is offered only where it can succeed: capability-gated and never | |
| 773 | − // on blocked-on-you work or queued turns (the server rejects both). | |
| 774 | − const showSnoozeButton = | |
| 775 | − props.snoozeSupported && canSnooze(thread, { now: new Date().toISOString() }); | |
| 776 | − // If the thread becomes blocked while the popover is open, the button | |
| 777 | − // unmounts without firing onOpenChange(false). Deriving the flag keeps a | |
| 778 | − // stale true from permanently hiding the status label / pinning the | |
| 779 | − // hover actions, and the effect clears the raw state so the popover | |
| 780 | − // doesn't resurrect if the button later remounts. | |
| 781 | − const snoozeMenuOpen = snoozeMenuOpenRaw && showSnoozeButton; | |
| 782 | − useEffect(() => { | |
| 783 | − if (!showSnoozeButton) setSnoozeMenuOpen(false); | |
| 784 | − }, [showSnoozeButton]); | |
| 785 | − const handlePrClick = useCallback( | |
| 786 | − (event: ReactMouseEvent<HTMLElement>) => { | |
| 787 | − if (pr?.url) openPrLink(event, pr.url); | |
| 788 | − }, | |
| 789 | − [openPrLink, pr], | |
| 790 | − ); | |
| 791 | − | |
| 792 | − // All Sidebar V2 rows share one surface model. Live threads used to look | |
| 793 | − // like elevated cards while settled threads were plain rows, leaving neither | |
| 794 | − // a useful hierarchy nor a reliable hover cue. Status now lives in the row | |
| 795 | − // content; surface is reserved for interaction (hover, multi-select, route). | |
| 796 | − const rowSurfaceClassName = cn( | |
| 797 | − "group/v2-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none", | |
| 798 | − props.isActive | |
| 799 | − ? "bg-sidebar-row-active text-sidebar-foreground" | |
| 800 | − : isSelected | |
| 801 | − ? "bg-sidebar-row-selected text-sidebar-foreground" | |
| 802 | − : shouldRecede | |
| 803 | − ? "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 804 | − : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover", | |
| 805 | − isInFlight && | |
| 806 | − !props.isActive && | |
| 807 | − !isSelected && | |
| 808 | − "opacity-70 transition-opacity hover:opacity-100", | |
| 809 | − ); | |
| 810 | − | |
| 811 | − const title = isRenaming ? ( | |
| 812 | − <input | |
| 813 | − autoFocus | |
| 814 | − value={renamingTitle} | |
| 815 | − aria-label="Thread title" | |
| 816 | − onChange={(event) => onRenameTitleChange(event.target.value)} | |
| 817 | − onFocus={(event) => event.currentTarget.select()} | |
| 818 | − onKeyDown={handleRenameKeyDown} | |
| 819 | − onBlur={handleRenameBlur} | |
| 820 | − onClick={(event) => event.stopPropagation()} | |
| 821 | − onDoubleClick={(event) => event.stopPropagation()} | |
| 822 | − className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground" | |
| 823 | − /> | |
| 824 | − ) : ( | |
| 825 | − <span | |
| 826 | − className={cn( | |
| 827 | − "min-w-0 flex-1 text-sm transition-opacity motion-reduce:transition-none", | |
| 828 | − shouldRecede ? "font-normal" : "font-medium", | |
| 829 | − variant === "card" | |
| 830 | − ? cn( | |
| 831 | − "truncate", | |
| 832 | − isUnread || isWoke | |
| 833 | − ? "text-foreground" | |
| 834 | − : shouldRecede | |
| 835 | − ? "text-secondary-label" | |
| 836 | − : status === "failed" | |
| 837 | − ? "text-foreground/95" | |
| 838 | − : "text-foreground/90", | |
| 839 | − ) | |
| 840 | − : cn( | |
| 841 | − "truncate group-hover/v2-row:text-foreground", | |
| 842 | − props.isActive || isWoke | |
| 843 | − ? "text-foreground" | |
| 844 | − : isUnread | |
| 845 | − ? "text-muted-foreground" | |
| 846 | − : "text-secondary-label/70", | |
| 847 | − ), | |
| 848 | − isRegeneratingTitle && "opacity-[0.55]", | |
| 849 | − )} | |
| 850 | − > | |
| 851 | − {thread.title} | |
| 852 | − </span> | |
| 853 | − ); | |
| 854 | − | |
| 855 | − const prBadge = | |
| 856 | − prStatus && pr ? ( | |
| 857 | − <button | |
| 858 | − type="button" | |
| 859 | − onClick={handlePrClick} | |
| 860 | − className={cn( | |
| 861 | − // Sidebar chrome follows the interface font; tabular digits keep the | |
| 862 | − // number from reflowing as PR states stream in. | |
| 863 | − "shrink-0 text-xs tabular-nums hover:underline", | |
| 864 | − variant === "slim" && variantAction === "unsettle" | |
| 865 | − ? props.isActive | |
| 866 | − ? "text-secondary-label" | |
| 867 | − : cn("text-secondary-label transition-colors", settledPrHoverClass) | |
| 868 | − : prStatus.colorClass, | |
| 869 | − )} | |
| 870 | − aria-label={prStatus.tooltip} | |
| 871 | − > | |
| 872 | − #{pr.number} | |
| 873 | − </button> | |
| 874 | − ) : null; | |
| 875 | − const terminalStatusIcon = terminalStatus ? ( | |
| 876 | − <span | |
| 877 | − role="img" | |
| 878 | − aria-label={terminalProcessLabel(terminalProcessCount)} | |
| 879 | − data-testid={`sidebar-v2-terminal-status-${thread.id}`} | |
| 880 | − className={cn("inline-flex shrink-0 items-center justify-center", terminalStatus.colorClass)} | |
| 881 | − > | |
| 882 | − <TerminalIcon className={cn("size-3.5", terminalStatus.pulse && "animate-status-pulse")} /> | |
| 883 | − </span> | |
| 884 | − ) : null; | |
| 885 | − | |
| 886 | − if (variant === "slim") { | |
| 887 | − return ( | |
| 888 | − <li | |
| 889 | − data-thread-item | |
| 890 | − className="list-none [content-visibility:auto] [contain-intrinsic-size:auto_34px]" | |
| 891 | − > | |
| 892 | − <Tooltip> | |
| 893 | − <TooltipTrigger | |
| 894 | − render={ | |
| 895 | − <div | |
| 896 | − role="button" | |
| 897 | − tabIndex={0} | |
| 898 | − data-testid="sidebar-v2-row-slim" | |
| 899 | − aria-busy={isRegeneratingTitle || undefined} | |
| 900 | − className={cn(rowSurfaceClassName, "flex h-9 items-center gap-2.5 px-2.5")} | |
| 901 | − onClick={handleClick} | |
| 902 | − onDoubleClick={handleDoubleClick} | |
| 903 | − onKeyDown={handleKeyDown} | |
| 904 | − onContextMenu={handleContextMenu} | |
| 905 | − /> | |
| 906 | − } | |
| 907 | − > | |
| 908 | − {/* Settled history recedes: dimmed favicon at rest, restored on | |
| 909 | − hover so the tail stays scannable when you're hunting. */} | |
| 910 | − <span | |
| 911 | − className={cn( | |
| 912 | − "shrink-0 transition-opacity", | |
| 913 | − !props.isActive && | |
| 914 | − "opacity-40 grayscale group-hover/v2-row:opacity-100 group-hover/v2-row:grayscale-0", | |
| 915 | − )} | |
| 916 | − > | |
| 917 | − <ProjectFavicon | |
| 918 | − environmentId={thread.environmentId} | |
| 919 | − cwd={props.projectCwd ?? ""} | |
| 920 | − className="size-4" | |
| 921 | − fallbackIcon={MessageSquareIcon} | |
| 922 | − /> | |
| 923 | − </span> | |
| 924 | − {title} | |
| 925 | − {terminalStatusIcon} | |
| 926 | − {isRegeneratingTitle ? ( | |
| 927 | − <span role="status" className="sr-only"> | |
| 928 | − Regenerating title | |
| 929 | − </span> | |
| 930 | − ) : null} | |
| 931 | − {/* The PR badge stays outside the hover-fading slot: it must | |
| 932 | − remain visible AND clickable while the row is hovered. Only | |
| 933 | − the time/jump label yields to the settle affordance. */} | |
| 934 | − {prBadge} | |
| 935 | − <span className="relative ml-auto flex h-6 min-w-8 shrink-0 items-center justify-end"> | |
| 936 | − <span | |
| 937 | − className={cn( | |
| 938 | − "inline-flex justify-end tabular-nums text-secondary-label transition-opacity", | |
| 939 | − !isWoke && "group-hover/v2-row:opacity-0", | |
| 940 | − )} | |
| 941 | − > | |
| 942 | − {variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( | |
| 943 | − // Snoozed rows show when they come BACK, not when they were | |
| 944 | − // last touched — the return ticket is the row's whole story. | |
| 945 | − <span className="text-xs text-blue-600 tabular-nums dark:text-blue-400"> | |
| 946 | − {props.snoozeWakeLabelText} | |
| 947 | − </span> | |
| 948 | − ) : isWoke ? ( | |
| 949 | − // A wake can land straight in the settled tail (e.g. PR | |
| 950 | − // merged while snoozed); the signal must survive the trip. | |
| 951 | − <button | |
| 952 | − type="button" | |
| 953 | − aria-label="Dismiss Woke notification" | |
| 954 | − title="Dismiss Woke notification" | |
| 955 | − onClick={handleAcknowledgeWokeClick} | |
| 956 | − className="inline-flex cursor-pointer items-center gap-1 rounded-sm text-xs font-medium text-amber-700 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring dark:text-amber-300" | |
| 957 | − > | |
| 958 | − <AlarmClockIcon aria-hidden className="size-3" /> | |
| 959 | − <span role="status">Woke</span> | |
| 960 | − </button> | |
| 961 | − ) : ( | |
| 962 | − <span className="text-xs"> | |
| 963 | − {variantAction === "unsettle" | |
| 964 | − ? settledTimeLabel(thread) | |
| 965 | − : threadTimeLabel(thread)} | |
| 966 | − </span> | |
| 967 | − )} | |
| 968 | − </span> | |
| 969 | − {variantAction === "unsnooze" ? ( | |
| 970 | − !props.snoozeSupported ? null : ( | |
| 971 | − <button | |
| 972 | − type="button" | |
| 973 | − aria-label="Wake thread now" | |
| 974 | − onClick={handleUnsnoozeClick} | |
| 975 | − className={cn( | |
| 976 | − "pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100", | |
| 977 | − isWoke && "group-hover/v2-row:static", | |
| 978 | − )} | |
| 979 | − > | |
| 980 | − <AlarmClockOffIcon className="size-3" /> | |
| 981 | − </button> | |
| 982 | − ) | |
| 983 | − ) : !props.settlementSupported ? null : variantAction === "unsettle" ? ( | |
| 984 | − <button | |
| 985 | − type="button" | |
| 986 | − aria-label="Un-settle thread" | |
| 987 | − onClick={handleUnsettleClick} | |
| 988 | − className={cn( | |
| 989 | − "pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100", | |
| 990 | − isWoke && "group-hover/v2-row:static", | |
| 991 | − )} | |
| 992 | − > | |
| 993 | − <Undo2Icon className="mb-px size-3.5" /> | |
| 994 | − </button> | |
| 995 | − ) : ( | |
| 996 | − <button | |
| 997 | − type="button" | |
| 998 | − aria-label="Settle thread" | |
| 999 | − onClick={handleSettleClick} | |
| 1000 | − className={cn( | |
| 1001 | − "pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100", | |
| 1002 | − isWoke && "group-hover/v2-row:static", | |
| 1003 | − )} | |
| 1004 | − > | |
| 1005 | − <CheckIcon className="size-3" /> | |
| 1006 | − </button> | |
| 1007 | − )} | |
| 1008 | − </span> | |
| 1009 | − {props.jumpLabel ? <JumpHintBadge label={props.jumpLabel} /> : null} | |
| 1010 | − </TooltipTrigger> | |
| 1011 | − {detailsTooltip} | |
| 1012 | − </Tooltip> | |
| 1013 | − </li> | |
| 1014 | − ); | |
| 1015 | − } | |
| 1016 | − | |
| 1017 | − const diff = latestTurnDiff(thread); | |
| 1018 | − | |
| 1019 | − const sortable = props.sortable; | |
| 1020 | − return ( | |
| 1021 | − <li | |
| 1022 | − data-thread-item | |
| 1023 | − ref={sortable?.setNodeRef} | |
| 1024 | − style={ | |
| 1025 | − sortable | |
| 1026 | − ? { | |
| 1027 | − transform: CSS.Translate.toString(sortable.transform), | |
| 1028 | − transition: sortable.transition, | |
| 1029 | − } | |
| 1030 | − : undefined | |
| 1031 | − } | |
| 1032 | − {...(sortable?.listeners ?? {})} | |
| 1033 | − className={cn( | |
| 1034 | − "list-none py-0.5 [content-visibility:auto] [contain-intrinsic-size:auto_96px]", | |
| 1035 | − sortable?.isDragging && "z-20 opacity-80", | |
| 1036 | − )} | |
| 1037 | − > | |
| 1038 | − <Tooltip> | |
| 1039 | − <TooltipTrigger | |
| 1040 | − render={ | |
| 1041 | − <div | |
| 1042 | − role="button" | |
| 1043 | − tabIndex={0} | |
| 1044 | − data-testid="sidebar-v2-row-card" | |
| 1045 | − aria-busy={isRegeneratingTitle || undefined} | |
| 1046 | − className={rowSurfaceClassName} | |
| 1047 | − onClick={handleClick} | |
| 1048 | − onDoubleClick={handleDoubleClick} | |
| 1049 | − onKeyDown={handleKeyDown} | |
| 1050 | − onContextMenu={handleContextMenu} | |
| 1051 | − /> | |
| 1052 | − } | |
| 1053 | − > | |
| 1054 | − <div className="relative z-10 h-[4.875rem] px-[var(--sidebar-row-content-inset)] py-[var(--sidebar-content-inset)]"> | |
| 1055 | − <div className="flex h-5 min-w-0 items-center gap-1.5"> | |
| 1056 | − <ProjectFavicon | |
| 1057 | − environmentId={thread.environmentId} | |
| 1058 | − cwd={props.projectCwd ?? ""} | |
| 1059 | − className="size-4 shrink-0" | |
| 1060 | − /> | |
| 1061 | − {props.projectTitle ? ( | |
| 1062 | − <span | |
| 1063 | − className={cn( | |
| 1064 | − "min-w-0 flex-1 truncate text-secondary-label text-xs", | |
| 1065 | − shouldRecede ? "font-normal" : "font-medium", | |
| 1066 | − )} | |
| 1067 | − > | |
| 1068 | − {props.projectTitle} | |
| 1069 | − </span> | |
| 1070 | − ) : ( | |
| 1071 | − <span className="flex-1" /> | |
| 1072 | − )} | |
| 1073 | − {props.isPinned ? ( | |
| 1074 | − props.pinningSupported ? ( | |
| 1075 | − <button | |
| 1076 | − type="button" | |
| 1077 | − aria-label="Unpin thread" | |
| 1078 | − title="Unpin thread" | |
| 1079 | − onClick={handleUnpinClick} | |
| 1080 | − className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring" | |
| 1081 | − > | |
| 1082 | − <PinIcon aria-hidden className="size-3 shrink-0" /> | |
| 1083 | − </button> | |
| 1084 | − ) : ( | |
| 1085 | − <PinIcon | |
| 1086 | − aria-label="Pinned" | |
| 1087 | − role="img" | |
| 1088 | − className="size-3 shrink-0 text-muted-foreground/65" | |
| 1089 | − /> | |
| 1090 | − ) | |
| 1091 | − ) : null} | |
| 1092 | − {/* The visible state owns this slot's width: status at rest, | |
| 1093 | − actions on hover/keyboard focus or while the popover is open. Keeping | |
| 1094 | − the hidden state out of flow lets the project label reclaim | |
| 1095 | − space without either state overlapping it. */} | |
| 1096 | − <span className="group/v2-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs"> | |
| 1097 | − {/* Read-only status labels yield to the hover actions. Woke is | |
| 1098 | − itself an action, so it stays pointer-enabled and visible | |
| 1099 | − while the other controls appear beside it. */} | |
| 1100 | − <span | |
| 1101 | − className={cn( | |
| 1102 | − isWokeStatus | |
| 1103 | − ? "pointer-events-auto" | |
| 1104 | − : "pointer-events-none group-has-[:focus-visible]/v2-status-slot:absolute group-has-[:focus-visible]/v2-status-slot:right-0 group-has-[:focus-visible]/v2-status-slot:opacity-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0", | |
| 1105 | − "self-center justify-self-end tabular-nums text-secondary-label transition-opacity", | |
| 1106 | − snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0", | |
| 1107 | − )} | |
| 1108 | − > | |
| 1109 | − {topStatus ? ( | |
| 1110 | − isWokeStatus ? ( | |
| 1111 | − <button | |
| 1112 | − type="button" | |
| 1113 | − aria-label="Dismiss Woke notification" | |
| 1114 | − title="Dismiss Woke notification" | |
| 1115 | − onClick={handleAcknowledgeWokeClick} | |
| 1116 | − className={cn( | |
| 1117 | − "inline-flex cursor-pointer items-center gap-1 rounded-sm font-medium outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring", | |
| 1118 | − topStatus.className, | |
| 1119 | − )} | |
| 1120 | − > | |
| 1121 | − <AlarmClockIcon aria-hidden className="size-4 shrink-0" /> | |
| 1122 | − <span role="status">{topStatus.label}</span> | |
| 1123 | − </button> | |
| 1124 | − ) : ( | |
| 1125 | − <span | |
| 1126 | − className={cn( | |
| 1127 | − "inline-flex items-center gap-1 font-medium", | |
| 1128 | − topStatus.className, | |
| 1129 | − )} | |
| 1130 | − > | |
| 1131 | − {topStatus.icon === "working" ? ( | |
| 1132 | − <CircleDashedIcon aria-hidden className="size-4 shrink-0" /> | |
| 1133 | − ) : topStatus.icon === "done" ? ( | |
| 1134 | − <CircleCheckIcon aria-hidden className="size-4 shrink-0" /> | |
| 1135 | − ) : null} | |
| 1136 | − {/* The label alone is the live region: a role="status" | |
| 1137 | − wrapper around the ticking duration would make | |
| 1138 | − screen readers announce every second. */} | |
| 1139 | − <span role="status">{topStatus.label}</span> | |
| 1140 | − {status === "working" ? ( | |
| 1141 | − <span aria-hidden> | |
| 1142 | − <WorkingDuration startedAt={resolveWorkingStartedAt(thread)} /> | |
| 1143 | − </span> | |
| 1144 | − ) : null} | |
| 1145 | − </span> | |
| 1146 | − ) | |
| 1147 | − ) : ( | |
| 1148 | − threadTimeLabel(thread) | |
| 1149 | − )} | |
| 1150 | − </span> | |
| 1151 | − {props.settlementSupported || showSnoozeButton ? ( | |
| 1152 | − <span | |
| 1153 | − className={cn( | |
| 1154 | − // focus-visible, not focus-within: a mouse click leaves | |
| 1155 | − // the Settle button focused, and a plain focus-within | |
| 1156 | − // would keep the controls pinned over the status label | |
| 1157 | − // once the pointer moves away (e.g. after a failed | |
| 1158 | − // settle) instead of cross-fading back. | |
| 1159 | − "pointer-events-none absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:static group-hover/v2-row:opacity-100", | |
| 1160 | − snoozeMenuOpen && "pointer-events-auto static opacity-100", | |
| 1161 | − )} | |
| 1162 | − > | |
| 1163 | − {showSnoozeButton ? ( | |
| 1164 | − <SnoozePopoverButton | |
| 1165 | − open={snoozeMenuOpen} | |
| 1166 | − onOpenChange={setSnoozeMenuOpen} | |
| 1167 | − onSnooze={handleSnoozePreset} | |
| 1168 | − timestampFormat={props.timestampFormat} | |
| 1169 | − /> | |
| 1170 | − ) : null} | |
| 1171 | − {props.settlementSupported ? ( | |
| 1172 | − <button | |
| 1173 | − type="button" | |
| 1174 | − aria-label="Settle thread" | |
| 1175 | − onClick={handleSettleClick} | |
| 1176 | − className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" | |
| 1177 | − > | |
| 1178 | − <CheckIcon className="size-3.5" /> | |
| 1179 | − Settle | |
| 1180 | − </button> | |
| 1181 | − ) : null} | |
| 1182 | − </span> | |
| 1183 | − ) : null} | |
| 1184 | − </span> | |
| 1185 | − </div> | |
| 1186 | − <div className="mt-1 flex min-w-0"> | |
| 1187 | − {title} | |
| 1188 | − {isRegeneratingTitle ? ( | |
| 1189 | − <span role="status" className="sr-only"> | |
| 1190 | − Regenerating title | |
| 1191 | − </span> | |
| 1192 | − ) : null} | |
| 1193 | − </div> | |
| 1194 | − <div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-secondary-label text-xs"> | |
| 1195 | − {/* While working, the current plan step outranks the branch: | |
| 1196 | − it's the one line that says what the thread is doing. */} | |
| 1197 | − {status === "working" && thread.planProgress ? ( | |
| 1198 | − <span className="min-w-0 flex-1 truncate whitespace-nowrap"> | |
| 1199 | − {thread.planProgress.step} | |
| 1200 | − {/* Completed count, matching the transcript chip's n/m. */} | |
| 1201 | − <span className="text-icon-muted tabular-nums"> | |
| 1202 | − {" "} | |
| 1203 | − {thread.planProgress.completedSteps}/{thread.planProgress.totalSteps} | |
| 1204 | − </span> | |
| 1205 | − </span> | |
| 1206 | − ) : thread.branch ? ( | |
| 1207 | − <span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span> | |
| 1208 | − ) : ( | |
| 1209 | − <span className="flex-1" /> | |
| 1210 | − )} | |
| 1211 | − {terminalStatusIcon} | |
| 1212 | − {prBadge} | |
| 1213 | − {diff ? ( | |
| 1214 | − <span className="shrink-0 font-mono"> | |
| 1215 | − <span className="text-emerald-600 dark:text-emerald-400">+{diff.insertions}</span>{" "} | |
| 1216 | − <span className="text-red-600 dark:text-red-400">−{diff.deletions}</span> | |
| 1217 | − </span> | |
| 1218 | − ) : null} | |
| 1219 | − <span | |
| 1220 | − aria-hidden | |
| 1221 | − className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" | |
| 1222 | − > | |
| 1223 | − {isRemote ? ( | |
| 1224 | − <span className="inline-flex shrink-0 items-center text-sidebar-muted-foreground/70"> | |
| 1225 | − <ServerIcon aria-hidden className="size-3.5" /> | |
| 1226 | − </span> | |
| 1227 | − ) : null} | |
| 1228 | − {driverKind ? ( | |
| 1229 | − <span className="inline-flex shrink-0 items-center opacity-60"> | |
| 1230 | − <ProviderInstanceIcon | |
| 1231 | − driverKind={driverKind} | |
| 1232 | − displayName={thread.session?.providerName ?? modelInstanceId} | |
| 1233 | − iconClassName="size-3.5" | |
| 1234 | − /> | |
| 1235 | − </span> | |
| 1236 | − ) : null} | |
| 1237 | − </span> | |
| 1238 | − </div> | |
| 1239 | − </div> | |
| 1240 | − {props.jumpLabel ? <JumpHintBadge label={props.jumpLabel} /> : null} | |
| 1241 | − </TooltipTrigger> | |
| 1242 | − {detailsTooltip} | |
| 1243 | − </Tooltip> | |
| 1244 | − </li> | |
| 1245 | − ); | |
| 1246 | −}); | |
| 1247 | − | |
| 1248 | −function latestTurnDiff( | |
| 1249 | − thread: SidebarThreadSummary, | |
| 1250 | −): { insertions: number; deletions: number } | null { | |
| 1251 | − // Shells don't carry checkpoint summaries; diff stats render only when the | |
| 1252 | − // shell projection grows them. Kept as a seam so the row layout is ready. | |
| 1253 | − void thread; | |
| 1254 | − return null; | |
| 1255 | −} | |
| 1256 | − | |
| 1257 | −const SidebarV2SearchResultRow = memo(function SidebarV2SearchResultRow(props: { | |
| 1258 | − thread: SidebarThreadSummary; | |
| 1259 | − projectCwd: string | null; | |
| 1260 | − projectTitle: string | null; | |
| 1261 | − environmentLabel: string | null; | |
| 1262 | − providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>; | |
| 1263 | − isHighlighted: boolean; | |
| 1264 | − isRouteActive: boolean; | |
| 1265 | − resultId: string; | |
| 1266 | − onHighlight: () => void; | |
| 1267 | − onSelect: () => void; | |
| 1268 | −}) { | |
| 1269 | − const { thread } = props; | |
| 1270 | − // Same details tooltip as the regular rows: a search hit is still a thread, | |
| 1271 | − // and the hover card is how you disambiguate identically-titled results. | |
| 1272 | − const gitCwd = thread.worktreePath ?? props.projectCwd; | |
| 1273 | − const gitStatus = useEnvironmentQuery( | |
| 1274 | − (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null | |
| 1275 | − ? vcsEnvironment.status({ | |
| 1276 | − environmentId: thread.environmentId, | |
| 1277 | − input: { cwd: gitCwd }, | |
| 1278 | − }) | |
| 1279 | − : null, | |
| 1280 | − ); | |
| 1281 | − const branchMismatch = resolveLocalCheckoutBranchMismatch({ | |
| 1282 | − effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", | |
| 1283 | − activeWorktreePath: thread.worktreePath, | |
| 1284 | − activeThreadBranch: thread.branch, | |
| 1285 | − currentGitBranch: gitStatus.data?.refName ?? null, | |
| 1286 | − }); | |
| 1287 | − const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; | |
| 1288 | − const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; | |
| 1289 | − const driverKind = providerEntry?.driverKind ?? null; | |
| 1290 | − const selectedModel = providerEntry?.models.find( | |
| 1291 | − (model) => model.slug === thread.modelSelection.model, | |
| 1292 | − ); | |
| 1293 | − const modelLabel = selectedModel | |
| 1294 | − ? getTriggerDisplayModelLabel(selectedModel) | |
| 1295 | − : thread.modelSelection.model; | |
| 1296 | − const runningTerminalIds = useThreadRunningTerminalIds({ | |
| 1297 | − environmentId: thread.environmentId, | |
| 1298 | − threadId: thread.id, | |
| 1299 | − }); | |
| 1300 | − const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); | |
| 1301 | − return ( | |
| 1302 | − <li role="presentation" className="list-none"> | |
| 1303 | − <Tooltip> | |
| 1304 | − <TooltipTrigger | |
| 1305 | − render={ | |
| 1306 | − <button | |
| 1307 | − id={props.resultId} | |
| 1308 | − type="button" | |
| 1309 | − role="option" | |
| 1310 | − // aria-activedescendant options: focus stays on the search input, | |
| 1311 | − // which owns all keyboard interaction for the listbox. | |
| 1312 | − tabIndex={-1} | |
| 1313 | − aria-selected={props.isHighlighted} | |
| 1314 | − aria-current={props.isRouteActive ? "page" : undefined} | |
| 1315 | − aria-label={ | |
| 1316 | − props.projectTitle ? `${thread.title}, ${props.projectTitle}` : thread.title | |
| 1317 | − } | |
| 1318 | − onMouseMove={props.onHighlight} | |
| 1319 | − onClick={props.onSelect} | |
| 1320 | − className={cn( | |
| 1321 | − "flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm outline-none", | |
| 1322 | − props.isHighlighted || props.isRouteActive | |
| 1323 | − ? "bg-sidebar-row-active text-sidebar-foreground" | |
| 1324 | − : "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground", | |
| 1325 | − )} | |
| 1326 | − /> | |
| 1327 | − } | |
| 1328 | − > | |
| 1329 | − <ProjectFavicon | |
| 1330 | − environmentId={thread.environmentId} | |
| 1331 | − cwd={props.projectCwd ?? ""} | |
| 1332 | − className="size-4 shrink-0" | |
| 1333 | − fallbackIcon={MessageSquareIcon} | |
| 1334 | − /> | |
| 1335 | − <span className="min-w-0 flex-1 truncate">{thread.title}</span> | |
| 1336 | − <span className="shrink-0 text-xs text-muted-foreground/55 tabular-nums"> | |
| 1337 | − {threadTimeLabel(thread)} | |
| 1338 | − </span> | |
| 1339 | − </TooltipTrigger> | |
| 1340 | − <SidebarV2ThreadTooltip | |
| 1341 | − thread={thread} | |
| 1342 | − projectTitle={props.projectTitle} | |
| 1343 | − projectCwd={props.projectCwd} | |
| 1344 | − environmentLabel={props.environmentLabel} | |
| 1345 | − driverKind={driverKind} | |
| 1346 | − modelInstanceId={modelInstanceId} | |
| 1347 | − modelLabel={modelLabel} | |
| 1348 | − branchMismatch={branchMismatch} | |
| 1349 | − terminalStatus={terminalStatus} | |
| 1350 | − terminalProcessCount={runningTerminalIds.length} | |
| 1351 | − /> | |
| 1352 | − </Tooltip> | |
| 1353 | − </li> | |
| 1354 | − ); | |
| 1355 | −}); | |
| 1356 | − | |
| 1357 | −export default function SidebarV2() { | |
| 1358 | − const projects = useProjects(); | |
| 1359 | − const projectOrder = useUiStateStore((store) => store.projectOrder); | |
| 1360 | − const threads = useThreadShells(); | |
| 1361 | − const router = useRouter(); | |
| 1362 | − const { isMobile, setOpenMobile } = useSidebar(); | |
| 1363 | − const keybindings = useAtomValue(primaryServerKeybindingsAtom); | |
| 1364 | − const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays); | |
| 1365 | − const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); | |
| 1366 | − const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); | |
| 1367 | − const timestampFormat = useClientSettings((s) => s.timestampFormat); | |
| 1368 | − const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); | |
| 1369 | − const { | |
| 1370 | − settleThread, | |
| 1371 | − unsettleThread, | |
| 1372 | − snoozeThread, | |
| 1373 | − unsnoozeThread, | |
| 1374 | − pinThread, | |
| 1375 | − unpinThread, | |
| 1376 | − reorderPinnedThread, | |
| 1377 | − deleteThread, | |
| 1378 | − } = useThreadActions(); | |
| 1379 | − const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { | |
| 1380 | − reportFailure: false, | |
| 1381 | − }); | |
| 1382 | − const deleteProject = useAtomCommand(projectEnvironment.delete, { | |
| 1383 | − reportFailure: false, | |
| 1384 | − }); | |
| 1385 | − const updateProject = useAtomCommand(projectEnvironment.update, { | |
| 1386 | − reportFailure: false, | |
| 1387 | − }); | |
| 1388 | − const updateSettings = useUpdateClientSettings(); | |
| 1389 | − const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ | |
| 1390 | − onCopy: ({ path }) => { | |
| 1391 | − toastManager.add({ | |
| 1392 | − type: "success", | |
| 1393 | − title: "Path copied", | |
| 1394 | − description: path, | |
| 1395 | − }); | |
| 1396 | − }, | |
| 1397 | − onError: (error) => { | |
| 1398 | − toastManager.add( | |
| 1399 | − stackedThreadToast({ | |
| 1400 | − type: "error", | |
| 1401 | − title: "Failed to copy path", | |
| 1402 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 1403 | − }), | |
| 1404 | − ); | |
| 1405 | − }, | |
| 1406 | − }); | |
| 1407 | − const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({ | |
| 1408 | − target: "branch name", | |
| 1409 | − onCopy: ({ branch }) => { | |
| 1410 | − toastManager.add({ | |
| 1411 | − type: "success", | |
| 1412 | − title: "Branch copied", | |
| 1413 | − description: branch, | |
| 1414 | − }); | |
| 1415 | − }, | |
| 1416 | − onError: (error) => { | |
| 1417 | − toastManager.add( | |
| 1418 | − stackedThreadToast({ | |
| 1419 | − type: "error", | |
| 1420 | − title: "Failed to copy branch", | |
| 1421 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 1422 | − }), | |
| 1423 | − ); | |
| 1424 | − }, | |
| 1425 | − }); | |
| 1426 | − const [projectActionsTarget, setProjectActionsTarget] = useState<SidebarProjectSnapshot | null>( | |
| 1427 | − null, | |
| 1428 | − ); | |
| 1429 | − const [projectScopeMenuOpen, setProjectScopeMenuOpen] = useState(false); | |
| 1430 | − const newThreadContext = useHandleNewThread(); | |
| 1431 | − const openAddProjectCommandPalette = useCallback( | |
| 1432 | − () => openCommandPalette({ open: "add-project" }), | |
| 1433 | − [], | |
| 1434 | − ); | |
| 1435 | − const { environments } = useEnvironments(); | |
| 1436 | − const primaryEnvironmentId = usePrimaryEnvironmentId(); | |
| 1437 | − const clearSelection = useThreadSelectionStore((s) => s.clearSelection); | |
| 1438 | − const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); | |
| 1439 | − const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); | |
| 1440 | − const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo); | |
| 1441 | − const markThreadUnread = useUiStateStore((s) => s.markThreadUnread); | |
| 1442 | − const markThreadVisited = useUiStateStore((s) => s.markThreadVisited); | |
| 1443 | − const acknowledgeWoke = useCallback( | |
| 1444 | − (threadRef: ScopedThreadRef, visitedAt: string) => { | |
| 1445 | − markThreadVisited(scopedThreadKey(threadRef), visitedAt); | |
| 1446 | − }, | |
| 1447 | − [markThreadVisited], | |
| 1448 | − ); | |
| 1449 | − const routeTarget = useParams({ | |
| 1450 | − strict: false, | |
| 1451 | − select: (params) => resolveThreadRouteTarget(params), | |
| 1452 | − }); | |
| 1453 | − const routeDraftThread = useComposerDraftStore((store) => | |
| 1454 | − routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null, | |
| 1455 | − ); | |
| 1456 | − const routeThreadRef = useMemo( | |
| 1457 | − () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread), | |
| 1458 | − [routeDraftThread, routeTarget], | |
| 1459 | − ); | |
| 1460 | − const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; | |
| 1461 | − const routeTargetRef = useRef(routeTarget); | |
| 1462 | − routeTargetRef.current = routeTarget; | |
| 1463 | − // Post-settle navigation validates against the CURRENT route, not the one | |
| 1464 | − // captured when the settle started: if the user navigated elsewhere while | |
| 1465 | − // the command was in flight, completing it must not yank them away. | |
| 1466 | − const routeThreadKeyRef = useRef(routeThreadKey); | |
| 1467 | − routeThreadKeyRef.current = routeThreadKey; | |
| 1468 | − | |
| 1469 | − const environmentLabelById = useMemo( | |
| 1470 | − () => | |
| 1471 | − new Map( | |
| 1472 | − environments.map((environment) => [environment.environmentId, environment.label] as const), | |
| 1473 | − ), | |
| 1474 | − [environments], | |
| 1475 | − ); | |
| 1476 | − const orderedProjects = useMemo( | |
| 1477 | − () => | |
| 1478 | − orderItemsByPreferredIds({ | |
| 1479 | − items: projects, | |
| 1480 | − preferredIds: projectOrder, | |
| 1481 | − getId: getProjectOrderKey, | |
| 1482 | − getPreferenceIds: (project) => [ | |
| 1483 | − getProjectOrderKey(project), | |
| 1484 | − legacyProjectCwdPreferenceKey(project.workspaceRoot), | |
| 1485 | − ], | |
| 1486 | − }), | |
| 1487 | − [projectOrder, projects], | |
| 1488 | − ); | |
| 1489 | − const unsortedProjectGroups = useMemo( | |
| 1490 | − () => | |
| 1491 | − buildSidebarProjectSnapshots({ | |
| 1492 | − projects: sidebarProjectSortOrder === "manual" ? orderedProjects : projects, | |
| 1493 | − settings: projectGroupingSettings, | |
| 1494 | − primaryEnvironmentId, | |
| 1495 | − resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, | |
| 1496 | − }), | |
| 1497 | − [ | |
| 1498 | − environmentLabelById, | |
| 1499 | − orderedProjects, | |
| 1500 | − primaryEnvironmentId, | |
| 1501 | − projectGroupingSettings, | |
| 1502 | − projects, | |
| 1503 | − sidebarProjectSortOrder, | |
| 1504 | − ], | |
| 1505 | − ); | |
| 1506 | − const projectGroups = useMemo( | |
| 1507 | − () => sortLogicalProjectsForSidebar(unsortedProjectGroups, threads, sidebarProjectSortOrder), | |
| 1508 | − [sidebarProjectSortOrder, threads, unsortedProjectGroups], | |
| 1509 | − ); | |
| 1510 | − const serverProviders = useAtomValue(primaryServerProvidersAtom); | |
| 1511 | − const providerEntryByInstanceId = useMemo( | |
| 1512 | − () => | |
| 1513 | − new Map( | |
| 1514 | − deriveProviderInstanceEntries(serverProviders).map( | |
| 1515 | − (entry) => [entry.instanceId as string, entry] as const, | |
| 1516 | − ), | |
| 1517 | − ), | |
| 1518 | − [serverProviders], | |
| 1519 | − ); | |
| 1520 | − const projectCwdByKey = useMemo( | |
| 1521 | − () => | |
| 1522 | − new Map( | |
| 1523 | − projects.map((project) => [ | |
| 1524 | − `${project.environmentId}:${project.id}`, | |
| 1525 | − project.workspaceRoot, | |
| 1526 | − ]), | |
| 1527 | − ), | |
| 1528 | − [projects], | |
| 1529 | − ); | |
| 1530 | − const projectDisplayNameByKey = useMemo( | |
| 1531 | − () => | |
| 1532 | − new Map( | |
| 1533 | − projectGroups.flatMap((group) => | |
| 1534 | − group.memberProjects.map( | |
| 1535 | − (project) => [`${project.environmentId}:${project.id}`, group.displayName] as const, | |
| 1536 | − ), | |
| 1537 | − ), | |
| 1538 | − ), | |
| 1539 | − [projectGroups], | |
| 1540 | − ); | |
| 1541 | − | |
| 1542 | − // now is quantized to the minute so effectiveSettled memoization doesn't | |
| 1543 | − // churn on every render; auto-settle thresholds are day-granular anyway. | |
| 1544 | − const nowMinute = useNowMinute(); | |
| 1545 | − // Snooze wake times are second-precise, so classifying with the quantized | |
| 1546 | − // minute would hold a woken thread on the shelf for up to a minute. The | |
| 1547 | − // tick is a plain counter bumped exactly at the next wake boundary (armed | |
| 1548 | − // below, after the partition knows the boundary); the partition reads a | |
| 1549 | − // fresh clock whenever it recomputes. | |
| 1550 | − const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); | |
| 1551 | − | |
| 1552 | − // PR states stream in per-row (rows own the VCS subscriptions); a merged or | |
| 1553 | − // closed PR auto-settles its thread on the next partition. | |
| 1554 | − const [changeRequestStateByKey, setChangeRequestStateByKey] = useState< | |
| 1555 | − ReadonlyMap<string, "open" | "closed" | "merged"> | |
| 1556 | − >(() => new Map()); | |
| 1557 | − const handleChangeRequestState = useCallback( | |
| 1558 | − (threadKey: string, state: "open" | "closed" | "merged" | null) => { | |
| 1559 | − setChangeRequestStateByKey((current) => { | |
| 1560 | − if ((current.get(threadKey) ?? null) === state) return current; | |
| 1561 | − const next = new Map(current); | |
| 1562 | − if (state === null) { | |
| 1563 | − next.delete(threadKey); | |
| 1564 | − } else { | |
| 1565 | − next.set(threadKey, state); | |
| 1566 | − } | |
| 1567 | − return next; | |
| 1568 | − }); | |
| 1569 | − }, | |
| 1570 | − [], | |
| 1571 | − ); | |
| 1572 | − | |
| 1573 | − // Project scope: one menu above the list. Scoping filters the list without | |
| 1574 | − // making the header width depend on the number or length of project names. | |
| 1575 | − const [projectScopeKey, setProjectScopeKey] = useState<string | null>(null); | |
| 1576 | − const scopedProjectGroup = useMemo( | |
| 1577 | − () => | |
| 1578 | − projectScopeKey === null | |
| 1579 | − ? null | |
| 1580 | − : (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null), | |
| 1581 | − [projectGroups, projectScopeKey], | |
| 1582 | − ); | |
| 1583 | − const scopedProjectKeys = useMemo( | |
| 1584 | − () => | |
| 1585 | − scopedProjectGroup === null | |
| 1586 | − ? null | |
| 1587 | − : new Set( | |
| 1588 | − scopedProjectGroup.memberProjectRefs.map( | |
| 1589 | − (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, | |
| 1590 | − ), | |
| 1591 | − ), | |
| 1592 | − [scopedProjectGroup], | |
| 1593 | − ); | |
| 1594 | − useEffect(() => { | |
| 1595 | − if (projectScopeKey !== null && scopedProjectGroup === null) { | |
| 1596 | − setProjectScopeKey(null); | |
| 1597 | − } | |
| 1598 | − }, [projectScopeKey, scopedProjectGroup]); | |
| 1599 | − // Scope flips drop the selection: rows selected under the old scope may be | |
| 1600 | − // hidden now, and bulk actions must never count or touch invisible rows. | |
| 1601 | − useEffect(() => { | |
| 1602 | − clearSelection(); | |
| 1603 | − }, [clearSelection, projectScopeKey]); | |
| 1604 | − | |
| 1605 | − const handleRemoveProjectMembers = useCallback( | |
| 1606 | − async (projectGroup: SidebarProjectSnapshot, members: readonly SidebarProjectGroupMember[]) => { | |
| 1607 | − const api = readLocalApi(); | |
| 1608 | − if (!api) return; | |
| 1609 | − | |
| 1610 | − const memberKeys = new Set(members.map((member) => `${member.environmentId}:${member.id}`)); | |
| 1611 | − const projectThreads = threads.filter((thread) => | |
| 1612 | − memberKeys.has(`${thread.environmentId}:${thread.projectId}`), | |
| 1613 | − ); | |
| 1614 | − const isWholeGroup = members.length === projectGroup.memberProjects.length; | |
| 1615 | − const singleMember = members.length === 1 ? members[0]! : null; | |
| 1616 | − const targetLabel = singleMember?.title ?? projectGroup.displayName; | |
| 1617 | − const confirmed = await settlePromise(() => | |
| 1618 | − api.dialogs.confirm( | |
| 1619 | − projectThreads.length > 0 | |
| 1620 | − ? [ | |
| 1621 | − `Remove project "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`, | |
| 1622 | − ...(singleMember | |
| 1623 | − ? [ | |
| 1624 | − `Path: ${singleMember.workspaceRoot}`, | |
| 1625 | − ...(singleMember.environmentLabel | |
| 1626 | − ? [`Environment: ${singleMember.environmentLabel}`] | |
| 1627 | − : []), | |
| 1628 | − ] | |
| 1629 | − : [`This removes ${members.length} grouped project entries.`]), | |
| 1630 | − "This permanently clears conversation history for those threads.", | |
| 1631 | − isWholeGroup | |
| 1632 | − ? "This removes only the project entries, not the files on disk." | |
| 1633 | − : "Other entries in this grouped project are unaffected.", | |
| 1634 | − "This action cannot be undone.", | |
| 1635 | − ].join("\n") | |
| 1636 | − : [ | |
| 1637 | − `Remove project "${targetLabel}"?`, | |
| 1638 | − ...(singleMember | |
| 1639 | − ? [ | |
| 1640 | − `Path: ${singleMember.workspaceRoot}`, | |
| 1641 | − ...(singleMember.environmentLabel | |
| 1642 | − ? [`Environment: ${singleMember.environmentLabel}`] | |
| 1643 | − : []), | |
| 1644 | − ] | |
| 1645 | − : [`This removes ${members.length} grouped project entries.`]), | |
| 1646 | − isWholeGroup | |
| 1647 | − ? "This removes only the project entries, not the files on disk." | |
| 1648 | − : "Other entries in this grouped project are unaffected.", | |
| 1649 | − ].join("\n"), | |
| 1650 | − ), | |
| 1651 | − ); | |
| 1652 | − if (confirmed._tag === "Failure" || !confirmed.value) return; | |
| 1653 | − | |
| 1654 | − const draftStore = useComposerDraftStore.getState(); | |
| 1655 | − let shouldNavigate = false; | |
| 1656 | − for (const project of members) { | |
| 1657 | − const memberThreads = projectThreads.filter( | |
| 1658 | − (thread) => | |
| 1659 | − thread.environmentId === project.environmentId && thread.projectId === project.id, | |
| 1660 | − ); | |
| 1661 | − const projectRef = scopeProjectRef(project.environmentId, project.id); | |
| 1662 | − const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef); | |
| 1663 | − const memberRemovalNeedsNavigation = shouldNavigateAfterProjectRemoval({ | |
| 1664 | − routeTarget: routeTargetRef.current, | |
| 1665 | − projectThreads: memberThreads, | |
| 1666 | − projectDraftId: projectDraftThread?.draftId ?? null, | |
| 1667 | − }); | |
| 1668 | − | |
| 1669 | − const result = await deleteProject({ | |
| 1670 | − environmentId: project.environmentId, | |
| 1671 | − input: { | |
| 1672 | − projectId: project.id, | |
| 1673 | − ...(memberThreads.length > 0 ? { force: true } : {}), | |
| 1674 | − }, | |
| 1675 | − }); | |
| 1676 | − if (result._tag === "Failure") { | |
| 1677 | − if (!isAtomCommandInterrupted(result)) { | |
| 1678 | − const error = squashAtomCommandFailure(result); | |
| 1679 | − toastManager.add( | |
| 1680 | − stackedThreadToast({ | |
| 1681 | − type: "error", | |
| 1682 | − title: `Failed to remove "${project.title}"`, | |
| 1683 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 1684 | − }), | |
| 1685 | − ); | |
| 1686 | − } | |
| 1687 | − if (shouldNavigate) { | |
| 1688 | − void router.navigate({ to: "/" }); | |
| 1689 | − } | |
| 1690 | − return; | |
| 1691 | − } | |
| 1692 | − | |
| 1693 | − shouldNavigate ||= memberRemovalNeedsNavigation; | |
| 1694 | − if (projectDraftThread) { | |
| 1695 | − draftStore.clearDraftThread(projectDraftThread.draftId); | |
| 1696 | − } | |
| 1697 | − draftStore.clearProjectDraftThreadId(projectRef); | |
| 1698 | − } | |
| 1699 | − | |
| 1700 | − if (shouldNavigate) { | |
| 1701 | − void router.navigate({ to: "/" }); | |
| 1702 | − } | |
| 1703 | − }, | |
| 1704 | − [deleteProject, router, threads], | |
| 1705 | − ); | |
| 1706 | − | |
| 1707 | − const renameProjectMember = useCallback( | |
| 1708 | − async (member: SidebarProjectGroupMember, nextTitle: string) => { | |
| 1709 | − const title = nextTitle.trim(); | |
| 1710 | − if (!title) { | |
| 1711 | − toastManager.add({ type: "warning", title: "Project title cannot be empty" }); | |
| 1712 | − return; | |
| 1713 | − } | |
| 1714 | − if (title === member.title) return; | |
| 1715 | − const result = await updateProject({ | |
| 1716 | − environmentId: member.environmentId, | |
| 1717 | − input: { projectId: member.id, title }, | |
| 1718 | − }); | |
| 1719 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 1720 | − const error = squashAtomCommandFailure(result); | |
| 1721 | − toastManager.add( | |
| 1722 | − stackedThreadToast({ | |
| 1723 | − type: "error", | |
| 1724 | − title: "Failed to rename project", | |
| 1725 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 1726 | − }), | |
| 1727 | − ); | |
| 1728 | − } | |
| 1729 | − }, | |
| 1730 | − [updateProject], | |
| 1731 | − ); | |
| 1732 | − | |
| 1733 | − const updateProjectGroupingPreference = useCallback( | |
| 1734 | − (member: SidebarProjectGroupMember, selection: SidebarProjectGroupingMode | "inherit") => { | |
| 1735 | − const overrideKey = deriveProjectGroupingOverrideKey(member); | |
| 1736 | − const nextOverrides = { ...projectGroupingSettings.sidebarProjectGroupingOverrides }; | |
| 1737 | − if (selection === "inherit") { | |
| 1738 | − delete nextOverrides[overrideKey]; | |
| 1739 | − } else { | |
| 1740 | − nextOverrides[overrideKey] = selection; | |
| 1741 | − } | |
| 1742 | − updateSettings({ sidebarProjectGroupingOverrides: nextOverrides }); | |
| 1743 | − }, | |
| 1744 | − [projectGroupingSettings.sidebarProjectGroupingOverrides, updateSettings], | |
| 1745 | − ); | |
| 1746 | − | |
| 1747 | − const handleProjectActions = useCallback( | |
| 1748 | − (event: ReactMouseEvent<HTMLButtonElement>, projectGroup: SidebarProjectSnapshot) => { | |
| 1749 | − event.preventDefault(); | |
| 1750 | − event.stopPropagation(); | |
| 1751 | − setProjectScopeMenuOpen(false); | |
| 1752 | − window.requestAnimationFrame(() => setProjectActionsTarget(projectGroup)); | |
| 1753 | − }, | |
| 1754 | − [], | |
| 1755 | − ); | |
| 1756 | − | |
| 1757 | − // Settled threads stay in the live shell stream (settled ≠ archived), so | |
| 1758 | − // the partition works directly off live shells: no archived-snapshot | |
| 1759 | − // merging, no optimistic holds. Archived threads remain hidden here — | |
| 1760 | − // archive keeps its original "remove from sidebar" meaning. | |
| 1761 | − const serverConfigs = useAtomValue(environmentServerConfigsAtom); | |
| 1762 | − const { | |
| 1763 | − pinnedThreads, | |
| 1764 | − reorderablePinnedKeys, | |
| 1765 | − activeThreads, | |
| 1766 | − snoozedThreads, | |
| 1767 | − settledThreads, | |
| 1768 | − snoozeNow, | |
| 1769 | − } = useMemo(() => { | |
| 1770 | − const now = `${nowMinute}:00.000Z`; | |
| 1771 | − // Snooze classification uses a REAL clock, not the quantized minute: | |
| 1772 | − // wake times are second-precise and a woken thread must not linger on | |
| 1773 | − // the shelf for the rest of the minute. snoozeWakeTick re-runs this | |
| 1774 | − // memo exactly at the next wake boundary. | |
| 1775 | − void snoozeWakeTick; | |
| 1776 | − const preciseNow = new Date().toISOString(); | |
| 1777 | − const visible = threads.filter( | |
| 1778 | − (thread) => | |
| 1779 | − thread.archivedAt === null && | |
| 1780 | − (scopedProjectKeys === null || | |
| 1781 | − scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)), | |
| 1782 | − ); | |
| 1783 | − const pinned: EnvironmentThreadShell[] = []; | |
| 1784 | − const active: EnvironmentThreadShell[] = []; | |
| 1785 | − const snoozed: EnvironmentThreadShell[] = []; | |
| 1786 | − const settled: EnvironmentThreadShell[] = []; | |
| 1787 | − for (const thread of visible) { | |
| 1788 | − // Threads on servers without the settlement capability (old server, | |
| 1789 | − // or descriptor not loaded yet) never classify as settled: the user | |
| 1790 | − // could neither un-settle nor pin them, so auto-settling them would | |
| 1791 | − // strand rows in a tail with no working affordances. | |
| 1792 | − const supportsSettlement = | |
| 1793 | − serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true; | |
| 1794 | − const supportsSnooze = | |
| 1795 | − serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; | |
| 1796 | − const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); | |
| 1797 | − const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null; | |
| 1798 | − // Snooze outranks everything, including a pin: "hide until Tuesday" | |
| 1799 | − // temporarily suspends "keep on top". The pin survives underneath — | |
| 1800 | − // and so does its pinOrderKey, so on wake the thread reappears at | |
| 1801 | − // its exact slot in the pinned block. (For unpinned threads | |
| 1802 | − // this is also the snooze-beats-auto-settle rule: the wake time is a | |
| 1803 | − // stronger statement about when the thread matters again.) | |
| 1804 | − if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) { | |
| 1805 | − snoozed.push(thread); | |
| 1806 | − // A pin otherwise overrides the lifecycle: pinned threads never | |
| 1807 | − // auto-settle out of sight. (The decider clears settled state on | |
| 1808 | − // pin and the pin on settle, so pin-vs-settled conflicts only | |
| 1809 | − // arise from stale or raced writes.) | |
| 1810 | − } else if (thread.pinnedAt != null) { | |
| 1811 | − pinned.push(thread); | |
| 1812 | − } else if ( | |
| 1813 | − supportsSettlement && | |
| 1814 | − effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState }) | |
| 1815 | − ) { | |
| 1816 | − settled.push(thread); | |
| 1817 | − } else { | |
| 1818 | − active.push(thread); | |
| 1819 | − } | |
| 1820 | − } | |
| 1821 | − // One shared rule on every platform (see sortPinnedThreadsByOrderKey): | |
| 1822 | − // user-arranged keys first, keyless threads in creation order below. | |
| 1823 | − // Server capability only gates DRAGGING — it must not influence the | |
| 1824 | − // sort, or mixed-version fleets would render different pinned orders on | |
| 1825 | − // web and mobile from the same data. | |
| 1826 | − return { | |
| 1827 | − pinnedThreads: sortPinnedThreadsForSidebarV2(pinned), | |
| 1828 | − reorderablePinnedKeys: new Set( | |
| 1829 | − pinned | |
| 1830 | − .filter( | |
| 1831 | − (thread) => | |
| 1832 | − serverConfigs.get(thread.environmentId)?.environment.capabilities.threadPinReorder === | |
| 1833 | − true, | |
| 1834 | − ) | |
| 1835 | − .map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 1836 | − ), | |
| 1837 | − activeThreads: sortThreadsForSidebarV2(active), | |
| 1838 | − // Soonest wake first: "what comes back next" is the shelf's question. | |
| 1839 | − snoozedThreads: snoozed.toSorted( | |
| 1840 | − (left, right) => | |
| 1841 | − firstValidTimestampMs(left.snoozedUntil ?? null) - | |
| 1842 | − firstValidTimestampMs(right.snoozedUntil ?? null), | |
| 1843 | − ), | |
| 1844 | − settledThreads: sortSettledThreadsForSidebarV2(settled), | |
| 1845 | − snoozeNow: preciseNow, | |
| 1846 | − }; | |
| 1847 | − }, [ | |
| 1848 | − autoSettleAfterDays, | |
| 1849 | − changeRequestStateByKey, | |
| 1850 | − nowMinute, | |
| 1851 | − scopedProjectKeys, | |
| 1852 | − serverConfigs, | |
| 1853 | − snoozeWakeTick, | |
| 1854 | − threads, | |
| 1855 | − ]); | |
| 1856 | − | |
| 1857 | − const threadSearchInputRef = useRef<HTMLInputElement>(null); | |
| 1858 | − const [threadSearchQuery, setThreadSearchQuery] = useState(""); | |
| 1859 | − const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0); | |
| 1860 | − const isSearchingThreads = threadSearchQuery.trim().length > 0; | |
| 1861 | − const searchableThreads = useMemo( | |
| 1862 | − () => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads], | |
| 1863 | − [activeThreads, pinnedThreads, settledThreads, snoozedThreads], | |
| 1864 | − ); | |
| 1865 | − const threadSearchResults = useMemo( | |
| 1866 | − () => searchSidebarThreadsByTitle(searchableThreads, threadSearchQuery), | |
| 1867 | − [searchableThreads, threadSearchQuery], | |
| 1868 | − ); | |
| 1869 | − const threadSearchResultOrderKey = threadSearchResults | |
| 1870 | − .map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))) | |
| 1871 | − .join("\0"); | |
| 1872 | − | |
| 1873 | − useEffect(() => { | |
| 1874 | − setActiveSearchResultIndex(0); | |
| 1875 | − }, [threadSearchResultOrderKey]); | |
| 1876 | − | |
| 1877 | − useEffect(() => { | |
| 1878 | − if (!isSearchingThreads) return; | |
| 1879 | − document | |
| 1880 | − .getElementById(`sidebar-thread-search-result-${activeSearchResultIndex}`) | |
| 1881 | − ?.scrollIntoView({ block: "nearest" }); | |
| 1882 | − }, [activeSearchResultIndex, isSearchingThreads, threadSearchResultOrderKey]); | |
| 1883 | − | |
| 1884 | − // Arm a timeout for the earliest upcoming wake so the shelf empties the | |
| 1885 | − // moment a snooze expires instead of on the next minute tick. Sorted | |
| 1886 | − // soonest-first, so entry 0 is the boundary. | |
| 1887 | − useEffect(() => { | |
| 1888 | − const nextWakeAtMs = | |
| 1889 | − snoozedThreads.length > 0 && snoozedThreads[0]?.snoozedUntil != null | |
| 1890 | − ? Date.parse(snoozedThreads[0].snoozedUntil) | |
| 1891 | − : Number.NaN; | |
| 1892 | − if (Number.isNaN(nextWakeAtMs)) return; | |
| 1893 | − // setTimeout delays are signed 32-bit: anything larger overflows and | |
| 1894 | − // fires immediately, turning a far-future wake (event-condition snoozes | |
| 1895 | − // synced from elsewhere) into a tight re-arm loop. Clamped, the timer | |
| 1896 | − // just re-arms every ~24.8 days until the wake is in range. | |
| 1897 | − const delayMs = Math.min(Math.max(0, nextWakeAtMs - Date.now()) + 50, 2_147_483_647); | |
| 1898 | − const id = window.setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs); | |
| 1899 | − return () => window.clearTimeout(id); | |
| 1900 | − }, [snoozedThreads]); | |
| 1901 | − | |
| 1902 | − // The settled tail renders in pages: history shouldn't dominate the | |
| 1903 | − // sidebar, and the common lookups are recent. Expansion resets when the | |
| 1904 | − // filter context changes so a scope/search flip never inherits a deep | |
| 1905 | − // page state. | |
| 1906 | − const [settledVisibleCount, setSettledVisibleCount] = useState(SETTLED_TAIL_INITIAL_COUNT); | |
| 1907 | − const settledResetKey = projectScopeKey ?? "all"; | |
| 1908 | − const lastSettledResetKeyRef = useRef(settledResetKey); | |
| 1909 | − if (lastSettledResetKeyRef.current !== settledResetKey) { | |
| 1910 | − lastSettledResetKeyRef.current = settledResetKey; | |
| 1911 | − setSettledVisibleCount(SETTLED_TAIL_INITIAL_COUNT); | |
| 1912 | − } | |
| 1913 | − const visibleSettledThreads = useMemo(() => { | |
| 1914 | − if (settledThreads.length <= settledVisibleCount) return settledThreads; | |
| 1915 | − const visible = settledThreads.slice(0, settledVisibleCount); | |
| 1916 | − // The open thread must never hide under "Show more": navigating into a | |
| 1917 | − // deep settled thread (search, deep link) pulls its row into the visible | |
| 1918 | − // tail so the highlight and the un-settle affordance stay reachable. | |
| 1919 | − if (routeThreadKey !== null) { | |
| 1920 | − const routeThread = settledThreads | |
| 1921 | − .slice(settledVisibleCount) | |
| 1922 | − .find( | |
| 1923 | − (thread) => | |
| 1924 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, | |
| 1925 | − ); | |
| 1926 | − if (routeThread !== undefined) visible.push(routeThread); | |
| 1927 | − } | |
| 1928 | − return visible; | |
| 1929 | − }, [routeThreadKey, settledThreads, settledVisibleCount]); | |
| 1930 | − const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length; | |
| 1931 | − const showMoreSettled = useCallback( | |
| 1932 | − () => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT), | |
| 1933 | − [], | |
| 1934 | − ); | |
| 1935 | − const [settledShelfExpanded, setSettledShelfExpanded] = useState(true); | |
| 1936 | − const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []); | |
| 1937 | − const renderedSettledThreads = useMemo(() => { | |
| 1938 | − if (settledShelfExpanded) return visibleSettledThreads; | |
| 1939 | − if (routeThreadKey === null) return []; | |
| 1940 | − const routeThread = visibleSettledThreads.find( | |
| 1941 | − (thread) => | |
| 1942 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, | |
| 1943 | − ); | |
| 1944 | − return routeThread === undefined ? [] : [routeThread]; | |
| 1945 | − }, [routeThreadKey, settledShelfExpanded, visibleSettledThreads]); | |
| 1946 | − | |
| 1947 | − // The snoozed shelf is collapsed by default: out of the way, never gone. | |
| 1948 | − // Collapsed threads don't render (and so don't participate in jump | |
| 1949 | − // shortcuts or multi-select), matching the settled tail's paging model. | |
| 1950 | − const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false); | |
| 1951 | − const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []); | |
| 1952 | − const visibleSnoozedThreads = useMemo(() => { | |
| 1953 | − if (snoozedShelfExpanded) return snoozedThreads; | |
| 1954 | − // The open thread must never vanish behind the collapsed shelf: a | |
| 1955 | − // snoozed thread reached by route (deep link, open before snoozing | |
| 1956 | − // elsewhere) keeps its row — with highlight and wake affordance — same | |
| 1957 | − // exception the settled tail's "Show more" makes. | |
| 1958 | − if (routeThreadKey === null) return []; | |
| 1959 | − const routeThread = snoozedThreads.find( | |
| 1960 | − (thread) => | |
| 1961 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, | |
| 1962 | − ); | |
| 1963 | − return routeThread === undefined ? [] : [routeThread]; | |
| 1964 | − }, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]); | |
| 1965 | − | |
| 1966 | − const orderedThreads = useMemo( | |
| 1967 | − () => [...pinnedThreads, ...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads], | |
| 1968 | − [pinnedThreads, activeThreads, visibleSnoozedThreads, renderedSettledThreads], | |
| 1969 | − ); | |
| 1970 | − const orderedThreadKeys = useMemo( | |
| 1971 | − () => | |
| 1972 | − orderedThreads.map((thread) => | |
| 1973 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 1974 | − ), | |
| 1975 | − [orderedThreads], | |
| 1976 | − ); | |
| 1977 | − // Rows call back into the click handler without carrying the ordered list as | |
| 1978 | − // a prop — a fresh array identity per shell update would defeat every row's | |
| 1979 | − // memoization. The ref keeps shift-range-select working against the list as | |
| 1980 | − // rendered at click time. | |
| 1981 | − const orderedThreadKeysRef = useRef(orderedThreadKeys); | |
| 1982 | − orderedThreadKeysRef.current = orderedThreadKeys; | |
| 1983 | − const threadByKey = useMemo( | |
| 1984 | − () => | |
| 1985 | − new Map( | |
| 1986 | − orderedThreads.map( | |
| 1987 | − (thread) => | |
| 1988 | − [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, | |
| 1989 | − ), | |
| 1990 | − ), | |
| 1991 | − [orderedThreads], | |
| 1992 | − ); | |
| 1993 | − // Handlers read these through refs: depending on per-update Map/Set | |
| 1994 | − // identities would give every row a fresh callback prop on each shell | |
| 1995 | − // event and defeat row memoization during streaming. | |
| 1996 | − const threadByKeyRef = useRef(threadByKey); | |
| 1997 | − threadByKeyRef.current = threadByKey; | |
| 1998 | − // handleNewThread is inherently unstable (depends on the projects list); | |
| 1999 | − // a ref keeps it out of attemptSettle's dependency array. | |
| 2000 | − const handleNewThreadRef = useRef(newThreadContext.handleNewThread); | |
| 2001 | − handleNewThreadRef.current = newThreadContext.handleNewThread; | |
| 2002 | − const settledThreadKeys = useMemo( | |
| 2003 | − () => | |
| 2004 | − new Set( | |
| 2005 | − settledThreads.map((thread) => | |
| 2006 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2007 | − ), | |
| 2008 | − ), | |
| 2009 | − [settledThreads], | |
| 2010 | − ); | |
| 2011 | − const settledThreadKeysRef = useRef(settledThreadKeys); | |
| 2012 | − settledThreadKeysRef.current = settledThreadKeys; | |
| 2013 | − const snoozedThreadKeys = useMemo( | |
| 2014 | − () => | |
| 2015 | − new Set( | |
| 2016 | − snoozedThreads.map((thread) => | |
| 2017 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2018 | − ), | |
| 2019 | − ), | |
| 2020 | − [snoozedThreads], | |
| 2021 | − ); | |
| 2022 | − const snoozedThreadKeysRef = useRef(snoozedThreadKeys); | |
| 2023 | − snoozedThreadKeysRef.current = snoozedThreadKeys; | |
| 2024 | − | |
| 2025 | − const jumpLabelByKey = useMemo(() => { | |
| 2026 | − const mapping = new Map<string, string>(); | |
| 2027 | − for (const [index, threadKey] of orderedThreadKeys.entries()) { | |
| 2028 | − const jumpCommand = threadJumpCommandForIndex(index); | |
| 2029 | − if (!jumpCommand) break; | |
| 2030 | − const label = shortcutLabelForCommand(keybindings, jumpCommand); | |
| 2031 | − if (label) mapping.set(threadKey, label); | |
| 2032 | − } | |
| 2033 | − return mapping; | |
| 2034 | − }, [keybindings, orderedThreadKeys]); | |
| 2035 | − const [showJumpHints, setShowJumpHints] = useState(false); | |
| 2036 | − | |
| 2037 | − // Settled threads are live shells, so opening one is plain navigation: | |
| 2038 | − // history stays readable without un-settling, and sending a message or | |
| 2039 | − // starting a session un-settles server-side. | |
| 2040 | − const navigateToThread = useCallback( | |
| 2041 | − (threadRef: ScopedThreadRef) => { | |
| 2042 | − if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { | |
| 2043 | − clearSelection(); | |
| 2044 | − } | |
| 2045 | − setSelectionAnchor(scopedThreadKey(threadRef)); | |
| 2046 | − if (isMobile) { | |
| 2047 | − setOpenMobile(false); | |
| 2048 | − } | |
| 2049 | − void router.navigate({ | |
| 2050 | − to: "/$environmentId/$threadId", | |
| 2051 | − params: buildThreadRouteParams(threadRef), | |
| 2052 | − }); | |
| 2053 | − }, | |
| 2054 | − [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor], | |
| 2055 | − ); | |
| 2056 | − | |
| 2057 | − const clearThreadSearch = useCallback(() => { | |
| 2058 | − setThreadSearchQuery(""); | |
| 2059 | − setActiveSearchResultIndex(0); | |
| 2060 | − }, []); | |
| 2061 | − const selectThreadSearchResult = useCallback( | |
| 2062 | − (thread: EnvironmentThreadShell) => { | |
| 2063 | − clearThreadSearch(); | |
| 2064 | − navigateToThread(scopeThreadRef(thread.environmentId, thread.id)); | |
| 2065 | − }, | |
| 2066 | − [clearThreadSearch, navigateToThread], | |
| 2067 | − ); | |
| 2068 | − const handleThreadSearchKeyDown = useCallback( | |
| 2069 | − (event: ReactKeyboardEvent<HTMLInputElement>) => { | |
| 2070 | − // IME composition (Japanese/Chinese input) uses the same keys; committing | |
| 2071 | − // a candidate must not move the highlight or navigate away mid-compose. | |
| 2072 | − if (event.nativeEvent.isComposing || event.keyCode === 229) return; | |
| 2073 | − if (event.key === "Escape" && isSearchingThreads) { | |
| 2074 | − event.preventDefault(); | |
| 2075 | − event.stopPropagation(); | |
| 2076 | − clearThreadSearch(); | |
| 2077 | − return; | |
| 2078 | − } | |
| 2079 | − if (threadSearchResults.length === 0) return; | |
| 2080 | − if (event.key === "ArrowDown") { | |
| 2081 | − event.preventDefault(); | |
| 2082 | − setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length); | |
| 2083 | − return; | |
| 2084 | − } | |
| 2085 | − if (event.key === "ArrowUp") { | |
| 2086 | − event.preventDefault(); | |
| 2087 | − setActiveSearchResultIndex( | |
| 2088 | − (index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length, | |
| 2089 | − ); | |
| 2090 | − return; | |
| 2091 | − } | |
| 2092 | − if (event.key === "Enter") { | |
| 2093 | − event.preventDefault(); | |
| 2094 | − const result = threadSearchResults[activeSearchResultIndex]; | |
| 2095 | − if (result) selectThreadSearchResult(result); | |
| 2096 | − } | |
| 2097 | − }, | |
| 2098 | − [ | |
| 2099 | − activeSearchResultIndex, | |
| 2100 | − clearThreadSearch, | |
| 2101 | − isSearchingThreads, | |
| 2102 | − selectThreadSearchResult, | |
| 2103 | − threadSearchResults, | |
| 2104 | − ], | |
| 2105 | − ); | |
| 2106 | − | |
| 2107 | − const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null); | |
| 2108 | − const [renamingTitle, setRenamingTitle] = useState(""); | |
| 2109 | − const startThreadRename = useCallback((threadRef: ScopedThreadRef, title: string) => { | |
| 2110 | − setRenamingThreadKey(scopedThreadKey(threadRef)); | |
| 2111 | − setRenamingTitle(title); | |
| 2112 | − }, []); | |
| 2113 | − const cancelThreadRename = useCallback(() => setRenamingThreadKey(null), []); | |
| 2114 | − const commitThreadRename = useCallback( | |
| 2115 | − (threadRef: ScopedThreadRef, title: string, originalTitle: string) => { | |
| 2116 | − void (async () => { | |
| 2117 | − const trimmed = title.trim(); | |
| 2118 | − setRenamingThreadKey(null); | |
| 2119 | − if (trimmed.length === 0) { | |
| 2120 | − toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); | |
| 2121 | − return; | |
| 2122 | − } | |
| 2123 | − if (trimmed === originalTitle) return; | |
| 2124 | − const result = await updateThreadMetadata({ | |
| 2125 | − environmentId: threadRef.environmentId, | |
| 2126 | − input: { threadId: threadRef.threadId, title: trimmed }, | |
| 2127 | − }); | |
| 2128 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2129 | − const error = squashAtomCommandFailure(result); | |
| 2130 | − toastManager.add( | |
| 2131 | − stackedThreadToast({ | |
| 2132 | − type: "error", | |
| 2133 | − title: "Failed to rename thread", | |
| 2134 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2135 | − }), | |
| 2136 | − ); | |
| 2137 | − } | |
| 2138 | − })(); | |
| 2139 | − }, | |
| 2140 | − [updateThreadMetadata], | |
| 2141 | − ); | |
| 2142 | − | |
| 2143 | − const handleThreadClick = useCallback( | |
| 2144 | − (event: ReactMouseEvent, threadRef: ScopedThreadRef) => { | |
| 2145 | − const isMac = isMacPlatform(navigator.platform); | |
| 2146 | − const isModClick = isMac ? event.metaKey : event.ctrlKey; | |
| 2147 | − const threadKey = scopedThreadKey(threadRef); | |
| 2148 | − if (isModClick) { | |
| 2149 | − event.preventDefault(); | |
| 2150 | − toggleThreadSelection(threadKey); | |
| 2151 | − return; | |
| 2152 | − } | |
| 2153 | − if (event.shiftKey) { | |
| 2154 | − event.preventDefault(); | |
| 2155 | − rangeSelectTo(threadKey, orderedThreadKeysRef.current); | |
| 2156 | − return; | |
| 2157 | − } | |
| 2158 | − if (isTrailingDoubleClick(event.detail)) { | |
| 2159 | − return; | |
| 2160 | − } | |
| 2161 | − navigateToThread(threadRef); | |
| 2162 | − }, | |
| 2163 | − [navigateToThread, rangeSelectTo, toggleThreadSelection], | |
| 2164 | − ); | |
| 2165 | − | |
| 2166 | − // A settle per thread at a time: double clicks and repeated menu picks | |
| 2167 | − // must not dispatch a second settle that fails and toasts a false error. | |
| 2168 | − const settlingThreadKeysRef = useRef(new Set<string>()); | |
| 2169 | − // Parking the thread you're looking at (settle or snooze) moves you | |
| 2170 | − // forward: the next remaining card (never a settled or snoozed row, never | |
| 2171 | − // one leaving in the same batch), or a fresh draft in this project when it | |
| 2172 | − // was the last active one. Callers snapshot the plan BEFORE the command | |
| 2173 | − // mutates the partition; background parks never navigate (null plan). | |
| 2174 | − const planForwardNavigation = useCallback( | |
| 2175 | − (threadKey: string, coParkingKeys?: ReadonlySet<string>): (() => void) | null => { | |
| 2176 | − if (routeThreadKeyRef.current !== threadKey) return null; | |
| 2177 | − const shell = threadByKeyRef.current.get(threadKey); | |
| 2178 | − const orderedKeys = orderedThreadKeysRef.current; | |
| 2179 | − const settledKeys = settledThreadKeysRef.current; | |
| 2180 | − const snoozedKeys = snoozedThreadKeysRef.current; | |
| 2181 | − const currentIndex = orderedKeys.indexOf(threadKey); | |
| 2182 | − const nextCardKey = | |
| 2183 | − currentIndex === -1 | |
| 2184 | − ? null | |
| 2185 | − : ([...orderedKeys.slice(currentIndex + 1), ...orderedKeys.slice(0, currentIndex)].find( | |
| 2186 | − (key) => !settledKeys.has(key) && !snoozedKeys.has(key) && !coParkingKeys?.has(key), | |
| 2187 | − ) ?? null); | |
| 2188 | − const nextThread = nextCardKey ? threadByKeyRef.current.get(nextCardKey) : null; | |
| 2189 | − return nextThread | |
| 2190 | − ? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id)) | |
| 2191 | − : shell | |
| 2192 | − ? () => | |
| 2193 | − void handleNewThreadRef.current(scopeProjectRef(shell.environmentId, shell.projectId)) | |
| 2194 | − : () => void router.navigate({ to: "/" }); | |
| 2195 | − }, | |
| 2196 | − [navigateToThread, router], | |
| 2197 | − ); | |
| 2198 | − | |
| 2199 | − const attemptSettle = useCallback( | |
| 2200 | − (threadRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet<string> } = {}) => { | |
| 2201 | − void (async () => { | |
| 2202 | − const threadKey = scopedThreadKey(threadRef); | |
| 2203 | − if (settlingThreadKeysRef.current.has(threadKey)) return; | |
| 2204 | − settlingThreadKeysRef.current.add(threadKey); | |
| 2205 | − try { | |
| 2206 | − const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); | |
| 2207 | − const result = await settleThread(threadRef); | |
| 2208 | − if (result._tag === "Failure") { | |
| 2209 | − // Never navigate away from a thread that did not settle. | |
| 2210 | − if (!isAtomCommandInterrupted(result)) { | |
| 2211 | − const error = squashAtomCommandFailure(result); | |
| 2212 | − toastManager.add( | |
| 2213 | − stackedThreadToast({ | |
| 2214 | − type: "error", | |
| 2215 | − title: "Failed to settle thread", | |
| 2216 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2217 | − }), | |
| 2218 | − ); | |
| 2219 | − } | |
| 2220 | − return; | |
| 2221 | − } | |
| 2222 | − // Only move forward if the user is still on the settled thread — | |
| 2223 | − // a navigation made during the await wins over ours. | |
| 2224 | − if (routeThreadKeyRef.current === threadKey) { | |
| 2225 | − navigateAfterSettle?.(); | |
| 2226 | − } | |
| 2227 | − } finally { | |
| 2228 | − settlingThreadKeysRef.current.delete(threadKey); | |
| 2229 | − } | |
| 2230 | − })(); | |
| 2231 | − }, | |
| 2232 | − [planForwardNavigation, settleThread], | |
| 2233 | − ); | |
| 2234 | − const attemptUnsettle = useCallback( | |
| 2235 | − (threadRef: ScopedThreadRef) => { | |
| 2236 | − void (async () => { | |
| 2237 | − const result = await unsettleThread(threadRef); | |
| 2238 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2239 | − const error = squashAtomCommandFailure(result); | |
| 2240 | − toastManager.add( | |
| 2241 | − stackedThreadToast({ | |
| 2242 | − type: "error", | |
| 2243 | − title: "Failed to un-settle thread", | |
| 2244 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2245 | − }), | |
| 2246 | − ); | |
| 2247 | − } | |
| 2248 | − })(); | |
| 2249 | − }, | |
| 2250 | − [unsettleThread], | |
| 2251 | − ); | |
| 2252 | − const attemptUnsnooze = useCallback( | |
| 2253 | − (threadRef: ScopedThreadRef) => { | |
| 2254 | − void (async () => { | |
| 2255 | − const result = await unsnoozeThread(threadRef); | |
| 2256 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2257 | − const error = squashAtomCommandFailure(result); | |
| 2258 | − toastManager.add( | |
| 2259 | − stackedThreadToast({ | |
| 2260 | − type: "error", | |
| 2261 | − title: "Failed to wake thread", | |
| 2262 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2263 | − }), | |
| 2264 | − ); | |
| 2265 | − } | |
| 2266 | − })(); | |
| 2267 | − }, | |
| 2268 | − [unsnoozeThread], | |
| 2269 | − ); | |
| 2270 | − // Drag-to-reorder for the pinned block. A drop computes ONE fractional key | |
| 2271 | − // for the moved thread and sends it to that thread's own server (see | |
| 2272 | − // planPinnedReorder for the keyless-neighbor materialization case). The | |
| 2273 | − // optimistic order keeps the card where it was dropped until the | |
| 2274 | − // confirming event round-trips; canonical order matching it releases the | |
| 2275 | − // override, and a failed write clears it (the card snaps back) with a toast. | |
| 2276 | − // ANY membership change (new pin, unpin, snooze/wake) also releases it: | |
| 2277 | − // the override can't say where members it never saw belong, and holding it | |
| 2278 | − // would misplace them and launder the stale order into later drags. | |
| 2279 | − const pinnedDndSensors = useSensors( | |
| 2280 | − useSensor(PointerSensor, { activationConstraint: { distance: 6 } }), | |
| 2281 | − ); | |
| 2282 | − const [optimisticPinnedOrder, setOptimisticPinnedOrder] = useState<{ | |
| 2283 | − readonly order: readonly string[]; | |
| 2284 | − /** pinOrderKey per thread as of the drop, so ANY landed write (ours | |
| 2285 | − confirming, or a concurrent one from another client) releases the | |
| 2286 | − override rather than fighting canonical state. */ | |
| 2287 | − readonly keysAtDrop: ReadonlyMap<string, string | null>; | |
| 2288 | − } | null>(null); | |
| 2289 | − const orderedPinnedThreads = useMemo(() => { | |
| 2290 | − if (optimisticPinnedOrder === null) return pinnedThreads; | |
| 2291 | − return orderItemsByPreferredIds({ | |
| 2292 | − items: pinnedThreads, | |
| 2293 | − preferredIds: optimisticPinnedOrder.order, | |
| 2294 | − getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2295 | − }); | |
| 2296 | − }, [optimisticPinnedOrder, pinnedThreads]); | |
| 2297 | − useEffect(() => { | |
| 2298 | − if (optimisticPinnedOrder === null) return; | |
| 2299 | − const canonical = pinnedThreads.filter((thread) => | |
| 2300 | − reorderablePinnedKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 2301 | − ); | |
| 2302 | − const canonicalKeys = canonical.map((thread) => | |
| 2303 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2304 | − ); | |
| 2305 | − // The override represents one drop against one snapshot of the world. | |
| 2306 | − // Release it as soon as the world moves on in any way: membership | |
| 2307 | − // changed (pin/unpin/snooze/wake — the override can't say where members | |
| 2308 | − // it never saw belong), a key changed (our write confirming, or a | |
| 2309 | − // concurrent client's reorder that must win), or canonical already | |
| 2310 | − // matches. Holding it longer would misplace newcomers and launder the | |
| 2311 | − // stale order into later drags. | |
| 2312 | − const membershipChanged = | |
| 2313 | − canonicalKeys.length !== optimisticPinnedOrder.order.length || | |
| 2314 | − canonicalKeys.some((key) => !optimisticPinnedOrder.order.includes(key)); | |
| 2315 | − const anyKeyLanded = canonical.some( | |
| 2316 | − (thread, index) => | |
| 2317 | − optimisticPinnedOrder.keysAtDrop.get(canonicalKeys[index]!) !== | |
| 2318 | − (thread.pinOrderKey ?? null), | |
| 2319 | − ); | |
| 2320 | − const orderConfirmed = | |
| 2321 | − !membershipChanged && | |
| 2322 | − canonicalKeys.every((key, index) => key === optimisticPinnedOrder.order[index]); | |
| 2323 | − if (membershipChanged || anyKeyLanded || orderConfirmed) { | |
| 2324 | − setOptimisticPinnedOrder(null); | |
| 2325 | − } | |
| 2326 | − }, [optimisticPinnedOrder, pinnedThreads, reorderablePinnedKeys]); | |
| 2327 | − const attemptPin = useCallback( | |
| 2328 | − (threadRef: ScopedThreadRef) => { | |
| 2329 | − void (async () => { | |
| 2330 | − // Fresh pins take the top of the arranged run: pinThread computes a | |
| 2331 | − // key before the smallest key across ALL pinned shells — including | |
| 2332 | − // snoozed pins hidden from this list, whose keys are still part of | |
| 2333 | − // the run — so the new pin can't land beneath a hidden head. | |
| 2334 | − const result = await pinThread(threadRef); | |
| 2335 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2336 | − const error = squashAtomCommandFailure(result); | |
| 2337 | − toastManager.add( | |
| 2338 | − stackedThreadToast({ | |
| 2339 | − type: "error", | |
| 2340 | − title: "Failed to pin thread", | |
| 2341 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2342 | − }), | |
| 2343 | − ); | |
| 2344 | − } | |
| 2345 | − })(); | |
| 2346 | − }, | |
| 2347 | − [pinThread], | |
| 2348 | − ); | |
| 2349 | − const attemptUnpin = useCallback( | |
| 2350 | − (threadRef: ScopedThreadRef) => { | |
| 2351 | − void (async () => { | |
| 2352 | − const result = await unpinThread(threadRef); | |
| 2353 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2354 | − const error = squashAtomCommandFailure(result); | |
| 2355 | − toastManager.add( | |
| 2356 | − stackedThreadToast({ | |
| 2357 | − type: "error", | |
| 2358 | − title: "Failed to unpin thread", | |
| 2359 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2360 | − }), | |
| 2361 | − ); | |
| 2362 | − } | |
| 2363 | − })(); | |
| 2364 | − }, | |
| 2365 | − [unpinThread], | |
| 2366 | − ); | |
| 2367 | − | |
| 2368 | − const handlePinnedDragEnd = useCallback( | |
| 2369 | − (event: DragEndEvent) => { | |
| 2370 | − const activeKey = String(event.active.id); | |
| 2371 | − const overKey = event.over === null ? null : String(event.over.id); | |
| 2372 | − if (overKey === null || activeKey === overKey) return; | |
| 2373 | − const reorderable = orderedPinnedThreads.filter((thread) => | |
| 2374 | − reorderablePinnedKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), | |
| 2375 | − ); | |
| 2376 | − const keys = reorderable.map((thread) => | |
| 2377 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 2378 | − ); | |
| 2379 | − const fromIndex = keys.indexOf(activeKey); | |
| 2380 | − const toIndex = keys.indexOf(overKey); | |
| 2381 | − if (fromIndex === -1 || toIndex === -1) return; | |
| 2382 | − const newOrder = arrayMove([...keys], fromIndex, toIndex); | |
| 2383 | − const threadByKey = new Map(reorderable.map((thread, index) => [keys[index]!, thread])); | |
| 2384 | − const keysAtDrop = new Map( | |
| 2385 | − reorderable.map((thread, index) => [keys[index]!, thread.pinOrderKey ?? null]), | |
| 2386 | − ); | |
| 2387 | − const assignments = planPinnedReorder({ | |
| 2388 | − orderedIds: newOrder, | |
| 2389 | − keysById: keysAtDrop, | |
| 2390 | − movedId: activeKey, | |
| 2391 | − }); | |
| 2392 | − if (assignments.length === 0) return; | |
| 2393 | − setOptimisticPinnedOrder({ order: newOrder, keysAtDrop }); | |
| 2394 | − void (async () => { | |
| 2395 | − // Sequential, stop on first failure. There is deliberately no | |
| 2396 | − // rollback: every key write is a complete, valid placement on its | |
| 2397 | − // own, so a partial materialization leaves a sensible order (and | |
| 2398 | − // the next drag repairs the rest) — unwinding writes across | |
| 2399 | − // servers would trade that for real inconsistency windows. | |
| 2400 | − for (const assignment of assignments) { | |
| 2401 | − const thread = threadByKey.get(assignment.id); | |
| 2402 | − if (thread === undefined) continue; | |
| 2403 | − const result = await reorderPinnedThread( | |
| 2404 | − scopeThreadRef(thread.environmentId, thread.id), | |
| 2405 | − assignment.orderKey, | |
| 2406 | − ); | |
| 2407 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2408 | − setOptimisticPinnedOrder(null); | |
| 2409 | − const error = squashAtomCommandFailure(result); | |
| 2410 | − toastManager.add( | |
| 2411 | − stackedThreadToast({ | |
| 2412 | − type: "error", | |
| 2413 | − title: "Failed to reorder pinned threads", | |
| 2414 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2415 | − }), | |
| 2416 | − ); | |
| 2417 | − return; | |
| 2418 | − } | |
| 2419 | − } | |
| 2420 | − })(); | |
| 2421 | − }, | |
| 2422 | − [orderedPinnedThreads, reorderPinnedThread, reorderablePinnedKeys], | |
| 2423 | − ); | |
| 2424 | − // One snooze per thread at a time — same double-dispatch guard as settle. | |
| 2425 | − const snoozingThreadKeysRef = useRef(new Set<string>()); | |
| 2426 | − const performSnooze = useCallback( | |
| 2427 | − async ( | |
| 2428 | − threadRef: ScopedThreadRef, | |
| 2429 | − preset: SnoozePreset, | |
| 2430 | − opts: { coSnoozingKeys?: ReadonlySet<string> } = {}, | |
| 2431 | − ) => { | |
| 2432 | − const threadKey = scopedThreadKey(threadRef); | |
| 2433 | − if (snoozingThreadKeysRef.current.has(threadKey)) { | |
| 2434 | − return { status: "skipped" } as const; | |
| 2435 | − } | |
| 2436 | − snoozingThreadKeysRef.current.add(threadKey); | |
| 2437 | − try { | |
| 2438 | − // Snoozing the open thread moves you forward, same as settle — | |
| 2439 | − // both park the thread you're done with for now. | |
| 2440 | − const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys); | |
| 2441 | − const result = await snoozeThread(threadRef, preset.snoozedUntil); | |
| 2442 | − if (result._tag === "Failure") { | |
| 2443 | − // Never navigate away from a thread that did not snooze. | |
| 2444 | − return isAtomCommandInterrupted(result) | |
| 2445 | − ? ({ status: "interrupted" } as const) | |
| 2446 | − : ({ status: "failure", error: squashAtomCommandFailure(result) } as const); | |
| 2447 | − } | |
| 2448 | − // Only move forward if the user is still on the snoozed thread — | |
| 2449 | − // a navigation made during the await wins over ours. | |
| 2450 | − if (routeThreadKeyRef.current === threadKey) { | |
| 2451 | − navigateAfterSnooze?.(); | |
| 2452 | − } | |
| 2453 | − return { status: "success" } as const; | |
| 2454 | − } finally { | |
| 2455 | − snoozingThreadKeysRef.current.delete(threadKey); | |
| 2456 | − } | |
| 2457 | − }, | |
| 2458 | − [planForwardNavigation, snoozeThread], | |
| 2459 | − ); | |
| 2460 | − const attemptSnooze = useCallback( | |
| 2461 | − ( | |
| 2462 | − threadRef: ScopedThreadRef, | |
| 2463 | − preset: SnoozePreset, | |
| 2464 | − opts: { coSnoozingKeys?: ReadonlySet<string> } = {}, | |
| 2465 | − ) => { | |
| 2466 | − void (async () => { | |
| 2467 | − const outcome = await performSnooze(threadRef, preset, opts); | |
| 2468 | − if (outcome.status === "failure") { | |
| 2469 | − toastManager.add( | |
| 2470 | − stackedThreadToast({ | |
| 2471 | − type: "error", | |
| 2472 | − title: "Failed to snooze thread", | |
| 2473 | − description: | |
| 2474 | − outcome.error instanceof Error ? outcome.error.message : "An error occurred.", | |
| 2475 | − }), | |
| 2476 | − ); | |
| 2477 | − return; | |
| 2478 | − } | |
| 2479 | − if (outcome.status !== "success") return; | |
| 2480 | − // Snooze hides the row, so the toast is the only confirmation — | |
| 2481 | − // and the Undo is the escape hatch for a mis-click. | |
| 2482 | − toastManager.add( | |
| 2483 | − stackedThreadToast({ | |
| 2484 | − type: "success", | |
| 2485 | − title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`, | |
| 2486 | − timeout: 5_000, | |
| 2487 | − actionProps: { | |
| 2488 | − children: "Undo", | |
| 2489 | − onClick: () => attemptUnsnooze(threadRef), | |
| 2490 | − }, | |
| 2491 | − }), | |
| 2492 | − ); | |
| 2493 | − })(); | |
| 2494 | − }, | |
| 2495 | − [attemptUnsnooze, performSnooze, timestampFormat], | |
| 2496 | − ); | |
| 2497 | − | |
| 2498 | − const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection); | |
| 2499 | − const handleMultiSelectContextMenu = useCallback( | |
| 2500 | − async (position: { x: number; y: number }) => { | |
| 2501 | − const api = readLocalApi(); | |
| 2502 | − if (!api) return; | |
| 2503 | − // One exact actionable set: keys whose rows are actually rendered | |
| 2504 | − // right now. Selections can outlive their rows (settled-tail paging, | |
| 2505 | − // thread deletion elsewhere) and the menu labels must count only what | |
| 2506 | − // the actions will touch. | |
| 2507 | − const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys].filter( | |
| 2508 | − (threadKey) => threadByKeyRef.current.has(threadKey), | |
| 2509 | − ); | |
| 2510 | − if (threadKeys.length === 0) return; | |
| 2511 | − const count = threadKeys.length; | |
| 2512 | − // Snooze (N) is offered when every selected thread can actually take | |
| 2513 | − // it — a mixed selection with blocked-on-you work would half-apply. | |
| 2514 | − const selectionNow = new Date(); | |
| 2515 | − const selectedThreads = threadKeys.flatMap((threadKey) => { | |
| 2516 | − const thread = threadByKeyRef.current.get(threadKey); | |
| 2517 | − return thread ? [thread] : []; | |
| 2518 | − }); | |
| 2519 | − const canSnoozeSelection = selectedThreads.every( | |
| 2520 | − (thread) => | |
| 2521 | − serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true && | |
| 2522 | − canSnooze(thread, { now: selectionNow.toISOString() }), | |
| 2523 | − ); | |
| 2524 | − const titleRegenerationThreads = selectedThreads.filter( | |
| 2525 | − (thread) => | |
| 2526 | − serverConfigs.get(thread.environmentId)?.environment.capabilities | |
| 2527 | − .threadTitleRegeneration === true, | |
| 2528 | − ); | |
| 2529 | − const regeneratableTitleThreads = titleRegenerationThreads.filter( | |
| 2530 | − (thread) => thread.titleRegeneration == null, | |
| 2531 | − ); | |
| 2532 | − const titleRegenerationMenuItem = buildBulkTitleRegenerationContextMenuItem({ | |
| 2533 | − supportedCount: titleRegenerationThreads.length, | |
| 2534 | − actionableCount: regeneratableTitleThreads.length, | |
| 2535 | − }); | |
| 2536 | − const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); | |
| 2537 | − const clicked = await settlePromise(() => | |
| 2538 | − api.contextMenu.show( | |
| 2539 | − [ | |
| 2540 | − { id: "settle", label: `Settle (${count})` }, | |
| 2541 | − ...(canSnoozeSelection | |
| 2542 | − ? [ | |
| 2543 | − { | |
| 2544 | − id: "snooze", | |
| 2545 | − label: `Snooze (${count})`, | |
| 2546 | − children: snoozePresets.map((preset) => ({ | |
| 2547 | − id: `snooze:${preset.id}`, | |
| 2548 | − label: `${preset.label} (${preset.whenLabel})`, | |
| 2549 | − })), | |
| 2550 | − }, | |
| 2551 | − ] | |
| 2552 | − : []), | |
| 2553 | − ...(titleRegenerationMenuItem ? [titleRegenerationMenuItem] : []), | |
| 2554 | − { id: "mark-unread", label: `Mark unread (${count})` }, | |
| 2555 | − { id: "delete", label: `Delete (${count})`, destructive: true }, | |
| 2556 | − ], | |
| 2557 | − position, | |
| 2558 | − ), | |
| 2559 | − ); | |
| 2560 | − if (clicked._tag === "Failure") return; | |
| 2561 | − if (clicked.value?.startsWith("snooze:")) { | |
| 2562 | − const preset = snoozePresets.find( | |
| 2563 | − (candidate) => `snooze:${candidate.id}` === clicked.value, | |
| 2564 | − ); | |
| 2565 | − if (preset) { | |
| 2566 | − // Post-snooze navigation must skip threads snoozing in this same | |
| 2567 | − // batch — they are all leaving the card block together. | |
| 2568 | − const coSnoozingKeys = new Set(threadKeys); | |
| 2569 | − clearSelection(); | |
| 2570 | − const outcomes = await Promise.all( | |
| 2571 | − selectedThreads.map(async (thread) => { | |
| 2572 | − const threadRef = scopeThreadRef(thread.environmentId, thread.id); | |
| 2573 | − const outcome = await performSnooze(threadRef, preset, { coSnoozingKeys }); | |
| 2574 | − return { outcome, threadRef }; | |
| 2575 | − }), | |
| 2576 | − ); | |
| 2577 | − const snoozedThreadRefs = outcomes.flatMap(({ outcome, threadRef }) => | |
| 2578 | − outcome.status === "success" ? [threadRef] : [], | |
| 2579 | − ); | |
| 2580 | − const failures = outcomes.flatMap(({ outcome }) => | |
| 2581 | − outcome.status === "failure" ? [outcome.error] : [], | |
| 2582 | − ); | |
| 2583 | − | |
| 2584 | − if (snoozedThreadRefs.length > 0) { | |
| 2585 | − const snoozedCount = snoozedThreadRefs.length; | |
| 2586 | − const failedCount = failures.length; | |
| 2587 | − toastManager.add( | |
| 2588 | − stackedThreadToast({ | |
| 2589 | − type: failedCount > 0 ? "warning" : "success", | |
| 2590 | − title: | |
| 2591 | − failedCount > 0 | |
| 2592 | − ? `Snoozed ${snoozedCount} of ${selectedThreads.length} threads` | |
| 2593 | − : `Snoozed ${snoozedCount} thread${snoozedCount === 1 ? "" : "s"}`, | |
| 2594 | − description: | |
| 2595 | − failedCount > 0 | |
| 2596 | − ? `${failedCount} thread${failedCount === 1 ? "" : "s"} couldn't be snoozed.` | |
| 2597 | − : undefined, | |
| 2598 | − timeout: 5_000, | |
| 2599 | − actionProps: { | |
| 2600 | − children: "Undo", | |
| 2601 | − onClick: () => { | |
| 2602 | − for (const threadRef of snoozedThreadRefs) attemptUnsnooze(threadRef); | |
| 2603 | − }, | |
| 2604 | − }, | |
| 2605 | − }), | |
| 2606 | − ); | |
| 2607 | − } else if (failures.length > 0) { | |
| 2608 | − const firstError = failures[0]; | |
| 2609 | − toastManager.add( | |
| 2610 | − stackedThreadToast({ | |
| 2611 | − type: "error", | |
| 2612 | − title: "Failed to snooze threads", | |
| 2613 | − description: | |
| 2614 | − firstError instanceof Error ? firstError.message : "An error occurred.", | |
| 2615 | − }), | |
| 2616 | − ); | |
| 2617 | − } | |
| 2618 | − } | |
| 2619 | − return; | |
| 2620 | − } | |
| 2621 | − if (clicked.value === "regenerate-title") { | |
| 2622 | − for (const thread of regeneratableTitleThreads) { | |
| 2623 | − const result = await updateThreadMetadata({ | |
| 2624 | − environmentId: thread.environmentId, | |
| 2625 | − input: { threadId: thread.id, regenerateTitle: true }, | |
| 2626 | − }); | |
| 2627 | − if (result._tag === "Success") continue; | |
| 2628 | − if (!isAtomCommandInterrupted(result)) { | |
| 2629 | − const error = squashAtomCommandFailure(result); | |
| 2630 | − toastManager.add( | |
| 2631 | − stackedThreadToast({ | |
| 2632 | − type: "error", | |
| 2633 | − title: "Failed to regenerate thread titles", | |
| 2634 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2635 | − }), | |
| 2636 | − ); | |
| 2637 | − } | |
| 2638 | − return; | |
| 2639 | − } | |
| 2640 | − clearSelection(); | |
| 2641 | − return; | |
| 2642 | − } | |
| 2643 | − if (clicked.value === "settle") { | |
| 2644 | − // Post-settle navigation must skip threads settling in this same | |
| 2645 | − // batch — they are all leaving the card block together. Rows that | |
| 2646 | − // are already explicitly settled are skipped: nothing to do on a | |
| 2647 | − // valid mixed selection. Pinned rows ARE included: the decider | |
| 2648 | − // clears the pin as part of settling, so they park like the rest. | |
| 2649 | − const coSettlingKeys = new Set(threadKeys); | |
| 2650 | − for (const threadKey of threadKeys) { | |
| 2651 | − const thread = threadByKeyRef.current.get(threadKey); | |
| 2652 | − if (!thread || thread.settledOverride === "settled") continue; | |
| 2653 | − attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys }); | |
| 2654 | − } | |
| 2655 | − clearSelection(); | |
| 2656 | − return; | |
| 2657 | − } | |
| 2658 | − if (clicked.value === "mark-unread") { | |
| 2659 | − for (const threadKey of threadKeys) { | |
| 2660 | − const thread = threadByKeyRef.current.get(threadKey); | |
| 2661 | − markThreadUnread(threadKey, thread?.latestTurn?.completedAt); | |
| 2662 | − } | |
| 2663 | − clearSelection(); | |
| 2664 | − return; | |
| 2665 | − } | |
| 2666 | − if (clicked.value !== "delete") return; | |
| 2667 | − if (confirmThreadDelete) { | |
| 2668 | − const confirmed = await settlePromise(() => | |
| 2669 | − api.dialogs.confirm( | |
| 2670 | − [ | |
| 2671 | − `Delete ${count} thread${count === 1 ? "" : "s"}?`, | |
| 2672 | − "This permanently clears conversation history for these threads.", | |
| 2673 | − ].join("\n"), | |
| 2674 | − ), | |
| 2675 | − ); | |
| 2676 | − if (confirmed._tag === "Failure" || !confirmed.value) return; | |
| 2677 | − } | |
| 2678 | − // Grown as deletions actually land, never seeded with the whole batch: | |
| 2679 | − // orphaned-worktree detection must only discount threads that are | |
| 2680 | − // really gone, or the first delete would treat still-alive batch mates | |
| 2681 | − // as deleted and remove a worktree they still point at. | |
| 2682 | − const deletedThreadKeys = new Set<string>(); | |
| 2683 | − for (const threadKey of threadKeys) { | |
| 2684 | − const thread = threadByKeyRef.current.get(threadKey); | |
| 2685 | − if (!thread) continue; | |
| 2686 | − const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id), { | |
| 2687 | − deletedThreadKeys, | |
| 2688 | − }); | |
| 2689 | − if (result._tag === "Failure") { | |
| 2690 | − if (!isAtomCommandInterrupted(result)) { | |
| 2691 | − const error = squashAtomCommandFailure(result); | |
| 2692 | − toastManager.add( | |
| 2693 | − stackedThreadToast({ | |
| 2694 | − type: "error", | |
| 2695 | − title: "Failed to delete threads", | |
| 2696 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2697 | − }), | |
| 2698 | − ); | |
| 2699 | − } | |
| 2700 | − return; | |
| 2701 | − } | |
| 2702 | − deletedThreadKeys.add(threadKey); | |
| 2703 | − } | |
| 2704 | − removeFromSelection(threadKeys); | |
| 2705 | − }, | |
| 2706 | − [ | |
| 2707 | − attemptSettle, | |
| 2708 | − attemptSnooze, | |
| 2709 | − clearSelection, | |
| 2710 | − confirmThreadDelete, | |
| 2711 | − deleteThread, | |
| 2712 | − markThreadUnread, | |
| 2713 | − performSnooze, | |
| 2714 | − removeFromSelection, | |
| 2715 | − serverConfigs, | |
| 2716 | − attemptUnsnooze, | |
| 2717 | − updateThreadMetadata, | |
| 2718 | − timestampFormat, | |
| 2719 | − ], | |
| 2720 | − ); | |
| 2721 | − | |
| 2722 | − const handleThreadContextMenu = useCallback( | |
| 2723 | − (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { | |
| 2724 | − void (async () => { | |
| 2725 | − const api = readLocalApi(); | |
| 2726 | − if (!api) return; | |
| 2727 | − const threadKey = scopedThreadKey(threadRef); | |
| 2728 | − const selectionState = useThreadSelectionStore.getState(); | |
| 2729 | − if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { | |
| 2730 | − await handleMultiSelectContextMenu(position); | |
| 2731 | − return; | |
| 2732 | − } | |
| 2733 | − const thread = threadByKeyRef.current.get(threadKey); | |
| 2734 | − if (!thread) return; | |
| 2735 | − const threadWorkspacePath = | |
| 2736 | − thread.worktreePath ?? | |
| 2737 | − projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? | |
| 2738 | − null; | |
| 2739 | − // Un-settle works on every settled row: for explicit settles it | |
| 2740 | − // clears the override, for auto-settled rows it pins the thread | |
| 2741 | − // active until real activity clears the pin. Environments without | |
| 2742 | − // the settlement capability get no lifecycle items at all. | |
| 2743 | − const supportsSettlement = | |
| 2744 | − serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === | |
| 2745 | − true; | |
| 2746 | − const supportsSnooze = | |
| 2747 | − serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; | |
| 2748 | − const supportsPinning = | |
| 2749 | − serverConfigs.get(thread.environmentId)?.environment.capabilities.threadPinning === true; | |
| 2750 | − const supportsTitleRegeneration = | |
| 2751 | − serverConfigs.get(thread.environmentId)?.environment.capabilities | |
| 2752 | − .threadTitleRegeneration === true; | |
| 2753 | − const isRegeneratingTitle = thread.titleRegeneration != null; | |
| 2754 | − const isSettled = settledThreadKeysRef.current.has(threadKey); | |
| 2755 | − const isSnoozed = snoozedThreadKeysRef.current.has(threadKey); | |
| 2756 | − const isPinned = thread.pinnedAt != null; | |
| 2757 | − // Presets resolve at menu-open time (same as the popover). | |
| 2758 | − const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); | |
| 2759 | − const clicked = await settlePromise(() => | |
| 2760 | − api.contextMenu.show( | |
| 2761 | − buildThreadActionMenuItems({ | |
| 2762 | − branch: thread.branch ?? null, | |
| 2763 | − isPinned, | |
| 2764 | − isSettled, | |
| 2765 | − isSnoozed, | |
| 2766 | − canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), | |
| 2767 | − isRegeneratingTitle, | |
| 2768 | − supports: { | |
| 2769 | − settlement: supportsSettlement, | |
| 2770 | − snooze: supportsSnooze, | |
| 2771 | − pinning: supportsPinning, | |
| 2772 | − titleRegeneration: supportsTitleRegeneration, | |
| 2773 | − }, | |
| 2774 | − snoozePresets, | |
| 2775 | − }), | |
| 2776 | − position, | |
| 2777 | − ), | |
| 2778 | − ); | |
| 2779 | − if (clicked._tag === "Failure") return; | |
| 2780 | − if (clicked.value?.startsWith("snooze:")) { | |
| 2781 | − const preset = snoozePresets.find( | |
| 2782 | − (candidate) => `snooze:${candidate.id}` === clicked.value, | |
| 2783 | − ); | |
| 2784 | − if (preset) attemptSnooze(threadRef, preset); | |
| 2785 | − return; | |
| 2786 | − } | |
| 2787 | − switch (clicked.value) { | |
| 2788 | − case "new-thread-on-branch": { | |
| 2789 | − // Explicit branch carry-over: reuse the thread's worktree when it | |
| 2790 | − // has one, otherwise its branch on the local checkout. | |
| 2791 | − const result = await settlePromise(() => | |
| 2792 | − handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId), { | |
| 2793 | − branch: thread.branch, | |
| 2794 | − worktreePath: thread.worktreePath, | |
| 2795 | − envMode: thread.worktreePath ? "worktree" : "local", | |
| 2796 | − startFromOrigin: false, | |
| 2797 | − }), | |
| 2798 | − ); | |
| 2799 | − if (result._tag === "Failure") { | |
| 2800 | − const error = squashAtomCommandFailure(result); | |
| 2801 | − toastManager.add( | |
| 2802 | − stackedThreadToast({ | |
| 2803 | − type: "error", | |
| 2804 | − title: "Could not create thread", | |
| 2805 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2806 | − }), | |
| 2807 | − ); | |
| 2808 | − } | |
| 2809 | − return; | |
| 2810 | − } | |
| 2811 | − case "settle": | |
| 2812 | − attemptSettle(threadRef); | |
| 2813 | − return; | |
| 2814 | − case "unsettle": | |
| 2815 | − attemptUnsettle(threadRef); | |
| 2816 | − return; | |
| 2817 | − case "unsnooze": | |
| 2818 | − attemptUnsnooze(threadRef); | |
| 2819 | − return; | |
| 2820 | − case "pin": | |
| 2821 | − attemptPin(threadRef); | |
| 2822 | − return; | |
| 2823 | − case "unpin": | |
| 2824 | − attemptUnpin(threadRef); | |
| 2825 | − return; | |
| 2826 | − case "rename": | |
| 2827 | − startThreadRename(threadRef, thread.title); | |
| 2828 | − return; | |
| 2829 | − case "regenerate-title": { | |
| 2830 | − if (isRegeneratingTitle) return; | |
| 2831 | − const result = await updateThreadMetadata({ | |
| 2832 | − environmentId: threadRef.environmentId, | |
| 2833 | − input: { threadId: threadRef.threadId, regenerateTitle: true }, | |
| 2834 | − }); | |
| 2835 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2836 | − const error = squashAtomCommandFailure(result); | |
| 2837 | − toastManager.add( | |
| 2838 | − stackedThreadToast({ | |
| 2839 | − type: "error", | |
| 2840 | − title: "Failed to regenerate thread title", | |
| 2841 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2842 | − }), | |
| 2843 | − ); | |
| 2844 | − } | |
| 2845 | − return; | |
| 2846 | − } | |
| 2847 | − case "mark-unread": | |
| 2848 | − markThreadUnread(threadKey, thread.latestTurn?.completedAt); | |
| 2849 | − return; | |
| 2850 | − case "copy-path": | |
| 2851 | − if (!threadWorkspacePath) { | |
| 2852 | − toastManager.add( | |
| 2853 | − stackedThreadToast({ | |
| 2854 | − type: "error", | |
| 2855 | − title: "Path unavailable", | |
| 2856 | − description: "This thread does not have a workspace path to copy.", | |
| 2857 | − }), | |
| 2858 | − ); | |
| 2859 | − return; | |
| 2860 | − } | |
| 2861 | − copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); | |
| 2862 | − return; | |
| 2863 | − case "copy-branch": | |
| 2864 | − if (thread.branch) { | |
| 2865 | − copyBranchToClipboard(thread.branch, { branch: thread.branch }); | |
| 2866 | − } | |
| 2867 | − return; | |
| 2868 | − case "delete": { | |
| 2869 | − if (confirmThreadDelete) { | |
| 2870 | − const confirmed = await settlePromise(() => | |
| 2871 | − api.dialogs.confirm( | |
| 2872 | − [ | |
| 2873 | − `Delete thread "${thread.title}"?`, | |
| 2874 | − "This permanently clears conversation history for this thread.", | |
| 2875 | − ].join("\n"), | |
| 2876 | − ), | |
| 2877 | − ); | |
| 2878 | − if (confirmed._tag === "Failure" || !confirmed.value) return; | |
| 2879 | − } | |
| 2880 | − const result = await deleteThread(threadRef); | |
| 2881 | − if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { | |
| 2882 | − const error = squashAtomCommandFailure(result); | |
| 2883 | − toastManager.add( | |
| 2884 | − stackedThreadToast({ | |
| 2885 | − type: "error", | |
| 2886 | − title: "Failed to delete thread", | |
| 2887 | − description: error instanceof Error ? error.message : "An error occurred.", | |
| 2888 | − }), | |
| 2889 | − ); | |
| 2890 | − return; | |
| 2891 | − } | |
| 2892 | − return; | |
| 2893 | − } | |
| 2894 | − default: | |
| 2895 | − return; | |
| 2896 | − } | |
| 2897 | − })(); | |
| 2898 | − }, | |
| 2899 | − [ | |
| 2900 | − attemptPin, | |
| 2901 | − attemptSettle, | |
| 2902 | − attemptSnooze, | |
| 2903 | − attemptUnpin, | |
| 2904 | − attemptUnsettle, | |
| 2905 | − attemptUnsnooze, | |
| 2906 | − confirmThreadDelete, | |
| 2907 | − copyBranchToClipboard, | |
| 2908 | − copyPathToClipboard, | |
| 2909 | − deleteThread, | |
| 2910 | − handleMultiSelectContextMenu, | |
| 2911 | − markThreadUnread, | |
| 2912 | − projectCwdByKey, | |
| 2913 | − serverConfigs, | |
| 2914 | − startThreadRename, | |
| 2915 | − updateThreadMetadata, | |
| 2916 | − timestampFormat, | |
| 2917 | − ], | |
| 2918 | − ); | |
| 2919 | − | |
| 2920 | − // Thread jump (cmd+1..9) and prev/next traversal reuse the same commands as | |
| 2921 | − // v1 — the keybinding layer is shared, only the ordered list differs. | |
| 2922 | − const routeTerminalOpen = useTerminalUiStateStore((state) => | |
| 2923 | − routeThreadRef | |
| 2924 | − ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen | |
| 2925 | − : false, | |
| 2926 | − ); | |
| 2927 | − useEffect(() => { | |
| 2928 | − const onWindowKeyDown = (event: KeyboardEvent) => { | |
| 2929 | − if (event.defaultPrevented || event.repeat) return; | |
| 2930 | − const command = resolveShortcutCommand(event, keybindings, { | |
| 2931 | − platform: navigator.platform, | |
| 2932 | − context: { | |
| 2933 | − terminalFocus: isTerminalFocused(), | |
| 2934 | − terminalOpen: routeTerminalOpen, | |
| 2935 | − modelPickerOpen: isModelPickerOpen(), | |
| 2936 | − }, | |
| 2937 | − }); | |
| 2938 | − const navigateToThreadKey = (targetThreadKey: string | null) => { | |
| 2939 | − if (!targetThreadKey) return false; | |
| 2940 | − const targetThread = threadByKey.get(targetThreadKey); | |
| 2941 | − if (!targetThread) return false; | |
| 2942 | − event.preventDefault(); | |
| 2943 | − event.stopPropagation(); | |
| 2944 | − navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); | |
| 2945 | − return true; | |
| 2946 | − }; | |
| 2947 | − const traversalDirection = threadTraversalDirectionFromCommand(command); | |
| 2948 | − if (traversalDirection !== null) { | |
| 2949 | − navigateToThreadKey( | |
| 2950 | − resolveAdjacentThreadId({ | |
| 2951 | − threadIds: orderedThreadKeys, | |
| 2952 | − currentThreadId: routeThreadKey, | |
| 2953 | − direction: traversalDirection, | |
| 2954 | − }), | |
| 2955 | − ); | |
| 2956 | − return; | |
| 2957 | − } | |
| 2958 | − const jumpIndex = threadJumpIndexFromCommand(command ?? ""); | |
| 2959 | − if (jumpIndex === null) return; | |
| 2960 | − navigateToThreadKey(orderedThreadKeys[jumpIndex] ?? null); | |
| 2961 | − }; | |
| 2962 | − window.addEventListener("keydown", onWindowKeyDown); | |
| 2963 | − return () => window.removeEventListener("keydown", onWindowKeyDown); | |
| 2964 | − }, [ | |
| 2965 | − keybindings, | |
| 2966 | − navigateToThread, | |
| 2967 | − orderedThreadKeys, | |
| 2968 | − routeTerminalOpen, | |
| 2969 | − routeThreadKey, | |
| 2970 | − threadByKey, | |
| 2971 | − ]); | |
| 2972 | − | |
| 2973 | − // Same predicate as v1: hints show only while the held modifiers exactly | |
| 2974 | − // match a thread-jump binding. Adding Shift (screenshots) or Alt no | |
| 2975 | − // longer matches ⌘1..9, so the overlay hides for chords like ⌘⇧4. | |
| 2976 | − const shortcutModifiers = useShortcutModifierState(); | |
| 2977 | − const shouldShowJumpHintsNow = shouldShowThreadJumpHintsForModifiers( | |
| 2978 | − shortcutModifiers, | |
| 2979 | − keybindings, | |
| 2980 | − { platform: navigator.platform }, | |
| 2981 | − ); | |
| 2982 | − useEffect(() => { | |
| 2983 | − setShowJumpHints(shouldShowJumpHintsNow); | |
| 2984 | − }, [shouldShowJumpHintsNow]); | |
| 2985 | − | |
| 2986 | − const attachListAutoAnimateRef = useCallback((node: HTMLUListElement | null) => { | |
| 2987 | − if (!node) return; | |
| 2988 | − autoAnimate(node, { duration: 150, easing: "ease-out" }); | |
| 2989 | − }, []); | |
| 2990 | − | |
| 2991 | − // New thread defaults to the project you're in (active thread's project, | |
| 2992 | − // falling back to the top project) — same resolution the command palette | |
| 2993 | − // uses. The command palette already offers a "New thread in..." submenu | |
| 2994 | − // for multi-project setups. | |
| 2995 | − const handleNewThreadClick = useCallback(() => { | |
| 2996 | − // One project: nothing to pick, create immediately. | |
| 2997 | − if (projectGroups.length <= 1) { | |
| 2998 | − if (isMobile) setOpenMobile(false); | |
| 2999 | − void startNewThreadFromContext({ | |
| 3000 | − activeDraftThread: newThreadContext.activeDraftThread, | |
| 3001 | − activeThread: newThreadContext.activeThread ?? undefined, | |
| 3002 | − defaultProjectRef: newThreadContext.defaultProjectRef, | |
| 3003 | − handleNewThread: newThreadContext.handleNewThread, | |
| 3004 | − }); | |
| 3005 | − return; | |
| 3006 | − } | |
| 3007 | − if (isMobile) setOpenMobile(false); | |
| 3008 | − openCommandPalette({ open: "new-thread-in" }); | |
| 3009 | − }, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]); | |
| 3010 | − | |
| 3011 | − // The button mirrors chat.new: in multi-project setups both route through | |
| 3012 | − // the command palette's "New thread in..." picker, and in single-project | |
| 3013 | − // setups both create immediately. chat.newLocal always creates directly, so | |
| 3014 | − // it is only a correct label when chat.new is unbound. | |
| 3015 | − const newThreadShortcutLabel = | |
| 3016 | − shortcutLabelForCommand(keybindings, "chat.new") ?? | |
| 3017 | − shortcutLabelForCommand(keybindings, "chat.newLocal"); | |
| 3018 | − return ( | |
| 3019 | − <> | |
| 3020 | − <SidebarChromeHeader isElectron={isElectron} /> | |
| 3021 | − <SidebarContent | |
| 3022 | − className="gap-0" | |
| 3023 | − fixedHeader={ | |
| 3024 | − // Lifted above the stage backdrop, whose fade bleeds below the | |
| 3025 | − // header and would otherwise paint across the search row's outline. | |
| 3026 | − <SidebarGroup className="relative z-[1] gap-1 p-[var(--sidebar-content-inset)]"> | |
| 3027 | − <div className="flex items-center gap-1"> | |
| 3028 | − <div className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground"> | |
| 3029 | − <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" /> | |
| 3030 | − <Input | |
| 3031 | − ref={threadSearchInputRef} | |
| 3032 | − nativeInput | |
| 3033 | − unstyled | |
| 3034 | − type="search" | |
| 3035 | − value={threadSearchQuery} | |
| 3036 | − onChange={(event) => { | |
| 3037 | − setThreadSearchQuery(event.currentTarget.value); | |
| 3038 | − setActiveSearchResultIndex(0); | |
| 3039 | − }} | |
| 3040 | − onKeyDown={handleThreadSearchKeyDown} | |
| 3041 | − placeholder="Search" | |
| 3042 | − aria-label="Search threads" | |
| 3043 | − role="combobox" | |
| 3044 | − aria-autocomplete="list" | |
| 3045 | − aria-expanded={isSearchingThreads && threadSearchResults.length > 0} | |
| 3046 | − aria-controls={ | |
| 3047 | − isSearchingThreads && threadSearchResults.length > 0 | |
| 3048 | − ? "sidebar-thread-search-results" | |
| 3049 | − : undefined | |
| 3050 | − } | |
| 3051 | − aria-activedescendant={ | |
| 3052 | − isSearchingThreads && threadSearchResults[activeSearchResultIndex] | |
| 3053 | − ? `sidebar-thread-search-result-${activeSearchResultIndex}` | |
| 3054 | − : undefined | |
| 3055 | − } | |
| 3056 | − className="min-w-0 flex-1 [&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:placeholder:text-sidebar-muted-foreground" | |
| 3057 | − /> | |
| 3058 | − {isSearchingThreads ? ( | |
| 3059 | − <Button | |
| 3060 | − type="button" | |
| 3061 | − size="icon-xs" | |
| 3062 | − variant="ghost" | |
| 3063 | − className="size-5 shrink-0 rounded-sm text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground" | |
| 3064 | − aria-label="Clear thread search" | |
| 3065 | − onClick={() => { | |
| 3066 | − clearThreadSearch(); | |
| 3067 | − threadSearchInputRef.current?.focus(); | |
| 3068 | − }} | |
| 3069 | − > | |
| 3070 | − <XIcon className="size-3" /> | |
| 3071 | − </Button> | |
| 3072 | − ) : null} | |
| 3073 | − </div> | |
| 3074 | − <div className="shrink-0"> | |
| 3075 | − <Tooltip> | |
| 3076 | − <TooltipTrigger | |
| 3077 | − render={ | |
| 3078 | − <SidebarMenuButton | |
| 3079 | − size="icon" | |
| 3080 | − type="button" | |
| 3081 | − className="relative focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar" | |
| 3082 | − onClick={handleNewThreadClick} | |
| 3083 | − disabled={projects.length === 0} | |
| 3084 | − aria-label="New thread" | |
| 3085 | − /> | |
| 3086 | − } | |
| 3087 | − > | |
| 3088 | − <SquarePenIcon /> | |
| 3089 | − <span | |
| 3090 | − className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden" | |
| 3091 | − aria-hidden="true" | |
| 3092 | − /> | |
| 3093 | − </TooltipTrigger> | |
| 3094 | − <TooltipPopup side="right"> | |
| 3095 | − {newThreadShortcutLabel | |
| 3096 | − ? `New thread (${newThreadShortcutLabel})` | |
| 3097 | − : "New thread"} | |
| 3098 | − </TooltipPopup> | |
| 3099 | − </Tooltip> | |
| 3100 | − </div> | |
| 3101 | − </div> | |
| 3102 | − {projectGroups.length > 0 ? ( | |
| 3103 | − <div className="flex items-center gap-1"> | |
| 3104 | − <Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}> | |
| 3105 | − <MenuTrigger | |
| 3106 | − render={ | |
| 3107 | − <SidebarMenuButton | |
| 3108 | − aria-label="Filter threads by project" | |
| 3109 | − className="min-w-0 flex-1 ps-[calc(var(--sidebar-row-content-inset)-1px)] focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar" | |
| 3110 | − /> | |
| 3111 | − } | |
| 3112 | − > | |
| 3113 | − {scopedProjectGroup ? ( | |
| 3114 | − <ProjectFavicon | |
| 3115 | − environmentId={scopedProjectGroup.environmentId} | |
| 3116 | − cwd={scopedProjectGroup.workspaceRoot} | |
| 3117 | − className="size-4 shrink-0" | |
| 3118 | − /> | |
| 3119 | − ) : ( | |
| 3120 | − <FolderIcon className="size-4 shrink-0" /> | |
| 3121 | − )} | |
| 3122 | − <span className="min-w-0 flex-1 truncate"> | |
| 3123 | − {scopedProjectGroup?.displayName ?? "All projects"} | |
| 3124 | − </span> | |
| 3125 | − <ChevronDownIcon className="-mr-px size-4 shrink-0" /> | |
| 3126 | − </MenuTrigger> | |
| 3127 | − <MenuPopup align="start" className="w-(--anchor-width)"> | |
| 3128 | − <MenuRadioGroup | |
| 3129 | − value={projectScopeKey ?? "all"} | |
| 3130 | − onValueChange={(value) => | |
| 3131 | − setProjectScopeKey(value === "all" ? null : (value as string)) | |
| 3132 | − } | |
| 3133 | − > | |
| 3134 | − <MenuRadioItem | |
| 3135 | − value="all" | |
| 3136 | − closeOnClick | |
| 3137 | − className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2" | |
| 3138 | − > | |
| 3139 | − <FolderIcon className="size-4 shrink-0" /> | |
| 3140 | − <span className="min-w-0 truncate text-sm">All projects</span> | |
| 3141 | − </MenuRadioItem> | |
| 3142 | − {projectGroups.map((project) => { | |
| 3143 | − const scopeKey = project.projectKey; | |
| 3144 | − return ( | |
| 3145 | − <MenuRadioItem | |
| 3146 | − key={scopeKey} | |
| 3147 | − value={scopeKey} | |
| 3148 | − closeOnClick | |
| 3149 | − className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2" | |
| 3150 | − > | |
| 3151 | − <ProjectFavicon | |
| 3152 | − environmentId={project.environmentId} | |
| 3153 | − cwd={project.workspaceRoot} | |
| 3154 | − className="size-4 shrink-0" | |
| 3155 | − /> | |
| 3156 | − <span className="min-w-0 truncate text-sm">{project.displayName}</span> | |
| 3157 | − <button | |
| 3158 | − type="button" | |
| 3159 | − aria-label={`Project actions for ${project.displayName}`} | |
| 3160 | − title={`Project actions for ${project.displayName}`} | |
| 3161 | − className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-icon-muted outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring" | |
| 3162 | − onPointerDown={(event) => event.stopPropagation()} | |
| 3163 | − onClick={(event) => { | |
| 3164 | − void handleProjectActions(event, project); | |
| 3165 | − }} | |
| 3166 | − > | |
| 3167 | − <EllipsisIcon className="size-3.5" /> | |
| 3168 | − </button> | |
| 3169 | − </MenuRadioItem> | |
| 3170 | − ); | |
| 3171 | − })} | |
| 3172 | − </MenuRadioGroup> | |
| 3173 | − </MenuPopup> | |
| 3174 | − </Menu> | |
| 3175 | − <Tooltip> | |
| 3176 | − <TooltipTrigger | |
| 3177 | − render={ | |
| 3178 | − <SidebarMenuButton | |
| 3179 | − size="icon" | |
| 3180 | − className="relative shrink-0 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar" | |
| 3181 | − onClick={openAddProjectCommandPalette} | |
| 3182 | − type="button" | |
| 3183 | − aria-label="New project" | |
| 3184 | − /> | |
| 3185 | − } | |
| 3186 | − > | |
| 3187 | − <FolderPlusIcon /> | |
| 3188 | − <span | |
| 3189 | − className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden" | |
| 3190 | − aria-hidden="true" | |
| 3191 | − /> | |
| 3192 | − </TooltipTrigger> | |
| 3193 | − <TooltipPopup side="right">New project</TooltipPopup> | |
| 3194 | − </Tooltip> | |
| 3195 | − </div> | |
| 3196 | − ) : null} | |
| 3197 | − </SidebarGroup> | |
| 3198 | − } | |
| 3199 | − > | |
| 3200 | − <SidebarGroup className="ps-[calc(var(--sidebar-content-inset)+1px)] pe-[var(--sidebar-content-inset)] pb-1 pt-0"> | |
| 3201 | − {isSearchingThreads ? ( | |
| 3202 | − threadSearchResults.length > 0 ? ( | |
| 3203 | − <TooltipProvider | |
| 3204 | − key="sidebar-thread-search-tooltips-150" | |
| 3205 | − delay={150} | |
| 3206 | − closeDelay={0} | |
| 3207 | − timeout={400} | |
| 3208 | − > | |
| 3209 | − <ul | |
| 3210 | − id="sidebar-thread-search-results" | |
| 3211 | − role="listbox" | |
| 3212 | − aria-label="Thread search results" | |
| 3213 | − className="flex flex-col gap-px" | |
| 3214 | − > | |
| 3215 | − {threadSearchResults.map((thread, index) => { | |
| 3216 | − const threadKey = scopedThreadKey( | |
| 3217 | − scopeThreadRef(thread.environmentId, thread.id), | |
| 3218 | − ); | |
| 3219 | − return ( | |
| 3220 | − <SidebarV2SearchResultRow | |
| 3221 | − key={threadKey} | |
| 3222 | − thread={thread} | |
| 3223 | − projectCwd={ | |
| 3224 | − projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null | |
| 3225 | − } | |
| 3226 | − projectTitle={ | |
| 3227 | − projectDisplayNameByKey.get( | |
| 3228 | − `${thread.environmentId}:${thread.projectId}`, | |
| 3229 | − ) ?? null | |
| 3230 | − } | |
| 3231 | − environmentLabel={environmentLabelById.get(thread.environmentId) ?? null} | |
| 3232 | − providerEntryByInstanceId={providerEntryByInstanceId} | |
| 3233 | − isHighlighted={activeSearchResultIndex === index} | |
| 3234 | − isRouteActive={routeThreadKey === threadKey} | |
| 3235 | − resultId={`sidebar-thread-search-result-${index}`} | |
| 3236 | − onHighlight={() => setActiveSearchResultIndex(index)} | |
| 3237 | − onSelect={() => selectThreadSearchResult(thread)} | |
| 3238 | − /> | |
| 3239 | − ); | |
| 3240 | − })} | |
| 3241 | − </ul> | |
| 3242 | − </TooltipProvider> | |
| 3243 | − ) : ( | |
| 3244 | − <p | |
| 3245 | − role="status" | |
| 3246 | − className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground" | |
| 3247 | − > | |
| 3248 | − No threads found | |
| 3249 | − </p> | |
| 3250 | − ) | |
| 3251 | − ) : null} | |
| 3252 | − {!isSearchingThreads ? ( | |
| 3253 | − <TooltipProvider | |
| 3254 | − key="sidebar-thread-tooltips-150" | |
| 3255 | − delay={150} | |
| 3256 | − closeDelay={0} | |
| 3257 | − timeout={400} | |
| 3258 | − > | |
| 3259 | − <ul ref={attachListAutoAnimateRef} role="list" className="flex flex-col gap-px"> | |
| 3260 | − {(() => { | |
| 3261 | − const renderThreadRow = ( | |
| 3262 | − thread: EnvironmentThreadShell, | |
| 3263 | − section: "pinned" | "active" | "snoozed" | "settled", | |
| 3264 | − sortable?: SortablePinnedRowBag, | |
| 3265 | − ) => { | |
| 3266 | − const threadKey = scopedThreadKey( | |
| 3267 | − scopeThreadRef(thread.environmentId, thread.id), | |
| 3268 | − ); | |
| 3269 | − // Settled and snoozed are the ONLY things that collapse a | |
| 3270 | − // row: every other thread is a full card. Density comes | |
| 3271 | − // from users (or the auto rules) actually parking work, | |
| 3272 | − // not from the sidebar second-guessing what still matters. | |
| 3273 | − const isCard = section === "active" || section === "pinned"; | |
| 3274 | − const rowVariant = isCard ? "card" : "slim"; | |
| 3275 | − return ( | |
| 3276 | − <SidebarV2Row | |
| 3277 | − // Keyed per variant on purpose: when a thread settles, | |
| 3278 | − // the card fades out in place and the slim row fades | |
| 3279 | − // in at its settled position instead of one element | |
| 3280 | − // FLIP-sliding through every row in between (rows here | |
| 3281 | − // are translucent, so a crossing row reads as text | |
| 3282 | − // painted over text). | |
| 3283 | − key={`${threadKey}:${rowVariant}`} | |
| 3284 | − thread={thread} | |
| 3285 | − variant={rowVariant} | |
| 3286 | − // Snoozed rows wake; settled rows un-settle (explicit | |
| 3287 | − // settles clear the override, auto-settled rows get | |
| 3288 | − // pinned active); cards settle. | |
| 3289 | − variantAction={ | |
| 3290 | − section === "snoozed" | |
| 3291 | − ? "unsnooze" | |
| 3292 | − : section === "settled" | |
| 3293 | − ? "unsettle" | |
| 3294 | − : "settle" | |
| 3295 | − } | |
| 3296 | − settlementSupported={ | |
| 3297 | − serverConfigs.get(thread.environmentId)?.environment.capabilities | |
| 3298 | − .threadSettlement === true | |
| 3299 | − } | |
| 3300 | − snoozeSupported={ | |
| 3301 | − serverConfigs.get(thread.environmentId)?.environment.capabilities | |
| 3302 | − .threadSnooze === true | |
| 3303 | − } | |
| 3304 | − pinningSupported={ | |
| 3305 | − serverConfigs.get(thread.environmentId)?.environment.capabilities | |
| 3306 | − .threadPinning === true | |
| 3307 | − } | |
| 3308 | − isPinned={section === "pinned"} | |
| 3309 | − sortable={sortable} | |
| 3310 | − snoozeWakeLabelText={ | |
| 3311 | − section === "snoozed" && thread.snoozedUntil != null | |
| 3312 | − ? snoozeWakeLabel(thread.snoozedUntil, { | |
| 3313 | − now: new Date().toISOString(), | |
| 3314 | − }) | |
| 3315 | − : null | |
| 3316 | − } | |
| 3317 | − // All sections: a woken thread can classify straight | |
| 3318 | − // into the settled tail (PR merged while snoozed), and | |
| 3319 | − // the wake signal must survive the trip. Still-snoozed | |
| 3320 | − // rows resolve to null on their own. | |
| 3321 | − wokeAt={threadWokeAt(thread, { now: snoozeNow })} | |
| 3322 | − isActive={routeThreadKey === threadKey} | |
| 3323 | − jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null} | |
| 3324 | − currentEnvironmentId={primaryEnvironmentId} | |
| 3325 | − environmentLabel={environmentLabelById.get(thread.environmentId) ?? null} | |
| 3326 | − projectCwd={ | |
| 3327 | − projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null | |
| 3328 | − } | |
| 3329 | − projectTitle={ | |
| 3330 | − projectDisplayNameByKey.get( | |
| 3331 | − `${thread.environmentId}:${thread.projectId}`, | |
| 3332 | − ) ?? null | |
| 3333 | − } | |
| 3334 | − providerEntryByInstanceId={providerEntryByInstanceId} | |
| 3335 | − timestampFormat={timestampFormat} | |
| 3336 | − onThreadClick={handleThreadClick} | |
| 3337 | − onThreadActivate={navigateToThread} | |
| 3338 | − onStartRename={startThreadRename} | |
| 3339 | − onRenameTitleChange={setRenamingTitle} | |
| 3340 | − onCommitRename={commitThreadRename} | |
| 3341 | − onCancelRename={cancelThreadRename} | |
| 3342 | − isRenaming={renamingThreadKey === threadKey} | |
| 3343 | − renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""} | |
| 3344 | − onContextMenu={handleThreadContextMenu} | |
| 3345 | − onSettle={attemptSettle} | |
| 3346 | − onUnsettle={attemptUnsettle} | |
| 3347 | − onSnooze={attemptSnooze} | |
| 3348 | − onUnsnooze={attemptUnsnooze} | |
| 3349 | − onUnpin={attemptUnpin} | |
| 3350 | − onAcknowledgeWoke={acknowledgeWoke} | |
| 3351 | − onChangeRequestState={handleChangeRequestState} | |
| 3352 | − /> | |
| 3353 | − ); | |
| 3354 | − }; | |
| 3355 | − // Pinned block: full cards above the inbox, closed by a | |
| 3356 | − // thin divider (the pin glyphs carry the meaning, so no | |
| 3357 | − // header text). Vanishes entirely at count 0. | |
| 3358 | − // Rows render in the one shared pinned order; only | |
| 3359 | − // reorder-capable rows register as sortable (legacy-server | |
| 3360 | − // pins render in place as plain rows). | |
| 3361 | − const items: ReactNode[] = [ | |
| 3362 | − <DndContext | |
| 3363 | − key="pinned-dnd" | |
| 3364 | − sensors={pinnedDndSensors} | |
| 3365 | − collisionDetection={closestCenter} | |
| 3366 | − modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]} | |
| 3367 | − onDragEnd={handlePinnedDragEnd} | |
| 3368 | − > | |
| 3369 | − <SortableContext | |
| 3370 | − items={orderedPinnedThreads | |
| 3371 | − .map((thread) => | |
| 3372 | − scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), | |
| 3373 | − ) | |
| 3374 | − .filter((threadKey) => reorderablePinnedKeys.has(threadKey))} | |
| 3375 | − strategy={verticalListSortingStrategy} | |
| 3376 | − > | |
| 3377 | − {orderedPinnedThreads.map((thread) => { | |
| 3378 | − const threadKey = scopedThreadKey( | |
| 3379 | − scopeThreadRef(thread.environmentId, thread.id), | |
| 3380 | − ); | |
| 3381 | − if (!reorderablePinnedKeys.has(threadKey)) { | |
| 3382 | − return renderThreadRow(thread, "pinned"); | |
| 3383 | − } | |
| 3384 | − return ( | |
| 3385 | − <SortablePinnedThreadRow key={threadKey} id={threadKey}> | |
| 3386 | − {(bag) => renderThreadRow(thread, "pinned", bag)} | |
| 3387 | − </SortablePinnedThreadRow> | |
| 3388 | − ); | |
| 3389 | − })} | |
| 3390 | − </SortableContext> | |
| 3391 | − </DndContext>, | |
| 3392 | − ]; | |
| 3393 | − if (pinnedThreads.length > 0) { | |
| 3394 | − items.push( | |
| 3395 | − <li | |
| 3396 | − key="pinned-divider" | |
| 3397 | − aria-hidden | |
| 3398 | − data-testid="sidebar-v2-pinned-divider" | |
| 3399 | − className="mx-2.5 my-1.5 h-px list-none bg-sidebar-border/60" | |
| 3400 | − />, | |
| 3401 | − ); | |
| 3402 | − } | |
| 3403 | − for (const thread of activeThreads) { | |
| 3404 | − items.push(renderThreadRow(thread, "active")); | |
| 3405 | − } | |
| 3406 | − // Snoozed shelf: between the inbox and Settled — out of the | |
| 3407 | − // way, never gone. The header always renders while anything | |
| 3408 | − // is snoozed (the count is the whole footprint when | |
| 3409 | − // collapsed); rows only when expanded. Vanishes entirely at | |
| 3410 | − // count 0. | |
| 3411 | − if (snoozedThreads.length > 0) { | |
| 3412 | − items.push( | |
| 3413 | − <li | |
| 3414 | − key="snoozed-shelf-header" | |
| 3415 | − data-thread-selection-safe | |
| 3416 | − className="list-none" | |
| 3417 | − > | |
| 3418 | − <button | |
| 3419 | − type="button" | |
| 3420 | − onClick={toggleSnoozedShelf} | |
| 3421 | − aria-expanded={snoozedShelfExpanded} | |
| 3422 | − data-testid="sidebar-v2-snoozed-shelf-toggle" | |
| 3423 | − className="mb-1 mt-3 flex w-full cursor-pointer items-center gap-2 px-2.5 text-left" | |
| 3424 | − > | |
| 3425 | − <span className="text-xs font-medium text-blue-600 dark:text-blue-400"> | |
| 3426 | − {snoozedShelfExpanded | |
| 3427 | − ? "Snoozed" | |
| 3428 | − : `Snoozed (${snoozedThreads.length})`} | |
| 3429 | − </span> | |
| 3430 | − <span className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" /> | |
| 3431 | − <ChevronDownIcon | |
| 3432 | − aria-hidden | |
| 3433 | − className={cn( | |
| 3434 | − "size-3 text-blue-600 transition-transform dark:text-blue-400", | |
| 3435 | − snoozedShelfExpanded && "rotate-180", | |
| 3436 | − )} | |
| 3437 | − /> | |
| 3438 | − </button> | |
| 3439 | − </li>, | |
| 3440 | − ); | |
| 3441 | − for (const thread of visibleSnoozedThreads) { | |
| 3442 | − items.push(renderThreadRow(thread, "snoozed")); | |
| 3443 | − } | |
| 3444 | − } | |
| 3445 | − if (settledThreads.length > 0) { | |
| 3446 | − items.push( | |
| 3447 | − <li | |
| 3448 | − key="settled-shelf-header" | |
| 3449 | − data-thread-selection-safe | |
| 3450 | − className="list-none" | |
| 3451 | − > | |
| 3452 | − <button | |
| 3453 | − type="button" | |
| 3454 | − onClick={toggleSettledShelf} | |
| 3455 | − aria-expanded={settledShelfExpanded} | |
| 3456 | − data-testid="sidebar-v2-settled-shelf-toggle" | |
| 3457 | − className="mb-1 mt-3 flex w-full cursor-pointer items-center gap-2 px-2.5 text-left" | |
| 3458 | − > | |
| 3459 | − <span className="text-xs font-medium text-muted-foreground/50"> | |
| 3460 | − {settledShelfExpanded | |
| 3461 | − ? "Settled" | |
| 3462 | − : `Settled (${settledThreads.length})`} | |
| 3463 | − </span> | |
| 3464 | − <span className="h-px flex-1 bg-sidebar-border/60" /> | |
| 3465 | − <ChevronDownIcon | |
| 3466 | − aria-hidden | |
| 3467 | − className={cn( | |
| 3468 | − "size-3 text-muted-foreground/50 transition-transform", | |
| 3469 | − settledShelfExpanded && "rotate-180", | |
| 3470 | − )} | |
| 3471 | − /> | |
| 3472 | − </button> | |
| 3473 | − </li>, | |
| 3474 | − ); | |
| 3475 | − } | |
| 3476 | − for (const thread of renderedSettledThreads) { | |
| 3477 | − items.push(renderThreadRow(thread, "settled")); | |
| 3478 | − } | |
| 3479 | − return items; | |
| 3480 | − })()} | |
| 3481 | − {settledShelfExpanded && hiddenSettledCount > 0 ? ( | |
| 3482 | − <li className="list-none"> | |
| 3483 | − <button | |
| 3484 | − type="button" | |
| 3485 | − onClick={showMoreSettled} | |
| 3486 | − className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground/55 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 3487 | − > | |
| 3488 | − <PlusIcon aria-hidden className="size-4 shrink-0" /> | |
| 3489 | − Show {Math.min(hiddenSettledCount, SETTLED_TAIL_PAGE_COUNT)} more | |
| 3490 | − </button> | |
| 3491 | − </li> | |
| 3492 | − ) : null} | |
| 3493 | − </ul> | |
| 3494 | − </TooltipProvider> | |
| 3495 | − ) : null} | |
| 3496 | − {!isSearchingThreads && | |
| 3497 | − pinnedThreads.length + | |
| 3498 | − activeThreads.length + | |
| 3499 | − snoozedThreads.length + | |
| 3500 | − settledThreads.length === | |
| 3501 | − 0 ? ( | |
| 3502 | − <div className="flex flex-col items-center gap-2 px-2 py-6 text-center text-xs text-muted-foreground/60"> | |
| 3503 | − {projects.length === 0 ? ( | |
| 3504 | − <> | |
| 3505 | − <span>No projects yet</span> | |
| 3506 | − <button | |
| 3507 | − type="button" | |
| 3508 | − onClick={openAddProjectCommandPalette} | |
| 3509 | − className="inline-flex items-center gap-1.5 rounded-md border border-sidebar-border px-2.5 py-1 text-[11px] font-medium text-sidebar-muted-foreground transition-colors hover:bg-sidebar-row-hover hover:text-sidebar-foreground" | |
| 3510 | − > | |
| 3511 | − <PlusIcon className="-mx-0.5 size-3" /> | |
| 3512 | − Add project | |
| 3513 | − </button> | |
| 3514 | − </> | |
| 3515 | − ) : scopedProjectGroup ? ( | |
| 3516 | − `No threads in ${scopedProjectGroup.displayName} yet` | |
| 3517 | − ) : ( | |
| 3518 | − "No threads yet" | |
| 3519 | − )} | |
| 3520 | − </div> | |
| 3521 | − ) : null} | |
| 3522 | − </SidebarGroup> | |
| 3523 | − </SidebarContent> | |
| 3524 | − <Dialog | |
| 3525 | − open={projectActionsTarget !== null} | |
| 3526 | − onOpenChange={(open) => { | |
| 3527 | − if (!open) setProjectActionsTarget(null); | |
| 3528 | − }} | |
| 3529 | − > | |
| 3530 | − <DialogPopup className="max-w-xl"> | |
| 3531 | − <DialogHeader className="gap-3 pb-1!"> | |
| 3532 | − <DialogTitle className="text-balance">Project settings</DialogTitle> | |
| 3533 | − <DialogDescription className="sr-only"> | |
| 3534 | − Manage project names, grouping rules, and environments. | |
| 3535 | − </DialogDescription> | |
| 3536 | − <div className="grid gap-1.5 text-base text-muted-foreground"> | |
| 3537 | − {projectActionsTarget?.memberProjects.map((member) => ( | |
| 3538 | − <div key={member.physicalProjectKey} className="flex min-w-0 items-center gap-3"> | |
| 3539 | − <span className="flex min-w-0 items-center gap-1"> | |
| 3540 | − <FolderIcon className="size-3.5 shrink-0 opacity-60" /> | |
| 3541 | − <span className="min-w-0 truncate font-mono">{member.workspaceRoot}</span> | |
| 3542 | − <Button | |
| 3543 | − size="icon-xs" | |
| 3544 | − variant="ghost" | |
| 3545 | − className="size-4 shrink-0 rounded-sm" | |
| 3546 | − aria-label="Copy project path" | |
| 3547 | − title="Copy project path" | |
| 3548 | − onClick={() => | |
| 3549 | − copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot }) | |
| 3550 | − } | |
| 3551 | − > | |
| 3552 | − <CopyIcon className="size-3.5" /> | |
| 3553 | − </Button> | |
| 3554 | − </span> | |
| 3555 | − <span className="flex min-w-0 shrink-0 items-center gap-1"> | |
| 3556 | − <ServerIcon className="size-3.5 shrink-0 opacity-60" /> | |
| 3557 | − <span className="min-w-0 truncate"> | |
| 3558 | − {member.environmentLabel ?? "Current environment"} | |
| 3559 | − </span> | |
| 3560 | − </span> | |
| 3561 | − </div> | |
| 3562 | − ))} | |
| 3563 | − </div> | |
| 3564 | − </DialogHeader> | |
| 3565 | − <DialogPanel className="p-0"> | |
| 3566 | − <div className="divide-y divide-border/60"> | |
| 3567 | − {projectActionsTarget?.memberProjects.map((member) => ( | |
| 3568 | − <section | |
| 3569 | − key={member.physicalProjectKey} | |
| 3570 | − className="grid min-w-0 gap-5 px-6 pb-5 pt-2 sm:gap-4 sm:pb-4 sm:pt-2" | |
| 3571 | − > | |
| 3572 | − <div className="grid gap-4 sm:grid-cols-2 sm:gap-3"> | |
| 3573 | − <label className="grid min-w-0 gap-1.5"> | |
| 3574 | − <span className="font-medium text-foreground">Project name</span> | |
| 3575 | − <Input | |
| 3576 | − key={`${member.physicalProjectKey}:${member.title}`} | |
| 3577 | − aria-label={`Project name in ${member.environmentLabel ?? "current environment"}`} | |
| 3578 | − defaultValue={member.title} | |
| 3579 | − onBlur={(event) => { | |
| 3580 | − void renameProjectMember(member, event.currentTarget.value); | |
| 3581 | − }} | |
| 3582 | − onKeyDown={(event) => { | |
| 3583 | − if (event.key === "Enter") event.currentTarget.blur(); | |
| 3584 | − }} | |
| 3585 | − /> | |
| 3586 | − </label> | |
| 3587 | − <label className="grid min-w-0 gap-1.5"> | |
| 3588 | − <span className="font-medium text-foreground">Grouping rule</span> | |
| 3589 | − <Select | |
| 3590 | − value={ | |
| 3591 | − projectGroupingSettings.sidebarProjectGroupingOverrides?.[ | |
| 3592 | − deriveProjectGroupingOverrideKey(member) | |
| 3593 | − ] ?? "inherit" | |
| 3594 | − } | |
| 3595 | − onValueChange={(value) => { | |
| 3596 | − if ( | |
| 3597 | − value === "inherit" || | |
| 3598 | − value === "repository" || | |
| 3599 | − value === "repository_path" || | |
| 3600 | − value === "separate" | |
| 3601 | − ) { | |
| 3602 | − updateProjectGroupingPreference(member, value); | |
| 3603 | − } | |
| 3604 | − }} | |
| 3605 | − > | |
| 3606 | − <SelectTrigger | |
| 3607 | − className="w-full sm:min-h-7.5" | |
| 3608 | − aria-label={`Grouping rule for ${member.environmentLabel ?? "current environment"}`} | |
| 3609 | − > | |
| 3610 | − <SelectValue> | |
| 3611 | − {(() => { | |
| 3612 | − const selection = | |
| 3613 | − projectGroupingSettings.sidebarProjectGroupingOverrides?.[ | |
| 3614 | − deriveProjectGroupingOverrideKey(member) | |
| 3615 | − ] ?? "inherit"; | |
| 3616 | − return selection === "inherit" | |
| 3617 | − ? `Default (${PROJECT_GROUPING_MODE_LABELS[projectGroupingSettings.sidebarProjectGroupingMode]})` | |
| 3618 | − : PROJECT_GROUPING_MODE_LABELS[selection]; | |
| 3619 | − })()} | |
| 3620 | − </SelectValue> | |
| 3621 | − </SelectTrigger> | |
| 3622 | − <SelectPopup align="start" alignItemWithTrigger={false}> | |
| 3623 | − <SelectItem hideIndicator value="inherit"> | |
| 3624 | − Use global default | |
| 3625 | − </SelectItem> | |
| 3626 | − <SelectItem hideIndicator value="repository"> | |
| 3627 | − {PROJECT_GROUPING_MODE_LABELS.repository} | |
| 3628 | − </SelectItem> | |
| 3629 | − <SelectItem hideIndicator value="repository_path"> | |
| 3630 | − {PROJECT_GROUPING_MODE_LABELS.repository_path} | |
| 3631 | − </SelectItem> | |
| 3632 | − <SelectItem hideIndicator value="separate"> | |
| 3633 | − {PROJECT_GROUPING_MODE_LABELS.separate} | |
| 3634 | − </SelectItem> | |
| 3635 | − </SelectPopup> | |
| 3636 | − </Select> | |
| 3637 | − </label> | |
| 3638 | − </div> | |
| 3639 | − {projectActionsTarget.memberProjects.length > 1 ? ( | |
| 3640 | − <div className="flex justify-end"> | |
| 3641 | − <Button | |
| 3642 | − size="sm" | |
| 3643 | − variant="ghost" | |
| 3644 | − className="text-destructive-foreground hover:bg-destructive/8 hover:text-destructive-foreground" | |
| 3645 | − onClick={() => { | |
| 3646 | − const projectGroup = projectActionsTarget; | |
| 3647 | − setProjectActionsTarget(null); | |
| 3648 | − void handleRemoveProjectMembers(projectGroup, [member]); | |
| 3649 | − }} | |
| 3650 | − > | |
| 3651 | − <Trash2Icon /> | |
| 3652 | − Remove project | |
| 3653 | − </Button> | |
| 3654 | − </div> | |
| 3655 | − ) : null} | |
| 3656 | − </section> | |
| 3657 | − ))} | |
| 3658 | − </div> | |
| 3659 | − {projectActionsTarget && projectActionsTarget.memberProjects.length > 1 ? ( | |
| 3660 | − <div className="flex flex-col gap-3 border-t border-border/60 bg-muted/32 px-6 py-4 sm:flex-row sm:items-center sm:justify-between"> | |
| 3661 | − <div className="min-w-0"> | |
| 3662 | − <p className="text-base font-medium text-foreground sm:text-sm"> | |
| 3663 | − Remove this project everywhere | |
| 3664 | − </p> | |
| 3665 | − <p className="text-base text-pretty text-muted-foreground sm:text-sm"> | |
| 3666 | − Deletes all grouped entries and their conversation history. | |
| 3667 | − </p> | |
| 3668 | − </div> | |
| 3669 | − <Button | |
| 3670 | − size="sm" | |
| 3671 | − variant="destructive-outline" | |
| 3672 | − className="shrink-0" | |
| 3673 | − onClick={() => { | |
| 3674 | − const projectGroup = projectActionsTarget; | |
| 3675 | − setProjectActionsTarget(null); | |
| 3676 | − void handleRemoveProjectMembers(projectGroup, projectGroup.memberProjects); | |
| 3677 | − }} | |
| 3678 | − > | |
| 3679 | − <Trash2Icon /> | |
| 3680 | − Remove all entries | |
| 3681 | − </Button> | |
| 3682 | − </div> | |
| 3683 | − ) : null} | |
| 3684 | − </DialogPanel> | |
| 3685 | − <DialogFooter | |
| 3686 | − variant="bare" | |
| 3687 | − className={cn( | |
| 3688 | − projectActionsTarget?.memberProjects.length === 1 && "sm:justify-between", | |
| 3689 | − )} | |
| 3690 | − > | |
| 3691 | − {projectActionsTarget?.memberProjects.length === 1 ? ( | |
| 3692 | − <Button | |
| 3693 | − variant="destructive-outline" | |
| 3694 | − onClick={() => { | |
| 3695 | − const projectGroup = projectActionsTarget; | |
| 3696 | − setProjectActionsTarget(null); | |
| 3697 | − void handleRemoveProjectMembers(projectGroup, projectGroup.memberProjects); | |
| 3698 | − }} | |
| 3699 | − > | |
| 3700 | − <Trash2Icon /> | |
| 3701 | − Remove project | |
| 3702 | − </Button> | |
| 3703 | − ) : null} | |
| 3704 | − <Button onClick={() => setProjectActionsTarget(null)}>Close</Button> | |
| 3705 | − </DialogFooter> | |
| 3706 | − </DialogPopup> | |
| 3707 | − </Dialog> | |
| 3708 | − <SidebarChromeFooter /> | |
| 3709 | − </> | |
| 3710 | − ); | |
| 3711 | −} | |
| @@ -66,7 +66,11 @@ import { terminalEnvironment } from "../state/terminal"; · 65 unmodified lines | ||
| 66 | 66 | import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview"; |
| 67 | 67 | import { useAtomCommand } from "../state/use-atom-command"; |
| 68 | 68 | import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut"; |
| 69 | −import { resolveTerminalFontPreference, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../appearanceFonts"; | |
| 69 | +import { | |
| 70 | + resolveTerminalFontPreference, | |
| 71 | + resolveTerminalFontSizePreference, | |
| 72 | + TYPOGRAPHY_ADVANCED_STORAGE_KEY, | |
| 73 | +} from "../appearanceFonts"; | |
| 70 | 74 | |
| 71 | 75 | const MIN_DRAWER_HEIGHT = 180; |
| 72 | 76 | const MAX_DRAWER_HEIGHT_RATIO = 0.75; |
| @@ -341,7 +345,13 @@ export function TerminalViewport({ · 268 unmodified lines | ||
| 341 | 345 | terminal: settings.fontFamilyTerminal, |
| 342 | 346 | }), |
| 343 | 347 | ); |
| 344 | − const terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal); | |
| 348 | + const terminalFontSize = useClientSettings((settings) => | |
| 349 | + resolveTerminalFontSizePreference({ | |
| 350 | + advanced: advancedTypography, | |
| 351 | + code: settings.fontSizeCode, | |
| 352 | + terminal: settings.fontSizeTerminal, | |
| 353 | + }), | |
| 354 | + ); | |
| 345 | 355 | const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize }); |
| 346 | 356 | const terminalSession = useAttachedTerminalSession({ |
| 347 | 357 | environmentId, |
| @@ -1,6 +1,64 @@ | ||
| 1 | −import { describe, expect, it } from "vite-plus/test"; | |
| 1 | +import { createElement } from "react"; | |
| 2 | +import { renderToStaticMarkup } from "react-dom/server"; | |
| 3 | +import { describe, expect, it, vi } from "vite-plus/test"; | |
| 2 | 4 | |
| 3 | −import { formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions"; | |
| 5 | +vi.mock("~/hooks/useSettings", () => ({ | |
| 6 | + useEnvironmentIdentificationMode: () => "none", | |
| 7 | +})); | |
| 8 | +vi.mock("../SidebarStageBackdrop", () => ({ | |
| 9 | + StageBackdropButtonArt: () => null, | |
| 10 | + useSidebarStageBackdropVariant: () => null, | |
| 11 | +})); | |
| 12 | + | |
| 13 | +import { ComposerPrimaryActions, formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions"; | |
| 14 | + | |
| 15 | +function renderPendingActions(isRunning: boolean) { | |
| 16 | + return renderToStaticMarkup( | |
| 17 | + createElement(ComposerPrimaryActions, { | |
| 18 | + compact: true, | |
| 19 | + pendingAction: { | |
| 20 | + questionIndex: 0, | |
| 21 | + isLastQuestion: true, | |
| 22 | + canAdvance: true, | |
| 23 | + isResponding: false, | |
| 24 | + isComplete: true, | |
| 25 | + }, | |
| 26 | + isRunning, | |
| 27 | + showPlanFollowUpPrompt: false, | |
| 28 | + promptHasText: false, | |
| 29 | + isSendBusy: false, | |
| 30 | + sendDisabledReason: null, | |
| 31 | + isConnecting: false, | |
| 32 | + isEnvironmentUnavailable: false, | |
| 33 | + isPreparingWorktree: false, | |
| 34 | + hasSendableContent: false, | |
| 35 | + onPreviousPendingQuestion: () => {}, | |
| 36 | + onInterrupt: () => {}, | |
| 37 | + onImplementPlanInNewThread: () => {}, | |
| 38 | + }), | |
| 39 | + ); | |
| 40 | +} | |
| 41 | + | |
| 42 | +function renderStandaloneStop() { | |
| 43 | + return renderToStaticMarkup( | |
| 44 | + createElement(ComposerPrimaryActions, { | |
| 45 | + compact: true, | |
| 46 | + pendingAction: null, | |
| 47 | + isRunning: true, | |
| 48 | + showPlanFollowUpPrompt: false, | |
| 49 | + promptHasText: false, | |
| 50 | + isSendBusy: false, | |
| 51 | + sendDisabledReason: null, | |
| 52 | + isConnecting: false, | |
| 53 | + isEnvironmentUnavailable: false, | |
| 54 | + isPreparingWorktree: false, | |
| 55 | + hasSendableContent: false, | |
| 56 | + onPreviousPendingQuestion: () => {}, | |
| 57 | + onInterrupt: () => {}, | |
| 58 | + onImplementPlanInNewThread: () => {}, | |
| 59 | + }), | |
| 60 | + ); | |
| 61 | +} | |
| 4 | 62 | |
| 5 | 63 | describe("formatPendingPrimaryActionLabel", () => { |
| 6 | 64 | it("returns 'Submitting...' while responding", () => { |
| @@ -91,3 +149,19 @@ describe("formatPendingPrimaryActionLabel", () => { · 84 unmodified lines | ||
| 91 | 149 | ).toBe("Submit answers"); |
| 92 | 150 | }); |
| 93 | 151 | }); |
| 152 | + | |
| 153 | +describe("ComposerPrimaryActions", () => { | |
| 154 | + it("offers Stop generation while a running turn is waiting for user input", () => { | |
| 155 | + expect(renderPendingActions(true)).toContain('aria-label="Stop generation"'); | |
| 156 | + }); | |
| 157 | + | |
| 158 | + it("does not offer Stop generation for a pending request without a running turn", () => { | |
| 159 | + expect(renderPendingActions(false)).not.toContain('aria-label="Stop generation"'); | |
| 160 | + }); | |
| 161 | + | |
| 162 | + it("matches the small pending action size without changing the standalone size", () => { | |
| 163 | + expect(renderPendingActions(true)).toContain("size-8 sm:size-7"); | |
| 164 | + expect(renderStandaloneStop()).toContain("size-8 sm:h-8 sm:w-8"); | |
| 165 | + expect(renderStandaloneStop()).not.toContain("sm:size-7"); | |
| 166 | + }); | |
| 167 | +}); | |
| @@ -75,9 +75,27 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ · 74 unmodified lines | ||
| 75 | 75 | : undefined; |
| 76 | 76 | const isSendDisabled = sendDisabledReason !== null; |
| 77 | 77 | |
| 78 | + const renderStopGenerationButton = (insidePendingAction: boolean) => ( | |
| 79 | + <button | |
| 80 | + type="button" | |
| 81 | + className={cn( | |
| 82 | + "flex cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none", | |
| 83 | + insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8", | |
| 84 | + )} | |
| 85 | + {...pointerFocusProps} | |
| 86 | + onClick={onInterrupt} | |
| 87 | + aria-label="Stop generation" | |
| 88 | + > | |
| 89 | + <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true"> | |
| 90 | + <rect x="2" y="2" width="8" height="8" rx="1.5" /> | |
| 91 | + </svg> | |
| 92 | + </button> | |
| 93 | + ); | |
| 94 | + | |
| 78 | 95 | if (pendingAction) { |
| 79 | 96 | return ( |
| 80 | 97 | <div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}> |
| 98 | + {isRunning ? renderStopGenerationButton(true) : null} | |
| 81 | 99 | {pendingAction.questionIndex > 0 ? ( |
| 82 | 100 | compact ? ( |
| 83 | 101 | <Button |
| @@ -130,19 +148,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ · 46 unmodified lines | ||
| 130 | 148 | } |
| 131 | 149 | |
| 132 | 150 | if (isRunning) { |
| 133 | − return ( | |
| 134 | − <button | |
| 135 | − type="button" | |
| 136 | − className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none sm:h-8 sm:w-8" | |
| 137 | − {...pointerFocusProps} | |
| 138 | − onClick={onInterrupt} | |
| 139 | − aria-label="Stop generation" | |
| 140 | − > | |
| 141 | − <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true"> | |
| 142 | − <rect x="2" y="2" width="8" height="8" rx="1.5" /> | |
| 143 | − </svg> | |
| 144 | − </button> | |
| 145 | − ); | |
| 151 | + return renderStopGenerationButton(false); | |
| 146 | 152 | } |
| 147 | 153 | |
| 148 | 154 | if (showPlanFollowUpPrompt) { |
| @@ -1,132 +0,0 @@ | ||
| 1 | −import { useEffect, useState } from "react"; | |
| 2 | − | |
| 3 | −import { | |
| 4 | − useClientSettings, | |
| 5 | − useSidebarV2Enabled, | |
| 6 | − useUpdateClientSettings, | |
| 7 | −} from "../../hooks/useSettings"; | |
| 8 | −import { Input } from "../ui/input"; | |
| 9 | −import { Switch } from "../ui/switch"; | |
| 10 | −import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; | |
| 11 | −import { searchableSetting } from "./settingsSearch"; | |
| 12 | − | |
| 13 | −const AUTO_SETTLE_MIN_DAYS = 1; | |
| 14 | −const AUTO_SETTLE_MAX_DAYS = 90; | |
| 15 | −const AUTO_SETTLE_DEFAULT_DAYS = 3; | |
| 16 | − | |
| 17 | −function AutoSettleDaysInput({ | |
| 18 | − value, | |
| 19 | − onCommit, | |
| 20 | −}: { | |
| 21 | − value: number; | |
| 22 | − onCommit: (days: number) => void; | |
| 23 | −}) { | |
| 24 | − // Local draft so the field can be emptied mid-edit; the setting only moves | |
| 25 | − // on valid input and snaps back to the persisted value on blur. | |
| 26 | − const [draft, setDraft] = useState(String(value)); | |
| 27 | − useEffect(() => { | |
| 28 | − setDraft(String(value)); | |
| 29 | − }, [value]); | |
| 30 | − | |
| 31 | − return ( | |
| 32 | − <Input | |
| 33 | − type="number" | |
| 34 | − min={AUTO_SETTLE_MIN_DAYS} | |
| 35 | − max={AUTO_SETTLE_MAX_DAYS} | |
| 36 | − className="w-full sm:w-24" | |
| 37 | − value={draft} | |
| 38 | − onChange={(event) => { | |
| 39 | − setDraft(event.target.value); | |
| 40 | − // Number(), not parseInt: "3.5" must be rejected (not truncated to a | |
| 41 | − // committed 3 while the field shows 3.5) — commit only when the | |
| 42 | − // persisted value matches the displayed one. | |
| 43 | − const parsed = Number(event.target.value); | |
| 44 | − if ( | |
| 45 | − Number.isInteger(parsed) && | |
| 46 | − parsed >= AUTO_SETTLE_MIN_DAYS && | |
| 47 | − parsed <= AUTO_SETTLE_MAX_DAYS | |
| 48 | − ) { | |
| 49 | − onCommit(parsed); | |
| 50 | − } | |
| 51 | − }} | |
| 52 | − onBlur={() => setDraft(String(value))} | |
| 53 | − aria-label="Days of inactivity before auto-settle" | |
| 54 | − /> | |
| 55 | − ); | |
| 56 | −} | |
| 57 | − | |
| 58 | −export function BetaSettingsPanel() { | |
| 59 | − const sidebarV2Enabled = useSidebarV2Enabled(); | |
| 60 | − const sidebarAutoSettleAfterDays = useClientSettings( | |
| 61 | − (settings) => settings.sidebarAutoSettleAfterDays, | |
| 62 | − ); | |
| 63 | − const planModeEnabled = useClientSettings((settings) => settings.planModeEnabled); | |
| 64 | − const updateSettings = useUpdateClientSettings(); | |
| 65 | − | |
| 66 | − return ( | |
| 67 | − <SettingsPageContainer> | |
| 68 | − <SettingsSection title="Beta features"> | |
| 69 | − <SettingsRow | |
| 70 | − {...searchableSetting("sidebar-v2")} | |
| 71 | − description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time." | |
| 72 | − control={ | |
| 73 | − <Switch | |
| 74 | − checked={sidebarV2Enabled} | |
| 75 | − // Touching the switch pins the choice, so a nightly build that | |
| 76 | − // defaults v2 on does not flip it back after the user opts out. | |
| 77 | − onCheckedChange={(checked) => | |
| 78 | − updateSettings({ | |
| 79 | − sidebarV2Enabled: Boolean(checked), | |
| 80 | − sidebarV2ConfiguredByUser: true, | |
| 81 | − }) | |
| 82 | − } | |
| 83 | − aria-label="Enable the sidebar v2 beta" | |
| 84 | − /> | |
| 85 | − } | |
| 86 | − /> | |
| 87 | − {sidebarV2Enabled ? ( | |
| 88 | − <> | |
| 89 | − <SettingsRow | |
| 90 | − title={searchableSetting("auto-settle-inactive-threads").title} | |
| 91 | − description="Threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle." | |
| 92 | − control={ | |
| 93 | − <Switch | |
| 94 | − checked={sidebarAutoSettleAfterDays !== null} | |
| 95 | − onCheckedChange={(checked) => | |
| 96 | − updateSettings({ | |
| 97 | − sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null, | |
| 98 | − }) | |
| 99 | − } | |
| 100 | − aria-label="Auto-settle inactive threads" | |
| 101 | − /> | |
| 102 | − } | |
| 103 | − /> | |
| 104 | − {sidebarAutoSettleAfterDays !== null ? ( | |
| 105 | − <SettingsRow | |
| 106 | − title="Days of inactivity before auto-settle" | |
| 107 | − description="Any new activity un-settles a thread automatically." | |
| 108 | − control={ | |
| 109 | − <AutoSettleDaysInput | |
| 110 | − value={sidebarAutoSettleAfterDays} | |
| 111 | − onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })} | |
| 112 | − /> | |
| 113 | − } | |
| 114 | − /> | |
| 115 | − ) : null} | |
| 116 | − </> | |
| 117 | − ) : null} | |
| 118 | − <SettingsRow | |
| 119 | − {...searchableSetting("restore-plan-mode")} | |
| 120 | − description="Legacy feature. Brings back the Build/Plan toggle in the composer along with the /plan and /default commands and the Shift+Tab shortcut. While off, every thread runs in build mode." | |
| 121 | − control={ | |
| 122 | − <Switch | |
| 123 | − checked={planModeEnabled} | |
| 124 | − onCheckedChange={(checked) => updateSettings({ planModeEnabled: Boolean(checked) })} | |
| 125 | − aria-label="Restore plan mode (legacy)" | |
| 126 | − /> | |
| 127 | − } | |
| 128 | − /> | |
| 129 | − </SettingsSection> | |
| 130 | − </SettingsPageContainer> | |
| 131 | − ); | |
| 132 | −} | |
| @@ -1,4 +1,4 @@ | ||
| 1 | −import { ArchiveIcon, ArchiveX, LoaderIcon, SettingsIcon } from "lucide-react"; | |
| 1 | +import { ArchiveIcon, ArchiveX, ChevronRightIcon, LoaderIcon, SettingsIcon } from "lucide-react"; | |
| 2 | 2 | import { Link } from "@tanstack/react-router"; |
| 3 | 3 | import type { CSSProperties, ReactNode } from "react"; |
| 4 | 4 | import { useCallback, useEffect, useMemo, useRef, useState } from "react"; |
| @@ -24,11 +24,13 @@ import { · 19 unmodified lines | ||
| 24 | 24 | MAX_GLASS_OPACITY, |
| 25 | 25 | MAX_INTERFACE_FONT_SIZE, |
| 26 | 26 | MAX_PROMPT_FONT_SIZE, |
| 27 | + MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, | |
| 27 | 28 | MAX_TERMINAL_FONT_SIZE, |
| 28 | 29 | MIN_CODE_FONT_SIZE, |
| 29 | 30 | MIN_GLASS_OPACITY, |
| 30 | 31 | MIN_INTERFACE_FONT_SIZE, |
| 31 | 32 | MIN_PROMPT_FONT_SIZE, |
| 33 | + MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, | |
| 32 | 34 | MIN_TERMINAL_FONT_SIZE, |
| 33 | 35 | } from "@t3tools/contracts/settings"; |
| 34 | 36 | import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; |
| @@ -79,6 +81,7 @@ import { useProjects } from "../../state/entities"; · 44 unmodified lines | ||
| 79 | 81 | import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; |
| 80 | 82 | import { formatRelativeTimeLabel } from "../../timestampFormat"; |
| 81 | 83 | import { Button } from "../ui/button"; |
| 84 | +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; | |
| 82 | 85 | import { |
| 83 | 86 | Dialog, |
| 84 | 87 | DialogDescription, |
| @@ -97,6 +100,7 @@ import { · 12 unmodified lines | ||
| 97 | 100 | isMonospaceFamily, |
| 98 | 101 | resolveDefaultFamilyLabel, |
| 99 | 102 | resolveTerminalFontPreference, |
| 103 | + resolveTerminalFontSizePreference, | |
| 100 | 104 | TYPOGRAPHY_ADVANCED_STORAGE_KEY, |
| 101 | 105 | } from "../../appearanceFonts"; |
| 102 | 106 | import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews"; |
| @@ -462,6 +466,10 @@ export function useSettingsRestore(onRestored?: () => void) { · 359 unmodified lines | ||
| 462 | 466 | DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode |
| 463 | 467 | ? ["Project Grouping"] |
| 464 | 468 | : []), |
| 469 | + ...(settings.sidebarAutoSettleAfterDays !== | |
| 470 | + DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays | |
| 471 | + ? ["Auto-settle inactive threads"] | |
| 472 | + : []), | |
| 465 | 473 | ...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []), |
| 466 | 474 | ...(settings.fontFamilySans !== DEFAULT_UNIFIED_SETTINGS.fontFamilySans |
| 467 | 475 | ? ["Interface font"] |
| @@ -476,8 +484,9 @@ export function useSettingsRestore(onRestored?: () => void) { · 8 unmodified lines | ||
| 476 | 484 | ...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace |
| 477 | 485 | ? ["Diff whitespace changes"] |
| 478 | 486 | : []), |
| 479 | − ...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming | |
| 480 | − ? ["Assistant output"] | |
| 487 | + ...(settings.enableLegacyTokenStreaming !== | |
| 488 | + DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming | |
| 489 | + ? ["Stream token by token"] | |
| 481 | 490 | : []), |
| 482 | 491 | ...(settings.enableProviderUpdateChecks !== |
| 483 | 492 | DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks |
| @@ -521,8 +530,9 @@ export function useSettingsRestore(onRestored?: () => void) { · 37 unmodified lines | ||
| 521 | 530 | settings.fontSizePrompt, |
| 522 | 531 | settings.fontSizeTerminal, |
| 523 | 532 | settings.glassOpacity, |
| 524 | − settings.enableAssistantStreaming, | |
| 533 | + settings.enableLegacyTokenStreaming, | |
| 525 | 534 | settings.enableProviderUpdateChecks, |
| 535 | + settings.sidebarAutoSettleAfterDays, | |
| 526 | 536 | settings.sidebarProjectGroupingMode, |
| 527 | 537 | settings.sidebarThreadPreviewCount, |
| 528 | 538 | settings.timestampFormat, |
| @@ -601,7 +611,8 @@ export function useSettingsRestore(onRestored?: () => void) { · 72 unmodified lines | ||
| 601 | 611 | glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, |
| 602 | 612 | sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount, |
| 603 | 613 | sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, |
| 604 | − enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming, | |
| 614 | + sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, | |
| 615 | + enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming, | |
| 605 | 616 | enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, |
| 606 | 617 | backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity, |
| 607 | 618 | backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile, |
| @@ -1262,7 +1273,11 @@ function SimpleFontRows() { · 654 unmodified lines | ||
| 1262 | 1273 | code: settings.fontFamilyCode, |
| 1263 | 1274 | terminal: settings.fontFamilyTerminal, |
| 1264 | 1275 | })} |
| 1265 | − size={settings.fontSizeTerminal} | |
| 1276 | + size={resolveTerminalFontSizePreference({ | |
| 1277 | + advanced: false, | |
| 1278 | + code: settings.fontSizeCode, | |
| 1279 | + terminal: settings.fontSizeTerminal, | |
| 1280 | + })} | |
| 1266 | 1281 | /> |
| 1267 | 1282 | </> |
| 1268 | 1283 | } |
| @@ -1504,6 +1519,153 @@ function FontFamilySettingsRow({ · 235 unmodified lines | ||
| 1504 | 1519 | ); |
| 1505 | 1520 | } |
| 1506 | 1521 | |
| 1522 | +const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 3; | |
| 1523 | + | |
| 1524 | +function AutoSettleDaysInput({ | |
| 1525 | + value, | |
| 1526 | + onCommit, | |
| 1527 | +}: { | |
| 1528 | + value: number; | |
| 1529 | + onCommit: (days: number) => void; | |
| 1530 | +}) { | |
| 1531 | + // Local draft so the field can be emptied mid-edit; the setting only moves | |
| 1532 | + // on valid input and snaps back to the persisted value on blur. | |
| 1533 | + const [draft, setDraft] = useState(String(value)); | |
| 1534 | + useEffect(() => { | |
| 1535 | + setDraft(String(value)); | |
| 1536 | + }, [value]); | |
| 1537 | + | |
| 1538 | + return ( | |
| 1539 | + <Input | |
| 1540 | + type="number" | |
| 1541 | + min={MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS} | |
| 1542 | + max={MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS} | |
| 1543 | + className="w-full sm:w-24" | |
| 1544 | + value={draft} | |
| 1545 | + onChange={(event) => { | |
| 1546 | + setDraft(event.target.value); | |
| 1547 | + // Number(), not parseInt: "3.5" must be rejected (not truncated to a | |
| 1548 | + // committed 3 while the field shows 3.5) — commit only when the | |
| 1549 | + // persisted value matches the displayed one. | |
| 1550 | + const parsed = Number(event.target.value); | |
| 1551 | + if ( | |
| 1552 | + Number.isInteger(parsed) && | |
| 1553 | + parsed >= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS && | |
| 1554 | + parsed <= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS | |
| 1555 | + ) { | |
| 1556 | + onCommit(parsed); | |
| 1557 | + } | |
| 1558 | + }} | |
| 1559 | + onBlur={() => setDraft(String(value))} | |
| 1560 | + aria-label="Days of inactivity before auto-settle" | |
| 1561 | + /> | |
| 1562 | + ); | |
| 1563 | +} | |
| 1564 | + | |
| 1565 | +// The legacy rows sit behind the fold, so a settings-search jump has to | |
| 1566 | +// expand the section before its target can mount and scroll. | |
| 1567 | +const LEGACY_FEATURE_TARGET_IDS: ReadonlySet<string> = new Set([ | |
| 1568 | + "legacy-plan-mode", | |
| 1569 | + "legacy-token-streaming", | |
| 1570 | + "legacy-sidebar", | |
| 1571 | +]); | |
| 1572 | + | |
| 1573 | +/** | |
| 1574 | + * Retired features kept only for users who still depend on them. Collapsed by | |
| 1575 | + * default so they stay out of the everyday settings path; a settings-search | |
| 1576 | + * jump to one of the rows unfolds the section. | |
| 1577 | + */ | |
| 1578 | +function LegacyFeaturesSection() { | |
| 1579 | + const settings = usePrimarySettings(); | |
| 1580 | + const updateSettings = useUpdatePrimarySettings(); | |
| 1581 | + const [open, setOpen] = useState(false); | |
| 1582 | + const searchTargetId = useSettingsSearchTargetId(); | |
| 1583 | + // Unfold once per search jump; tracking the handled id lets the user fold | |
| 1584 | + // the section back up without the still-set target immediately reopening it. | |
| 1585 | + const lastExpandedTargetRef = useRef<string | null>(null); | |
| 1586 | + useEffect(() => { | |
| 1587 | + if (searchTargetId === null) { | |
| 1588 | + // A handled jump clears the target; forgetting it here lets a later | |
| 1589 | + // jump to the same row expand the section again. | |
| 1590 | + lastExpandedTargetRef.current = null; | |
| 1591 | + return; | |
| 1592 | + } | |
| 1593 | + if (!LEGACY_FEATURE_TARGET_IDS.has(searchTargetId)) return; | |
| 1594 | + if (lastExpandedTargetRef.current === searchTargetId) return; | |
| 1595 | + lastExpandedTargetRef.current = searchTargetId; | |
| 1596 | + setOpen(true); | |
| 1597 | + }, [searchTargetId]); | |
| 1598 | + | |
| 1599 | + return ( | |
| 1600 | + <section className="space-y-3"> | |
| 1601 | + <Collapsible open={open} onOpenChange={setOpen}> | |
| 1602 | + <CollapsibleTrigger className="group flex min-h-8 w-full items-center gap-2 px-3 sm:px-4"> | |
| 1603 | + <h2 className="text-lg font-semibold tracking-[-0.025em] text-muted-foreground transition-colors group-hover:text-foreground"> | |
| 1604 | + Legacy features | |
| 1605 | + </h2> | |
| 1606 | + <ChevronRightIcon className="size-4 text-muted-foreground transition-transform duration-200 group-data-panel-open:rotate-90" /> | |
| 1607 | + </CollapsibleTrigger> | |
| 1608 | + <CollapsiblePanel> | |
| 1609 | + <div className="relative space-y-1 overflow-visible pt-3 text-foreground"> | |
| 1610 | + <SettingsRow | |
| 1611 | + {...searchableSetting("legacy-plan-mode")} | |
| 1612 | + description="Brings back the Build/Plan toggle in the composer along with the /plan and /default commands and the Shift+Tab shortcut. While off, every thread runs in build mode." | |
| 1613 | + control={ | |
| 1614 | + <Switch | |
| 1615 | + checked={settings.planModeEnabled} | |
| 1616 | + onCheckedChange={(checked) => | |
| 1617 | + updateSettings({ planModeEnabled: Boolean(checked) }) | |
| 1618 | + } | |
| 1619 | + aria-label="Plan mode (legacy)" | |
| 1620 | + /> | |
| 1621 | + } | |
| 1622 | + /> | |
| 1623 | + <SettingsRow | |
| 1624 | + {...searchableSetting("legacy-token-streaming")} | |
| 1625 | + description="Paints assistant output token by token instead of in complete chunks. Not recommended: it is significantly slower, and long responses become harder to follow. Kept only for compatibility with the old behavior." | |
| 1626 | + control={ | |
| 1627 | + <Switch | |
| 1628 | + checked={settings.enableLegacyTokenStreaming} | |
| 1629 | + onCheckedChange={(checked) => { | |
| 1630 | + if (!checked) { | |
| 1631 | + updateSettings({ enableLegacyTokenStreaming: false }); | |
| 1632 | + return; | |
| 1633 | + } | |
| 1634 | + void (async () => { | |
| 1635 | + const api = readLocalApi(); | |
| 1636 | + const confirmed = await (api ?? ensureLocalApi()).dialogs.confirm( | |
| 1637 | + [ | |
| 1638 | + "Turn on token-by-token output?", | |
| 1639 | + "It is significantly slower than the default buffered output and hurts the reading experience. This switch exists only for backwards compatibility.", | |
| 1640 | + ].join("\n"), | |
| 1641 | + ); | |
| 1642 | + if (confirmed) updateSettings({ enableLegacyTokenStreaming: true }); | |
| 1643 | + })(); | |
| 1644 | + }} | |
| 1645 | + aria-label="Stream token by token (legacy)" | |
| 1646 | + /> | |
| 1647 | + } | |
| 1648 | + /> | |
| 1649 | + <SettingsRow | |
| 1650 | + {...searchableSetting("legacy-sidebar")} | |
| 1651 | + description="Brings back the original sidebar with per-project thread trees. The default sidebar shows one flat list: active work as rich cards, settled threads as compact rows." | |
| 1652 | + control={ | |
| 1653 | + <Switch | |
| 1654 | + checked={settings.legacySidebarEnabled} | |
| 1655 | + onCheckedChange={(checked) => | |
| 1656 | + updateSettings({ legacySidebarEnabled: Boolean(checked) }) | |
| 1657 | + } | |
| 1658 | + aria-label="Sidebar (legacy)" | |
| 1659 | + /> | |
| 1660 | + } | |
| 1661 | + /> | |
| 1662 | + </div> | |
| 1663 | + </CollapsiblePanel> | |
| 1664 | + </Collapsible> | |
| 1665 | + </section> | |
| 1666 | + ); | |
| 1667 | +} | |
| 1668 | + | |
| 1507 | 1669 | export function GeneralSettingsPanel() { |
| 1508 | 1670 | const settings = usePrimarySettings(); |
| 1509 | 1671 | const updateSettings = useUpdatePrimarySettings(); |
| @@ -1596,6 +1758,47 @@ export function GeneralSettingsPanel() { · 86 unmodified lines | ||
| 1596 | 1758 | } |
| 1597 | 1759 | /> |
| 1598 | 1760 | |
| 1761 | + <SettingsRow | |
| 1762 | + {...searchableSetting("auto-settle-inactive-threads")} | |
| 1763 | + description="Sidebar threads with no activity for this long settle automatically. Threads on merged or closed PRs always settle." | |
| 1764 | + resetAction={ | |
| 1765 | + settings.sidebarAutoSettleAfterDays !== | |
| 1766 | + DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ? ( | |
| 1767 | + <SettingResetButton | |
| 1768 | + label="auto-settle" | |
| 1769 | + onClick={() => | |
| 1770 | + updateSettings({ | |
| 1771 | + sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, | |
| 1772 | + }) | |
| 1773 | + } | |
| 1774 | + /> | |
| 1775 | + ) : null | |
| 1776 | + } | |
| 1777 | + control={ | |
| 1778 | + <Switch | |
| 1779 | + checked={settings.sidebarAutoSettleAfterDays !== null} | |
| 1780 | + onCheckedChange={(checked) => | |
| 1781 | + updateSettings({ | |
| 1782 | + sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null, | |
| 1783 | + }) | |
| 1784 | + } | |
| 1785 | + aria-label="Auto-settle inactive threads" | |
| 1786 | + /> | |
| 1787 | + } | |
| 1788 | + /> | |
| 1789 | + {settings.sidebarAutoSettleAfterDays !== null ? ( | |
| 1790 | + <SettingsRow | |
| 1791 | + title="Days of inactivity before auto-settle" | |
| 1792 | + description="Any new activity un-settles a thread automatically." | |
| 1793 | + control={ | |
| 1794 | + <AutoSettleDaysInput | |
| 1795 | + value={settings.sidebarAutoSettleAfterDays} | |
| 1796 | + onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })} | |
| 1797 | + /> | |
| 1798 | + } | |
| 1799 | + /> | |
| 1800 | + ) : null} | |
| 1801 | + | |
| 1599 | 1802 | <SettingsRow |
| 1600 | 1803 | {...searchableSetting("time-format")} |
| 1601 | 1804 | description="System default follows your browser or OS clock preference." |
| @@ -1664,33 +1867,6 @@ export function GeneralSettingsPanel() { · 62 unmodified lines | ||
| 1664 | 1867 | } |
| 1665 | 1868 | /> |
| 1666 | 1869 | |
| 1667 | − <SettingsRow | |
| 1668 | − {...searchableSetting("assistant-output")} | |
| 1669 | − description="Show token-by-token output while a response is in progress." | |
| 1670 | − resetAction={ | |
| 1671 | − settings.enableAssistantStreaming !== | |
| 1672 | − DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? ( | |
| 1673 | − <SettingResetButton | |
| 1674 | − label="assistant output" | |
| 1675 | − onClick={() => | |
| 1676 | − updateSettings({ | |
| 1677 | − enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming, | |
| 1678 | − }) | |
| 1679 | − } | |
| 1680 | − /> | |
| 1681 | − ) : null | |
| 1682 | − } | |
| 1683 | − control={ | |
| 1684 | − <Switch | |
| 1685 | − checked={settings.enableAssistantStreaming} | |
| 1686 | − onCheckedChange={(checked) => | |
| 1687 | − updateSettings({ enableAssistantStreaming: Boolean(checked) }) | |
| 1688 | − } | |
| 1689 | − aria-label="Stream assistant messages" | |
| 1690 | − /> | |
| 1691 | − } | |
| 1692 | − /> | |
| 1693 | − | |
| 1694 | 1870 | <SettingsRow |
| 1695 | 1871 | {...searchableSetting("provider-update-checks")} |
| 1696 | 1872 | description="Check installed provider CLIs for newer available versions." |
| @@ -2050,6 +2226,8 @@ export function GeneralSettingsPanel() { · 353 unmodified lines | ||
| 2050 | 2226 | } |
| 2051 | 2227 | /> |
| 2052 | 2228 | </SettingsSection> |
| 2229 | + | |
| 2230 | + <LegacyFeaturesSection /> | |
| 2053 | 2231 | </SettingsPageContainer> |
| 2054 | 2232 | ); |
| 2055 | 2233 | } |
| @@ -11,7 +11,6 @@ import { · 10 unmodified lines | ||
| 11 | 11 | ArchiveIcon, |
| 12 | 12 | ArrowLeftIcon, |
| 13 | 13 | BotIcon, |
| 14 | − FlaskConicalIcon, | |
| 15 | 14 | GitBranchIcon, |
| 16 | 15 | KeyboardIcon, |
| 17 | 16 | Link2Icon, |
| @@ -52,7 +51,6 @@ const SETTINGS_SECTION_ICONS: Readonly< · 34 unmodified lines | ||
| 52 | 51 | "/settings/providers": BotIcon, |
| 53 | 52 | "/settings/source-control": GitBranchIcon, |
| 54 | 53 | "/settings/connections": Link2Icon, |
| 55 | − "/settings/beta": FlaskConicalIcon, | |
| 56 | 54 | "/settings/archived": ArchiveIcon, |
| 57 | 55 | }; |
| 58 | 56 | |
| @@ -5,7 +5,6 @@ export type SettingsPath = · 4 unmodified lines | ||
| 5 | 5 | | "/settings/providers" |
| 6 | 6 | | "/settings/source-control" |
| 7 | 7 | | "/settings/connections" |
| 8 | − | "/settings/beta" | |
| 9 | 8 | | "/settings/archived"; |
| 10 | 9 | |
| 11 | 10 | export interface SettingsSearchItem { |
| @@ -26,7 +25,6 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = { · 14 unmodified lines | ||
| 26 | 25 | "/settings/providers": "Providers", |
| 27 | 26 | "/settings/source-control": "Source Control", |
| 28 | 27 | "/settings/connections": "Connections", |
| 29 | − "/settings/beta": "Beta", | |
| 30 | 28 | "/settings/archived": "Archive", |
| 31 | 29 | }; |
| 32 | 30 | |
| @@ -100,6 +98,11 @@ export const SETTINGS_SEARCH_ITEMS = [ · 67 unmodified lines | ||
| 100 | 98 | title: "Project grouping", |
| 101 | 99 | to: "/settings/general", |
| 102 | 100 | }, |
| 101 | + { | |
| 102 | + id: "auto-settle-inactive-threads", | |
| 103 | + title: "Auto-settle inactive threads", | |
| 104 | + to: "/settings/general", | |
| 105 | + }, | |
| 103 | 106 | { |
| 104 | 107 | id: "time-format", |
| 105 | 108 | title: "Time format", |
| @@ -110,11 +113,6 @@ export const SETTINGS_SEARCH_ITEMS = [ · 4 unmodified lines | ||
| 110 | 113 | title: "Hide whitespace changes", |
| 111 | 114 | to: "/settings/general", |
| 112 | 115 | }, |
| 113 | − { | |
| 114 | − id: "assistant-output", | |
| 115 | − title: "Assistant output", | |
| 116 | − to: "/settings/general", | |
| 117 | − }, | |
| 118 | 116 | { |
| 119 | 117 | id: "provider-update-checks", |
| 120 | 118 | title: "Provider update checks", |
| @@ -156,6 +154,21 @@ export const SETTINGS_SEARCH_ITEMS = [ · 35 unmodified lines | ||
| 156 | 154 | title: "Diagnostics", |
| 157 | 155 | to: "/settings/general", |
| 158 | 156 | }, |
| 157 | + { | |
| 158 | + id: "legacy-plan-mode", | |
| 159 | + title: "Plan mode (legacy)", | |
| 160 | + to: "/settings/general", | |
| 161 | + }, | |
| 162 | + { | |
| 163 | + id: "legacy-token-streaming", | |
| 164 | + title: "Stream token by token (legacy)", | |
| 165 | + to: "/settings/general", | |
| 166 | + }, | |
| 167 | + { | |
| 168 | + id: "legacy-sidebar", | |
| 169 | + title: "Sidebar (legacy)", | |
| 170 | + to: "/settings/general", | |
| 171 | + }, | |
| 159 | 172 | { |
| 160 | 173 | id: "keybindings", |
| 161 | 174 | title: "Keybindings", |
| @@ -176,22 +189,6 @@ export const SETTINGS_SEARCH_ITEMS = [ · 14 unmodified lines | ||
| 176 | 189 | title: "Remote environments", |
| 177 | 190 | to: "/settings/connections", |
| 178 | 191 | }, |
| 179 | − { | |
| 180 | − id: "sidebar-v2", | |
| 181 | − title: "Sidebar v2", | |
| 182 | − to: "/settings/beta", | |
| 183 | − }, | |
| 184 | − { | |
| 185 | − id: "auto-settle-inactive-threads", | |
| 186 | − title: "Auto-settle inactive threads", | |
| 187 | − to: "/settings/beta", | |
| 188 | − targetId: "sidebar-v2", | |
| 189 | − }, | |
| 190 | − { | |
| 191 | − id: "restore-plan-mode", | |
| 192 | − title: "Restore plan mode (legacy)", | |
| 193 | − to: "/settings/beta", | |
| 194 | − }, | |
| 195 | 192 | { |
| 196 | 193 | id: "archive", |
| 197 | 194 | title: "Archived threads", |
| @@ -1,4 +1,4 @@ | ||
| 1 | −import { SettingsIcon } from "lucide-react"; | |
| 1 | +import { ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react"; | |
| 2 | 2 | import { memo, useCallback } from "react"; |
| 3 | 3 | import { Link, useNavigate } from "@tanstack/react-router"; |
| 4 | 4 | |
| @@ -118,11 +118,24 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() { · 113 unmodified lines | ||
| 118 | 118 | void navigate({ to: "/settings" }); |
| 119 | 119 | }, [isMobile, navigate, setOpenMobile]); |
| 120 | 120 | |
| 121 | + const handleUsageClick = useCallback(() => { | |
| 122 | + if (isMobile) { | |
| 123 | + setOpenMobile(false); | |
| 124 | + } | |
| 125 | + void navigate({ to: "/usage" }); | |
| 126 | + }, [isMobile, navigate, setOpenMobile]); | |
| 127 | + | |
| 121 | 128 | return ( |
| 122 | 129 | <SidebarFooter className="p-[var(--sidebar-content-inset)]"> |
| 123 | 130 | <SidebarProviderUpdatePill /> |
| 124 | 131 | <SidebarUpdatePill /> |
| 125 | 132 | <SidebarMenu> |
| 133 | + <SidebarMenuItem> | |
| 134 | + <SidebarMenuButton onClick={handleUsageClick}> | |
| 135 | + <ChartNoAxesColumnIcon /> | |
| 136 | + <span>Usage</span> | |
| 137 | + </SidebarMenuButton> | |
| 138 | + </SidebarMenuItem> | |
| 126 | 139 | <SidebarMenuItem> |
| 127 | 140 | <SidebarMenuButton onClick={handleSettingsClick}> |
| 128 | 141 | <SettingsIcon /> |
| @@ -0,0 +1,454 @@ | ||
| 1 | +import type { UsageProviderKind } from "@t3tools/contracts"; | |
| 2 | +import { RefreshCwIcon } from "lucide-react"; | |
| 3 | +import { useMemo, useState } from "react"; | |
| 4 | + | |
| 5 | +import { cn } from "../../lib/utils"; | |
| 6 | +import { useUsage } from "../../state/usage"; | |
| 7 | +import { | |
| 8 | + enumerateDays, | |
| 9 | + formatCount, | |
| 10 | + formatDayShort, | |
| 11 | + formatPercent, | |
| 12 | + formatTokens, | |
| 13 | + formatUsd, | |
| 14 | + makeWindow, | |
| 15 | +} from "../../usage/usageFormat"; | |
| 16 | +import { ScrollArea } from "../ui/scroll-area"; | |
| 17 | +import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart"; | |
| 18 | +import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders"; | |
| 19 | + | |
| 20 | +const WINDOW_OPTIONS = [ | |
| 21 | + { days: 7, label: "7 days" }, | |
| 22 | + { days: 30, label: "30 days" }, | |
| 23 | + { days: 90, label: "90 days" }, | |
| 24 | +] as const; | |
| 25 | + | |
| 26 | +export function UsagePage() { | |
| 27 | + const [windowDays, setWindowDays] = useState<number>(30); | |
| 28 | + const [metric, setMetric] = useState<UsageChartMetric>("cost"); | |
| 29 | + const [breakdown, setBreakdown] = useState<"model" | "day">("model"); | |
| 30 | + | |
| 31 | + // Recomputed only when the window length changes, so a re-render does not | |
| 32 | + // shift the range and refetch every environment. | |
| 33 | + const window = useMemo(() => makeWindow(windowDays), [windowDays]); | |
| 34 | + const { merged, environments, isPending, isPartial, refresh } = useUsage(window); | |
| 35 | + | |
| 36 | + const days = useMemo( | |
| 37 | + () => enumerateDays(window.sinceDay, window.untilDay), | |
| 38 | + [window.sinceDay, window.untilDay], | |
| 39 | + ); | |
| 40 | + const recentDays = useMemo(() => merged.daily.toReversed().slice(0, 8), [merged.daily]); | |
| 41 | + | |
| 42 | + // Ranked by whatever the toggle is showing, so the bars always descend. | |
| 43 | + const orderedProviders = useMemo( | |
| 44 | + () => | |
| 45 | + merged.providers.toSorted((a, b) => | |
| 46 | + metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens, | |
| 47 | + ), | |
| 48 | + [merged.providers, metric], | |
| 49 | + ); | |
| 50 | + | |
| 51 | + const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length; | |
| 52 | + const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays; | |
| 53 | + const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens; | |
| 54 | + const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput; | |
| 55 | + | |
| 56 | + return ( | |
| 57 | + <ScrollArea className="h-full"> | |
| 58 | + <div className="mx-auto flex w-full max-w-6xl flex-col gap-8 px-6 py-6"> | |
| 59 | + <header className="flex flex-wrap items-start justify-between gap-4"> | |
| 60 | + <div className="flex flex-col gap-1"> | |
| 61 | + <h1 className="text-2xl font-semibold text-foreground">Usage</h1> | |
| 62 | + <p className="text-sm text-muted-foreground"> | |
| 63 | + {formatDayShort(window.sinceDay)} to {formatDayShort(window.untilDay)} | |
| 64 | + </p> | |
| 65 | + </div> | |
| 66 | + <div className="flex items-center gap-2"> | |
| 67 | + <div className="flex overflow-hidden rounded-md border border-border"> | |
| 68 | + {WINDOW_OPTIONS.map((option) => ( | |
| 69 | + <button | |
| 70 | + key={option.days} | |
| 71 | + type="button" | |
| 72 | + onClick={() => setWindowDays(option.days)} | |
| 73 | + className={cn( | |
| 74 | + "px-3 py-1.5 text-xs", | |
| 75 | + option.days === windowDays | |
| 76 | + ? "bg-muted text-foreground" | |
| 77 | + : "text-muted-foreground hover:text-foreground", | |
| 78 | + )} | |
| 79 | + > | |
| 80 | + {option.label} | |
| 81 | + </button> | |
| 82 | + ))} | |
| 83 | + </div> | |
| 84 | + <button | |
| 85 | + type="button" | |
| 86 | + onClick={refresh} | |
| 87 | + aria-label="Refresh usage" | |
| 88 | + className="rounded-md border border-border p-2 text-muted-foreground hover:text-foreground" | |
| 89 | + > | |
| 90 | + <RefreshCwIcon className="size-3.5" /> | |
| 91 | + </button> | |
| 92 | + </div> | |
| 93 | + </header> | |
| 94 | + | |
| 95 | + <UsageCoverageNotice | |
| 96 | + environments={environments} | |
| 97 | + duplicateSources={merged.duplicateSources} | |
| 98 | + staleEnvironments={merged.staleEnvironments} | |
| 99 | + isPartial={isPartial} | |
| 100 | + /> | |
| 101 | + | |
| 102 | + {isPending ? ( | |
| 103 | + <p className="py-16 text-center text-sm text-muted-foreground"> | |
| 104 | + Scanning provider transcripts… | |
| 105 | + </p> | |
| 106 | + ) : ( | |
| 107 | + <> | |
| 108 | + {/* Cost first: the financial answer, then the provider split. */} | |
| 109 | + <section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]"> | |
| 110 | + {/* The summary follows the chart toggle, so the headline and the | |
| 111 | + series are always reading the same units. */} | |
| 112 | + <div className="flex flex-col gap-5"> | |
| 113 | + <div className="flex flex-col gap-1"> | |
| 114 | + <span className="text-xs tracking-wide text-muted-foreground uppercase"> | |
| 115 | + {metric === "cost" ? "Raw token cost" : "Processed tokens"} | |
| 116 | + </span> | |
| 117 | + <span className="text-4xl font-semibold text-foreground tabular-nums"> | |
| 118 | + {metric === "cost" | |
| 119 | + ? `${formatUsd(merged.costUsd)}*` | |
| 120 | + : formatTokens(merged.totalTokens)} | |
| 121 | + </span> | |
| 122 | + <span className="text-xs text-muted-foreground"> | |
| 123 | + {metric === "cost" | |
| 124 | + ? "* if billed at full API rate" | |
| 125 | + : `Input, cache reads and output across ${formatCount(merged.sessions)} sessions.`} | |
| 126 | + </span> | |
| 127 | + </div> | |
| 128 | + | |
| 129 | + {orderedProviders.map((provider) => { | |
| 130 | + const share = metric === "cost" ? provider.costShare : provider.tokenShare; | |
| 131 | + return ( | |
| 132 | + <div key={provider.provider} className="flex flex-col gap-1.5"> | |
| 133 | + <div className="flex items-baseline justify-between"> | |
| 134 | + <span className="flex items-center gap-2 text-sm text-foreground"> | |
| 135 | + <ProviderMark provider={provider.provider} className="size-4" /> | |
| 136 | + {PROVIDER_LABEL[provider.provider]} | |
| 137 | + </span> | |
| 138 | + <span className="text-sm text-foreground tabular-nums"> | |
| 139 | + {metric === "cost" | |
| 140 | + ? formatUsd(provider.costUsd) | |
| 141 | + : formatTokens(provider.totalTokens)} | |
| 142 | + </span> | |
| 143 | + </div> | |
| 144 | + <div className="h-1 w-full overflow-hidden rounded-full bg-muted"> | |
| 145 | + <div | |
| 146 | + className="h-full" | |
| 147 | + style={{ | |
| 148 | + width: `${(share * 100).toFixed(1)}%`, | |
| 149 | + backgroundColor: PROVIDER_COLOR[provider.provider], | |
| 150 | + }} | |
| 151 | + /> | |
| 152 | + </div> | |
| 153 | + <span className="text-xs text-muted-foreground"> | |
| 154 | + {metric === "cost" | |
| 155 | + ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens` | |
| 156 | + : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`} | |
| 157 | + </span> | |
| 158 | + </div> | |
| 159 | + ); | |
| 160 | + })} | |
| 161 | + </div> | |
| 162 | + | |
| 163 | + <div className="flex flex-col gap-3"> | |
| 164 | + <div className="flex flex-wrap items-center justify-between gap-3"> | |
| 165 | + <h2 className="text-sm font-medium text-foreground"> | |
| 166 | + Daily {metric === "tokens" ? "processed tokens" : "cost"} | |
| 167 | + </h2> | |
| 168 | + <div className="flex items-center gap-4"> | |
| 169 | + <div className="flex overflow-hidden rounded-md border border-border"> | |
| 170 | + {(["cost", "tokens"] as const).map((option) => ( | |
| 171 | + <button | |
| 172 | + key={option} | |
| 173 | + type="button" | |
| 174 | + onClick={() => setMetric(option)} | |
| 175 | + className={cn( | |
| 176 | + "px-2.5 py-1 text-[10px] tracking-wide uppercase", | |
| 177 | + option === metric | |
| 178 | + ? "bg-muted text-foreground" | |
| 179 | + : "text-muted-foreground hover:text-foreground", | |
| 180 | + )} | |
| 181 | + > | |
| 182 | + {option} | |
| 183 | + </button> | |
| 184 | + ))} | |
| 185 | + </div> | |
| 186 | + <UsageChartLegend /> | |
| 187 | + </div> | |
| 188 | + </div> | |
| 189 | + <UsageProviderChart days={days} daily={merged.daily} metric={metric} /> | |
| 190 | + </div> | |
| 191 | + </section> | |
| 192 | + | |
| 193 | + <section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5"> | |
| 194 | + <Metric | |
| 195 | + label="Processed tokens" | |
| 196 | + value={formatTokens(merged.totalTokens)} | |
| 197 | + detail={`${formatTokens(dailyAverage)} per active day`} | |
| 198 | + /> | |
| 199 | + <Metric | |
| 200 | + label="Cached input" | |
| 201 | + value={formatTokens(merged.cachedInputTokens)} | |
| 202 | + detail={`${formatPercent(cachedShare)} of observed input`} | |
| 203 | + /> | |
| 204 | + <Metric | |
| 205 | + label="Uncached input" | |
| 206 | + value={formatTokens(merged.uncachedInputTokens)} | |
| 207 | + detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`} | |
| 208 | + /> | |
| 209 | + <Metric | |
| 210 | + label="Output" | |
| 211 | + value={formatTokens(merged.outputTokens)} | |
| 212 | + detail={`includes ${formatTokens(merged.reasoningTokens)} reasoning`} | |
| 213 | + /> | |
| 214 | + <Metric | |
| 215 | + label="Cache savings" | |
| 216 | + value={formatUsd(merged.costQuality.cacheSavingsUsd)} | |
| 217 | + detail={ | |
| 218 | + merged.costUsd > 0 | |
| 219 | + ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw token cost` | |
| 220 | + : "vs full input rates" | |
| 221 | + } | |
| 222 | + /> | |
| 223 | + </section> | |
| 224 | + | |
| 225 | + <section className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,18rem)]"> | |
| 226 | + <div className="flex flex-col gap-3"> | |
| 227 | + <div className="flex items-center justify-between gap-3"> | |
| 228 | + <h2 className="text-sm font-medium text-foreground">Breakdown</h2> | |
| 229 | + <div className="flex overflow-hidden rounded-md border border-border"> | |
| 230 | + {(["model", "day"] as const).map((option) => ( | |
| 231 | + <button | |
| 232 | + key={option} | |
| 233 | + type="button" | |
| 234 | + onClick={() => setBreakdown(option)} | |
| 235 | + className={cn( | |
| 236 | + "px-2.5 py-1 text-[10px] tracking-wide uppercase", | |
| 237 | + option === breakdown | |
| 238 | + ? "bg-muted text-foreground" | |
| 239 | + : "text-muted-foreground hover:text-foreground", | |
| 240 | + )} | |
| 241 | + > | |
| 242 | + {option} | |
| 243 | + </button> | |
| 244 | + ))} | |
| 245 | + </div> | |
| 246 | + </div> | |
| 247 | + | |
| 248 | + {breakdown === "model" ? ( | |
| 249 | + <table className="w-full text-sm"> | |
| 250 | + <thead> | |
| 251 | + <tr className="border-b border-border text-left text-xs text-muted-foreground"> | |
| 252 | + <th className="py-2 font-normal">Model</th> | |
| 253 | + <th className="py-2 text-right font-normal">Cost</th> | |
| 254 | + <th className="py-2 text-right font-normal">Share</th> | |
| 255 | + <th className="py-2 text-right font-normal">Tokens</th> | |
| 256 | + </tr> | |
| 257 | + </thead> | |
| 258 | + <tbody> | |
| 259 | + {merged.models.length === 0 ? ( | |
| 260 | + <tr> | |
| 261 | + <td colSpan={4} className="py-6 text-center text-muted-foreground"> | |
| 262 | + No activity in this window. | |
| 263 | + </td> | |
| 264 | + </tr> | |
| 265 | + ) : ( | |
| 266 | + merged.models.map((model) => ( | |
| 267 | + <tr | |
| 268 | + key={`${model.provider}:${model.model}`} | |
| 269 | + className="border-b border-border/50" | |
| 270 | + > | |
| 271 | + <td className="py-2 text-foreground"> | |
| 272 | + <span className="flex items-center gap-2"> | |
| 273 | + <ProviderMark provider={model.provider} className="size-3.5" /> | |
| 274 | + {model.model} | |
| 275 | + </span> | |
| 276 | + </td> | |
| 277 | + <td className="py-2 text-right text-foreground tabular-nums"> | |
| 278 | + {formatUsd(model.costUsd)} | |
| 279 | + </td> | |
| 280 | + <td className="py-2 text-right text-muted-foreground tabular-nums"> | |
| 281 | + {formatPercent(model.costShare)} | |
| 282 | + </td> | |
| 283 | + <td className="py-2 text-right text-muted-foreground tabular-nums"> | |
| 284 | + {formatTokens(model.totalTokens)} | |
| 285 | + </td> | |
| 286 | + </tr> | |
| 287 | + )) | |
| 288 | + )} | |
| 289 | + </tbody> | |
| 290 | + </table> | |
| 291 | + ) : ( | |
| 292 | + <table className="w-full text-sm"> | |
| 293 | + <thead> | |
| 294 | + <tr className="border-b border-border text-left text-xs text-muted-foreground"> | |
| 295 | + <th className="py-2 font-normal">Day</th> | |
| 296 | + {PROVIDER_ORDER.map((provider) => ( | |
| 297 | + <th key={provider} className="py-2 text-right font-normal"> | |
| 298 | + {PROVIDER_LABEL[provider]} | |
| 299 | + </th> | |
| 300 | + ))} | |
| 301 | + <th className="py-2 text-right font-normal">Total</th> | |
| 302 | + <th className="py-2 text-right font-normal">Tokens</th> | |
| 303 | + </tr> | |
| 304 | + </thead> | |
| 305 | + <tbody> | |
| 306 | + {recentDays.length === 0 ? ( | |
| 307 | + <tr> | |
| 308 | + <td colSpan={5} className="py-6 text-center text-muted-foreground"> | |
| 309 | + No activity in this window. | |
| 310 | + </td> | |
| 311 | + </tr> | |
| 312 | + ) : ( | |
| 313 | + recentDays.map((day) => ( | |
| 314 | + <tr key={day.day} className="border-b border-border/50"> | |
| 315 | + <td className="py-2 text-foreground">{formatDayShort(day.day)}</td> | |
| 316 | + {PROVIDER_ORDER.map((provider) => ( | |
| 317 | + <td | |
| 318 | + key={provider} | |
| 319 | + className="py-2 text-right text-muted-foreground tabular-nums" | |
| 320 | + > | |
| 321 | + {formatUsd(day.byProvider.get(provider)?.costUsd ?? 0)} | |
| 322 | + </td> | |
| 323 | + ))} | |
| 324 | + <td className="py-2 text-right text-foreground tabular-nums"> | |
| 325 | + {formatUsd(day.costUsd)} | |
| 326 | + </td> | |
| 327 | + <td className="py-2 text-right text-muted-foreground tabular-nums"> | |
| 328 | + {formatTokens(day.totalTokens)} | |
| 329 | + </td> | |
| 330 | + </tr> | |
| 331 | + )) | |
| 332 | + )} | |
| 333 | + </tbody> | |
| 334 | + </table> | |
| 335 | + )} | |
| 336 | + </div> | |
| 337 | + | |
| 338 | + <div className="flex flex-col gap-3"> | |
| 339 | + <h2 className="text-sm font-medium text-foreground">Cost quality</h2> | |
| 340 | + <dl className="flex flex-col"> | |
| 341 | + <QualityRow | |
| 342 | + label="Provider reported" | |
| 343 | + value={formatPercent(merged.costQuality.providerReportedShare)} | |
| 344 | + /> | |
| 345 | + <QualityRow | |
| 346 | + label="Model priced" | |
| 347 | + value={formatPercent(merged.costQuality.modelPricedShare)} | |
| 348 | + /> | |
| 349 | + <QualityRow | |
| 350 | + label="Unpriced" | |
| 351 | + value={formatPercent(merged.costQuality.unpricedShare)} | |
| 352 | + /> | |
| 353 | + <QualityRow | |
| 354 | + label="Cache savings" | |
| 355 | + value={formatUsd(merged.costQuality.cacheSavingsUsd)} | |
| 356 | + /> | |
| 357 | + </dl> | |
| 358 | + </div> | |
| 359 | + </section> | |
| 360 | + </> | |
| 361 | + )} | |
| 362 | + </div> | |
| 363 | + </ScrollArea> | |
| 364 | + ); | |
| 365 | +} | |
| 366 | + | |
| 367 | +/** Brand mark for the harness a row belongs to. */ | |
| 368 | +function ProviderMark({ | |
| 369 | + provider, | |
| 370 | + className, | |
| 371 | +}: { | |
| 372 | + readonly provider: UsageProviderKind; | |
| 373 | + readonly className: string; | |
| 374 | +}) { | |
| 375 | + const Mark = PROVIDER_MARK[provider]; | |
| 376 | + return <Mark className={cn("shrink-0", className)} aria-hidden />; | |
| 377 | +} | |
| 378 | + | |
| 379 | +function Metric({ | |
| 380 | + label, | |
| 381 | + value, | |
| 382 | + detail, | |
| 383 | +}: { | |
| 384 | + readonly label: string; | |
| 385 | + readonly value: string; | |
| 386 | + readonly detail: string; | |
| 387 | +}) { | |
| 388 | + return ( | |
| 389 | + <div className="flex flex-col gap-0.5 bg-background px-4 py-3"> | |
| 390 | + <span className="text-xs text-muted-foreground">{label}</span> | |
| 391 | + <span className="text-lg text-foreground tabular-nums">{value}</span> | |
| 392 | + <span className="text-xs text-muted-foreground">{detail}</span> | |
| 393 | + </div> | |
| 394 | + ); | |
| 395 | +} | |
| 396 | + | |
| 397 | +function QualityRow({ label, value }: { readonly label: string; readonly value: string }) { | |
| 398 | + return ( | |
| 399 | + <div className="flex items-center justify-between border-b border-border/50 py-2 text-sm"> | |
| 400 | + <dt className="text-muted-foreground">{label}</dt> | |
| 401 | + <dd className="text-foreground tabular-nums">{value}</dd> | |
| 402 | + </div> | |
| 403 | + ); | |
| 404 | +} | |
| 405 | + | |
| 406 | +/** | |
| 407 | + * Says plainly when the totals are incomplete: an environment still answering, | |
| 408 | + * one that failed, or one whose transcripts another environment already | |
| 409 | + * reported. | |
| 410 | + */ | |
| 411 | +function UsageCoverageNotice({ | |
| 412 | + environments, | |
| 413 | + duplicateSources, | |
| 414 | + staleEnvironments, | |
| 415 | + isPartial, | |
| 416 | +}: { | |
| 417 | + readonly environments: readonly { | |
| 418 | + environmentId: string; | |
| 419 | + label: string; | |
| 420 | + error: string | null; | |
| 421 | + isPending: boolean; | |
| 422 | + }[]; | |
| 423 | + readonly duplicateSources: readonly string[]; | |
| 424 | + readonly staleEnvironments: readonly string[]; | |
| 425 | + readonly isPartial: boolean; | |
| 426 | +}) { | |
| 427 | + const failed = environments.filter((environment) => environment.error !== null); | |
| 428 | + const stale = environments.filter((environment) => | |
| 429 | + staleEnvironments.includes(environment.environmentId), | |
| 430 | + ); | |
| 431 | + if (failed.length === 0 && stale.length === 0 && duplicateSources.length === 0 && !isPartial) { | |
| 432 | + return null; | |
| 433 | + } | |
| 434 | + | |
| 435 | + return ( | |
| 436 | + <div className="flex flex-col gap-1 border border-border px-3 py-2 text-xs text-muted-foreground"> | |
| 437 | + {isPartial ? <span>Some environments are still reporting. Totals are partial.</span> : null} | |
| 438 | + {failed.map((environment) => ( | |
| 439 | + <span key={environment.label}>{environment.label} could not report usage.</span> | |
| 440 | + ))} | |
| 441 | + {stale.map((environment) => ( | |
| 442 | + <span key={environment.label}> | |
| 443 | + {environment.label} runs an older server version and is excluded from totals. | |
| 444 | + </span> | |
| 445 | + ))} | |
| 446 | + {duplicateSources.length > 0 ? ( | |
| 447 | + <span> | |
| 448 | + Counted once across environments sharing a transcript directory:{" "} | |
| 449 | + {duplicateSources.join(", ")} | |
| 450 | + </span> | |
| 451 | + ) : null} | |
| 452 | + </div> | |
| 453 | + ); | |
| 454 | +} | |
| @@ -0,0 +1,97 @@ | ||
| 1 | +import { describe, expect, it } from "vite-plus/test"; | |
| 2 | + | |
| 3 | +import { buildDayColumns, niceScale } from "./UsageProviderChart"; | |
| 4 | + | |
| 5 | +describe("niceScale", () => { | |
| 6 | + it("never puts the peak above the top of the scale", () => { | |
| 7 | + // Regression: an earlier version stopped at the last step below the peak, | |
| 8 | + // so the tallest day was drawn past the plot and clipped. | |
| 9 | + for (const peak of [1122.71, 999, 1, 0.04, 1_400_000_000, 37.5, 5000, 100.001]) { | |
| 10 | + const { max } = niceScale(peak, 4); | |
| 11 | + expect(max, `peak ${peak}`).toBeGreaterThanOrEqual(peak); | |
| 12 | + } | |
| 13 | + }); | |
| 14 | + | |
| 15 | + it("starts at zero and ends at the maximum", () => { | |
| 16 | + const { max, ticks } = niceScale(1122.71, 4); | |
| 17 | + | |
| 18 | + expect(ticks[0]).toBe(0); | |
| 19 | + expect(ticks[ticks.length - 1]).toBeCloseTo(max, 6); | |
| 20 | + }); | |
| 21 | + | |
| 22 | + it("uses evenly spaced 1/2/5 steps", () => { | |
| 23 | + const { ticks } = niceScale(1122.71, 4); | |
| 24 | + const steps = ticks.slice(1).map((tick, index) => tick - (ticks[index] ?? 0)); | |
| 25 | + | |
| 26 | + for (const step of steps) expect(step).toBeCloseTo(steps[0] ?? 0, 6); | |
| 27 | + const [first = 0] = steps; | |
| 28 | + const normalized = first / 10 ** Math.floor(Math.log10(first)); | |
| 29 | + expect([1, 2, 5, 10]).toContain(Math.round(normalized)); | |
| 30 | + }); | |
| 31 | + | |
| 32 | + it("keeps the tick count near the requested resolution", () => { | |
| 33 | + const { ticks } = niceScale(1122.71, 4); | |
| 34 | + expect(ticks.length).toBeGreaterThanOrEqual(3); | |
| 35 | + expect(ticks.length).toBeLessThanOrEqual(7); | |
| 36 | + }); | |
| 37 | + | |
| 38 | + it("degrades to a single zero tick with no data", () => { | |
| 39 | + expect(niceScale(0, 4)).toEqual({ max: 0, ticks: [0] }); | |
| 40 | + }); | |
| 41 | +}); | |
| 42 | + | |
| 43 | +describe("buildDayColumns", () => { | |
| 44 | + const days = ["2026-08-01", "2026-08-02", "2026-08-03"]; | |
| 45 | + const byDay = new Map([ | |
| 46 | + [ | |
| 47 | + "2026-08-01", | |
| 48 | + { | |
| 49 | + day: "2026-08-01", | |
| 50 | + costUsd: 30, | |
| 51 | + totalTokens: 300, | |
| 52 | + byProvider: new Map([ | |
| 53 | + ["codex" as const, { costUsd: 10, totalTokens: 100 }], | |
| 54 | + ["claude" as const, { costUsd: 20, totalTokens: 200 }], | |
| 55 | + ]), | |
| 56 | + }, | |
| 57 | + ], | |
| 58 | + // 2026-08-02 is deliberately absent: a day with no activity. | |
| 59 | + [ | |
| 60 | + "2026-08-03", | |
| 61 | + { | |
| 62 | + day: "2026-08-03", | |
| 63 | + costUsd: 5, | |
| 64 | + totalTokens: 50, | |
| 65 | + byProvider: new Map([["claude" as const, { costUsd: 5, totalTokens: 50 }]]), | |
| 66 | + }, | |
| 67 | + ], | |
| 68 | + ]); | |
| 69 | + | |
| 70 | + it("plots each day on its own", () => { | |
| 71 | + expect(buildDayColumns(days, byDay, "cost").map((column) => column.total)).toEqual([30, 0, 5]); | |
| 72 | + }); | |
| 73 | + | |
| 74 | + it("reads the requested metric", () => { | |
| 75 | + expect(buildDayColumns(days, byDay, "tokens").map((column) => column.total)).toEqual([ | |
| 76 | + 300, 0, 50, | |
| 77 | + ]); | |
| 78 | + }); | |
| 79 | + | |
| 80 | + it("keeps band values absolute rather than cumulative", () => { | |
| 81 | + // Regression: the bands were once stack offsets, which drew Claude Code | |
| 82 | + // permanently above Codex regardless of which provider spent more. | |
| 83 | + const [first] = buildDayColumns(days, byDay, "cost"); | |
| 84 | + | |
| 85 | + expect(first?.bands).toEqual([ | |
| 86 | + { provider: "codex", value: 10 }, | |
| 87 | + { provider: "claude", value: 20 }, | |
| 88 | + ]); | |
| 89 | + }); | |
| 90 | + | |
| 91 | + it("reports the total as the sum of its bands", () => { | |
| 92 | + for (const column of buildDayColumns(days, byDay, "cost")) { | |
| 93 | + const sum = column.bands.reduce((running, band) => running + band.value, 0); | |
| 94 | + expect(column.total).toBeCloseTo(sum, 9); | |
| 95 | + } | |
| 96 | + }); | |
| 97 | +}); | |
| @@ -0,0 +1,395 @@ | ||
| 1 | +import type { UsageProviderKind } from "@t3tools/contracts"; | |
| 2 | +import { useCallback, useMemo, useRef, useState } from "react"; | |
| 3 | + | |
| 4 | +import type { DailyTotals } from "../../usage/usageMerge"; | |
| 5 | +import { formatDayShort, formatTokens, formatUsd } from "../../usage/usageFormat"; | |
| 6 | +import { PROVIDER_COLOR, PROVIDER_LABEL, PROVIDER_MARK, PROVIDER_ORDER } from "./usageProviders"; | |
| 7 | + | |
| 8 | +const VIEW_WIDTH = 960; | |
| 9 | +const VIEW_HEIGHT = 260; | |
| 10 | +const TICK_COUNT = 4; | |
| 11 | +const PLOT_TOP = 8; | |
| 12 | + | |
| 13 | +export type UsageChartMetric = "tokens" | "cost"; | |
| 14 | + | |
| 15 | +interface UsageProviderChartProps { | |
| 16 | + readonly days: readonly string[]; | |
| 17 | + readonly daily: readonly DailyTotals[]; | |
| 18 | + readonly metric: UsageChartMetric; | |
| 19 | +} | |
| 20 | + | |
| 21 | +/** One day's per-provider values, shared by the paths and the hover readout. */ | |
| 22 | +export interface DayColumn { | |
| 23 | + readonly bands: readonly { | |
| 24 | + readonly provider: UsageProviderKind; | |
| 25 | + readonly value: number; | |
| 26 | + }[]; | |
| 27 | + readonly total: number; | |
| 28 | +} | |
| 29 | + | |
| 30 | +interface Point { | |
| 31 | + readonly x: number; | |
| 32 | + readonly y: number; | |
| 33 | +} | |
| 34 | + | |
| 35 | +function valueFor( | |
| 36 | + daily: DailyTotals | undefined, | |
| 37 | + provider: UsageProviderKind, | |
| 38 | + metric: UsageChartMetric, | |
| 39 | +): number { | |
| 40 | + const entry = daily?.byProvider.get(provider); | |
| 41 | + if (entry === undefined) return 0; | |
| 42 | + return metric === "tokens" ? entry.totalTokens : entry.costUsd; | |
| 43 | +} | |
| 44 | + | |
| 45 | +/** | |
| 46 | + * Monotone cubic tangents (Fritsch-Carlson). | |
| 47 | + * | |
| 48 | + * Plain cubic smoothing overshoots on spiky daily data and would dip the area | |
| 49 | + * below zero between points, which reads as negative spend. This variant is | |
| 50 | + * shape-preserving, so a smoothed series never leaves the range of its samples. | |
| 51 | + */ | |
| 52 | +function monotoneTangents(points: readonly Point[]): readonly number[] { | |
| 53 | + const count = points.length; | |
| 54 | + if (count < 2) return [0]; | |
| 55 | + | |
| 56 | + const slopes: number[] = []; | |
| 57 | + for (let index = 0; index < count - 1; index += 1) { | |
| 58 | + const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0); | |
| 59 | + const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0); | |
| 60 | + slopes.push(dx === 0 ? 0 : dy / dx); | |
| 61 | + } | |
| 62 | + | |
| 63 | + const tangents: number[] = Array.from({ length: count }, () => 0); | |
| 64 | + tangents[0] = slopes[0] ?? 0; | |
| 65 | + tangents[count - 1] = slopes[count - 2] ?? 0; | |
| 66 | + for (let index = 1; index < count - 1; index += 1) { | |
| 67 | + const previous = slopes[index - 1] ?? 0; | |
| 68 | + const next = slopes[index] ?? 0; | |
| 69 | + tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2; | |
| 70 | + } | |
| 71 | + | |
| 72 | + for (let index = 0; index < count - 1; index += 1) { | |
| 73 | + const slope = slopes[index] ?? 0; | |
| 74 | + if (slope === 0) { | |
| 75 | + tangents[index] = 0; | |
| 76 | + tangents[index + 1] = 0; | |
| 77 | + continue; | |
| 78 | + } | |
| 79 | + const a = (tangents[index] ?? 0) / slope; | |
| 80 | + const b = (tangents[index + 1] ?? 0) / slope; | |
| 81 | + const magnitude = a * a + b * b; | |
| 82 | + if (magnitude > 9) { | |
| 83 | + const scale = 3 / Math.sqrt(magnitude); | |
| 84 | + tangents[index] = scale * a * slope; | |
| 85 | + tangents[index + 1] = scale * b * slope; | |
| 86 | + } | |
| 87 | + } | |
| 88 | + | |
| 89 | + return tangents; | |
| 90 | +} | |
| 91 | + | |
| 92 | +/** One cubic segment of a smoothed boundary. */ | |
| 93 | +interface CurveSegment { | |
| 94 | + readonly from: Point; | |
| 95 | + readonly c1: Point; | |
| 96 | + readonly c2: Point; | |
| 97 | + readonly to: Point; | |
| 98 | +} | |
| 99 | + | |
| 100 | +/** Smoothed polyline through `points`, as explicit cubic control points. */ | |
| 101 | +function smoothCurve(points: readonly Point[]): readonly CurveSegment[] { | |
| 102 | + if (points.length < 2) return []; | |
| 103 | + const tangents = monotoneTangents(points); | |
| 104 | + const segments: CurveSegment[] = []; | |
| 105 | + | |
| 106 | + for (let index = 0; index < points.length - 1; index += 1) { | |
| 107 | + const from = points[index]; | |
| 108 | + const to = points[index + 1]; | |
| 109 | + if (from === undefined || to === undefined) continue; | |
| 110 | + const dx = to.x - from.x; | |
| 111 | + segments.push({ | |
| 112 | + from, | |
| 113 | + c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 }, | |
| 114 | + c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 }, | |
| 115 | + to, | |
| 116 | + }); | |
| 117 | + } | |
| 118 | + return segments; | |
| 119 | +} | |
| 120 | + | |
| 121 | +function curvePath(segments: readonly CurveSegment[], startCommand: "M" | "L"): string { | |
| 122 | + const first = segments[0]; | |
| 123 | + if (first === undefined) return ""; | |
| 124 | + let path = `${startCommand}${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`; | |
| 125 | + for (const segment of segments) { | |
| 126 | + path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`; | |
| 127 | + } | |
| 128 | + return path; | |
| 129 | +} | |
| 130 | + | |
| 131 | +/** | |
| 132 | + * Builds a scale whose maximum is a readable 1/2/5 x 10^n step at or above the | |
| 133 | + * peak. | |
| 134 | + * | |
| 135 | + * Rounding the maximum *up* is the point: stopping at the last step below the | |
| 136 | + * peak leaves the tallest day drawn past the top of the plot, where it is | |
| 137 | + * clipped. | |
| 138 | + */ | |
| 139 | +export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } { | |
| 140 | + if (peak <= 0) return { max: 0, ticks: [0] }; | |
| 141 | + | |
| 142 | + const rawStep = peak / count; | |
| 143 | + const magnitude = 10 ** Math.floor(Math.log10(rawStep)); | |
| 144 | + const normalized = rawStep / magnitude; | |
| 145 | + const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude; | |
| 146 | + | |
| 147 | + const max = Math.ceil(peak / step) * step; | |
| 148 | + const ticks: number[] = []; | |
| 149 | + for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value); | |
| 150 | + return { max, ticks }; | |
| 151 | +} | |
| 152 | + | |
| 153 | +/** | |
| 154 | + * Turns the merged daily totals into one column per day. | |
| 155 | + * | |
| 156 | + * Values are absolute, not cumulative: the series are layered from a shared | |
| 157 | + * zero baseline rather than stacked. A stacked chart puts whichever provider is | |
| 158 | + * drawn last permanently above the other, which reads as "that one is bigger" | |
| 159 | + * even on days where it is not. | |
| 160 | + * | |
| 161 | + * The chart paths and the hover readout both consume this, so the number under | |
| 162 | + * the cursor is by construction the number that was plotted rather than a | |
| 163 | + * second derivation that can drift from it. | |
| 164 | + */ | |
| 165 | +export function buildDayColumns( | |
| 166 | + days: readonly string[], | |
| 167 | + byDay: ReadonlyMap<string, DailyTotals>, | |
| 168 | + metric: UsageChartMetric, | |
| 169 | +): readonly DayColumn[] { | |
| 170 | + return days.map((day) => { | |
| 171 | + const entry = byDay.get(day); | |
| 172 | + const bands = PROVIDER_ORDER.map((provider) => ({ | |
| 173 | + provider, | |
| 174 | + value: valueFor(entry, provider, metric), | |
| 175 | + })); | |
| 176 | + return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) }; | |
| 177 | + }); | |
| 178 | +} | |
| 179 | + | |
| 180 | +export function UsageProviderChart({ days, daily, metric }: UsageProviderChartProps) { | |
| 181 | + const byDay = useMemo(() => new Map(daily.map((entry) => [entry.day, entry])), [daily]); | |
| 182 | + const [hoverIndex, setHoverIndex] = useState<number | null>(null); | |
| 183 | + const plotRef = useRef<HTMLDivElement | null>(null); | |
| 184 | + | |
| 185 | + const { paths, ticks, stepX, toY, series } = useMemo(() => { | |
| 186 | + if (days.length === 0) { | |
| 187 | + return { | |
| 188 | + paths: [], | |
| 189 | + ticks: [0] as readonly number[], | |
| 190 | + stepX: 0, | |
| 191 | + toY: () => VIEW_HEIGHT, | |
| 192 | + series: [] as readonly DayColumn[], | |
| 193 | + }; | |
| 194 | + } | |
| 195 | + | |
| 196 | + const columns = buildDayColumns(days, byDay, metric); | |
| 197 | + | |
| 198 | + // The scale tops out at the largest single provider-day, not the largest | |
| 199 | + // sum: layered series each measure from zero, so a combined peak would | |
| 200 | + // leave the plot permanently half empty. | |
| 201 | + const peak = columns.reduce( | |
| 202 | + (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max), | |
| 203 | + 0, | |
| 204 | + ); | |
| 205 | + const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT); | |
| 206 | + const step = days.length === 1 ? 0 : VIEW_WIDTH / (days.length - 1); | |
| 207 | + // Reserve a sliver above the top gridline so the series stroke, which is | |
| 208 | + // drawn at constant screen width, is not shaved off at a peak. | |
| 209 | + const toY = (value: number) => | |
| 210 | + max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP); | |
| 211 | + | |
| 212 | + const built = PROVIDER_ORDER.map((provider, providerIndex) => { | |
| 213 | + const curve = smoothCurve( | |
| 214 | + columns.map((column, dayIndex) => ({ | |
| 215 | + x: dayIndex * step, | |
| 216 | + y: toY(column.bands[providerIndex]?.value ?? 0), | |
| 217 | + })), | |
| 218 | + ); | |
| 219 | + const line = curvePath(curve, "M"); | |
| 220 | + return { | |
| 221 | + provider, | |
| 222 | + total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0), | |
| 223 | + area: line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`, | |
| 224 | + line, | |
| 225 | + }; | |
| 226 | + }); | |
| 227 | + | |
| 228 | + // Paint the heavier series first so the lighter one is never buried under | |
| 229 | + // it. The fills are faint enough that the order barely shows, but the | |
| 230 | + // strokes are drawn in a second pass regardless, so neither can be hidden. | |
| 231 | + const ordered = [...built].sort((a, b) => b.total - a.total); | |
| 232 | + | |
| 233 | + return { paths: ordered, ticks: tickValues, stepX: step, toY, series: columns }; | |
| 234 | + }, [byDay, days, metric]); | |
| 235 | + | |
| 236 | + const format = metric === "tokens" ? formatTokens : formatUsd; | |
| 237 | + | |
| 238 | + const handleMove = useCallback( | |
| 239 | + (event: React.MouseEvent<HTMLDivElement>) => { | |
| 240 | + const bounds = plotRef.current?.getBoundingClientRect(); | |
| 241 | + if (bounds === undefined || bounds.width === 0 || days.length === 0) return; | |
| 242 | + const fraction = (event.clientX - bounds.left) / bounds.width; | |
| 243 | + const index = Math.round(fraction * (days.length - 1)); | |
| 244 | + setHoverIndex(Math.min(days.length - 1, Math.max(0, index))); | |
| 245 | + }, | |
| 246 | + [days.length], | |
| 247 | + ); | |
| 248 | + | |
| 249 | + const hoveredDay = hoverIndex === null ? undefined : days[hoverIndex]; | |
| 250 | + const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex]; | |
| 251 | + const hoverLeft = days.length <= 1 ? 0 : ((hoverIndex ?? 0) / (days.length - 1)) * 100; | |
| 252 | + | |
| 253 | + return ( | |
| 254 | + <div className="flex flex-col gap-1"> | |
| 255 | + <div className="flex gap-2"> | |
| 256 | + {/* Axis labels sit outside the plot so they stay aligned to gridlines. */} | |
| 257 | + <div className="relative h-56 w-14 shrink-0"> | |
| 258 | + {ticks.map((tick) => ( | |
| 259 | + <span | |
| 260 | + key={tick} | |
| 261 | + className="absolute right-0 -translate-y-1/2 text-[10px] text-muted-foreground tabular-nums" | |
| 262 | + style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }} | |
| 263 | + > | |
| 264 | + {tick === 0 ? "0" : format(tick)} | |
| 265 | + </span> | |
| 266 | + ))} | |
| 267 | + </div> | |
| 268 | + | |
| 269 | + <div | |
| 270 | + ref={plotRef} | |
| 271 | + className="relative h-56 flex-1" | |
| 272 | + onMouseMove={handleMove} | |
| 273 | + onMouseLeave={() => setHoverIndex(null)} | |
| 274 | + > | |
| 275 | + <svg | |
| 276 | + className="h-full w-full" | |
| 277 | + viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`} | |
| 278 | + preserveAspectRatio="none" | |
| 279 | + role="img" | |
| 280 | + aria-label={`Daily ${metric === "tokens" ? "processed tokens" : "cost"} by provider`} | |
| 281 | + > | |
| 282 | + {ticks.map((tick) => { | |
| 283 | + const y = toY(tick); | |
| 284 | + return ( | |
| 285 | + <line | |
| 286 | + key={tick} | |
| 287 | + x1={0} | |
| 288 | + x2={VIEW_WIDTH} | |
| 289 | + y1={y} | |
| 290 | + y2={y} | |
| 291 | + stroke="currentColor" | |
| 292 | + strokeWidth={1} | |
| 293 | + className="text-border" | |
| 294 | + vectorEffect="non-scaling-stroke" | |
| 295 | + /> | |
| 296 | + ); | |
| 297 | + })} | |
| 298 | + | |
| 299 | + {/* Fills first, then every stroke, so no series covers another's line. */} | |
| 300 | + {paths.map(({ provider, area }) => ( | |
| 301 | + <path key={provider} d={area} fill={PROVIDER_COLOR[provider]} fillOpacity={0.12} /> | |
| 302 | + ))} | |
| 303 | + {paths.map(({ provider, line }) => ( | |
| 304 | + <path | |
| 305 | + key={provider} | |
| 306 | + d={line} | |
| 307 | + fill="none" | |
| 308 | + stroke={PROVIDER_COLOR[provider]} | |
| 309 | + strokeWidth={2} | |
| 310 | + vectorEffect="non-scaling-stroke" | |
| 311 | + /> | |
| 312 | + ))} | |
| 313 | + | |
| 314 | + {hoverIndex === null ? null : ( | |
| 315 | + <line | |
| 316 | + x1={hoverIndex * stepX} | |
| 317 | + x2={hoverIndex * stepX} | |
| 318 | + y1={PLOT_TOP} | |
| 319 | + y2={VIEW_HEIGHT} | |
| 320 | + stroke="currentColor" | |
| 321 | + strokeWidth={1} | |
| 322 | + className="text-muted-foreground" | |
| 323 | + vectorEffect="non-scaling-stroke" | |
| 324 | + /> | |
| 325 | + )} | |
| 326 | + </svg> | |
| 327 | + | |
| 328 | + {hoveredDay === undefined ? null : ( | |
| 329 | + <div | |
| 330 | + className="pointer-events-none absolute top-0 z-10 min-w-36 border border-border bg-background/95 px-2 py-1.5 text-xs" | |
| 331 | + style={{ | |
| 332 | + left: `${hoverLeft}%`, | |
| 333 | + transform: hoverLeft > 60 ? "translateX(-100%)" : "translateX(0)", | |
| 334 | + }} | |
| 335 | + > | |
| 336 | + <div className="mb-1 text-muted-foreground">{formatDayShort(hoveredDay)}</div> | |
| 337 | + {PROVIDER_ORDER.map((provider) => { | |
| 338 | + const Mark = PROVIDER_MARK[provider]; | |
| 339 | + return ( | |
| 340 | + <div key={provider} className="flex items-center justify-between gap-3"> | |
| 341 | + <span className="flex items-center gap-1.5 text-muted-foreground"> | |
| 342 | + <Mark className="size-3 shrink-0" aria-hidden /> | |
| 343 | + {PROVIDER_LABEL[provider]} | |
| 344 | + </span> | |
| 345 | + <span className="text-foreground tabular-nums"> | |
| 346 | + {format( | |
| 347 | + hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0, | |
| 348 | + )} | |
| 349 | + </span> | |
| 350 | + </div> | |
| 351 | + ); | |
| 352 | + })} | |
| 353 | + <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1"> | |
| 354 | + <span className="text-muted-foreground">Total</span> | |
| 355 | + <span className="text-foreground tabular-nums"> | |
| 356 | + {format(hoveredColumn?.total ?? 0)} | |
| 357 | + </span> | |
| 358 | + </div> | |
| 359 | + </div> | |
| 360 | + )} | |
| 361 | + </div> | |
| 362 | + </div> | |
| 363 | + | |
| 364 | + <div className="flex justify-between pl-16 text-[10px] text-muted-foreground uppercase"> | |
| 365 | + <span>{days[0] === undefined ? "" : formatDayShort(days[0])}</span> | |
| 366 | + <span> | |
| 367 | + {days[Math.floor(days.length / 2)] === undefined | |
| 368 | + ? "" | |
| 369 | + : formatDayShort(days[Math.floor(days.length / 2)] ?? "")} | |
| 370 | + </span> | |
| 371 | + <span> | |
| 372 | + {days[days.length - 1] === undefined ? "" : formatDayShort(days[days.length - 1] ?? "")} | |
| 373 | + </span> | |
| 374 | + </div> | |
| 375 | + </div> | |
| 376 | + ); | |
| 377 | +} | |
| 378 | + | |
| 379 | +export function UsageChartLegend() { | |
| 380 | + return ( | |
| 381 | + <div className="flex items-center gap-4"> | |
| 382 | + {PROVIDER_ORDER.map((provider) => { | |
| 383 | + // The marks carry the same fills as the bands, so they key the chart | |
| 384 | + // just as a colour swatch would. | |
| 385 | + const Mark = PROVIDER_MARK[provider]; | |
| 386 | + return ( | |
| 387 | + <span key={provider} className="flex items-center gap-1.5 text-xs text-muted-foreground"> | |
| 388 | + <Mark className="size-3.5 shrink-0" aria-hidden /> | |
| 389 | + {PROVIDER_LABEL[provider]} | |
| 390 | + </span> | |
| 391 | + ); | |
| 392 | + })} | |
| 393 | + </div> | |
| 394 | + ); | |
| 395 | +} | |
| @@ -0,0 +1,33 @@ | ||
| 1 | +import type { UsageProviderKind } from "@t3tools/contracts"; | |
| 2 | + | |
| 3 | +import { ClaudeAI, type Icon, OpenAI } from "../Icons"; | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * Series and table order. The chart layers both providers from a shared zero | |
| 7 | + * baseline, so this only fixes the reading order of legends, tables and hover | |
| 8 | + * rows; it does not decide which series sits above the other. | |
| 9 | + */ | |
| 10 | +export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"]; | |
| 11 | + | |
| 12 | +export const PROVIDER_LABEL: Record<UsageProviderKind, string> = { | |
| 13 | + claude: "Claude Code", | |
| 14 | + codex: "Codex", | |
| 15 | +}; | |
| 16 | + | |
| 17 | +/** Claude's brand orange against a neutral white for Codex. */ | |
| 18 | +export const PROVIDER_COLOR: Record<UsageProviderKind, string> = { | |
| 19 | + claude: "#d97757", | |
| 20 | + codex: "#e6e6e6", | |
| 21 | +}; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * Brand marks, reused from the provider picker. | |
| 25 | + * | |
| 26 | + * These ship their own fills (`#d97757` for Claude, white on dark for OpenAI), | |
| 27 | + * which are the same colours as the chart bands, so swapping a colour dot for a | |
| 28 | + * mark keeps the series association intact rather than trading it away. | |
| 29 | + */ | |
| 30 | +export const PROVIDER_MARK: Record<UsageProviderKind, Icon> = { | |
| 31 | + claude: ClaudeAI, | |
| 32 | + codex: OpenAI, | |
| 33 | +}; | |
| @@ -25,8 +25,6 @@ import { · 24 unmodified lines | ||
| 25 | 25 | type UnifiedSettings, |
| 26 | 26 | } from "@t3tools/contracts/settings"; |
| 27 | 27 | import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; |
| 28 | −import { APP_STAGE_LABEL } from "~/branding"; | |
| 29 | −import { resolveSidebarV2Enabled } from "~/branding.logic"; | |
| 30 | 28 | import { ensureLocalApi } from "~/localApi"; |
| 31 | 29 | import { |
| 32 | 30 | getThemeDefinition, |
| @@ -266,29 +264,18 @@ export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMod · 233 unmodified lines | ||
| 266 | 264 | } |
| 267 | 265 | |
| 268 | 266 | /** |
| 269 | − * Resolved sidebar v2 state: an explicit choice in Settings → Beta if the user | |
| 270 | − * has made one, otherwise the default for this build stage (on for nightly and | |
| 271 | − * dev, off for production). Every consumer must read through this rather than | |
| 272 | − * `settings.sidebarV2Enabled`, which is only meaningful alongside | |
| 273 | − * `sidebarV2ConfiguredByUser`. | |
| 267 | + * Whether the legacy sidebar (Settings → General → Legacy features) replaces | |
| 268 | + * the default one. | |
| 274 | 269 | * |
| 275 | − * Held at v1 until client settings hydrate. The pre-hydration snapshot is just | |
| 276 | − * the schema defaults, so resolving against it would mount one sidebar and then | |
| 277 | − * swap it out once persisted settings land — remounting the whole tree. | |
| 270 | + * Held at the default sidebar until client settings hydrate: the pre-hydration | |
| 271 | + * snapshot is just the schema defaults, so resolving against it could mount one | |
| 272 | + * sidebar and then swap it out once persisted settings land — remounting the | |
| 273 | + * whole tree for everyone instead of only for legacy opt-ins. | |
| 278 | 274 | */ |
| 279 | −export function useSidebarV2Enabled(): boolean { | |
| 275 | +export function useLegacySidebarEnabled(): boolean { | |
| 280 | 276 | const settingsHydrated = useClientSettingsHydrated(); |
| 281 | − const settings = useClientSettingsValue(); | |
| 282 | − return useMemo( | |
| 283 | − () => | |
| 284 | − resolveSidebarV2Enabled({ | |
| 285 | − enabled: settings.sidebarV2Enabled, | |
| 286 | − configuredByUser: settings.sidebarV2ConfiguredByUser, | |
| 287 | − settingsHydrated, | |
| 288 | − stageLabel: APP_STAGE_LABEL, | |
| 289 | − }), | |
| 290 | − [settings.sidebarV2Enabled, settings.sidebarV2ConfiguredByUser, settingsHydrated], | |
| 291 | − ); | |
| 277 | + const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled; | |
| 278 | + return settingsHydrated && legacySidebarEnabled; | |
| 292 | 279 | } |
| 293 | 280 | |
| 294 | 281 | /** Read current settings for one environment, merged with client-local preferences. */ |
| @@ -995,12 +995,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil · 994 unmodified lines | ||
| 995 | 995 | } |
| 996 | 996 | } |
| 997 | 997 | |
| 998 | −/* Keep both navigation implementations on the same quiet zinc hierarchy: | |
| 999 | − zinc-50 navigation, zinc-25 hover, and white selected/raised surfaces. | |
| 1000 | − The version attribute remains useful for layout-specific styling without | |
| 1001 | − changing the color system when the beta is toggled. */ | |
| 1002 | −[data-sidebar-version="v1"], | |
| 1003 | −[data-sidebar-version="v2"] { | |
| 998 | +/* Keep both sidebar implementations (default and legacy) on the same quiet | |
| 999 | + zinc hierarchy: zinc-50 navigation, zinc-25 hover, and white selected/raised | |
| 1000 | + surfaces. */ | |
| 1001 | +[data-app-sidebar] { | |
| 1004 | 1002 | --background: var(--color-zinc-25); |
| 1005 | 1003 | --foreground: var(--color-zinc-800); |
| 1006 | 1004 | --card: var(--color-white); |
| @@ -1023,8 +1021,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil · 16 unmodified lines | ||
| 1023 | 1021 | background-color: var(--sidebar); |
| 1024 | 1022 | } |
| 1025 | 1023 | |
| 1026 | −.dark [data-sidebar-version="v1"], | |
| 1027 | −.dark [data-sidebar-version="v2"] { | |
| 1024 | +.dark [data-app-sidebar] { | |
| 1028 | 1025 | --background: #000; |
| 1029 | 1026 | --foreground: #f1f3f7; |
| 1030 | 1027 | --card: #000; |
| @@ -1321,8 +1318,7 @@ html[data-theme-id] .chat-markdown .chat-markdown-chrome-action[aria-pressed="tr · 290 unmodified lines | ||
| 1321 | 1318 | color: var(--code-foreground); |
| 1322 | 1319 | } |
| 1323 | 1320 | |
| 1324 | −html[data-theme-id] [data-sidebar-version="v1"], | |
| 1325 | −html[data-theme-id] [data-sidebar-version="v2"] { | |
| 1321 | +html[data-theme-id] [data-app-sidebar] { | |
| 1326 | 1322 | --background: var(--app-theme-canvas); |
| 1327 | 1323 | --foreground: var(--app-theme-text); |
| 1328 | 1324 | --card: var(--app-theme-surface); |
| @@ -9,6 +9,7 @@ · 8 unmodified lines | ||
| 9 | 9 | // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. |
| 10 | 10 | |
| 11 | 11 | import { Route as rootRouteImport } from './routes/__root' |
| 12 | +import { Route as UsageRouteImport } from './routes/usage' | |
| 12 | 13 | import { Route as SettingsRouteImport } from './routes/settings' |
| 13 | 14 | import { Route as PairRouteImport } from './routes/pair' |
| 14 | 15 | import { Route as ConnectRouteImport } from './routes/connect' |
| @@ -20,13 +21,17 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi · 5 unmodified lines | ||
| 20 | 21 | import { Route as SettingsGeneralRouteImport } from './routes/settings.general' |
| 21 | 22 | import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics' |
| 22 | 23 | import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections' |
| 23 | −import { Route as SettingsBetaRouteImport } from './routes/settings.beta' | |
| 24 | 24 | import { Route as SettingsArchivedRouteImport } from './routes/settings.archived' |
| 25 | 25 | import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance' |
| 26 | 26 | import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback' |
| 27 | 27 | import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId' |
| 28 | 28 | import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId' |
| 29 | 29 | |
| 30 | +const UsageRoute = UsageRouteImport.update({ | |
| 31 | + id: '/usage', | |
| 32 | + path: '/usage', | |
| 33 | + getParentRoute: () => rootRouteImport, | |
| 34 | +} as any) | |
| 30 | 35 | const SettingsRoute = SettingsRouteImport.update({ |
| 31 | 36 | id: '/settings', |
| 32 | 37 | path: '/settings', |
| @@ -81,11 +86,6 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({ · 48 unmodified lines | ||
| 81 | 86 | path: '/connections', |
| 82 | 87 | getParentRoute: () => SettingsRoute, |
| 83 | 88 | } as any) |
| 84 | −const SettingsBetaRoute = SettingsBetaRouteImport.update({ | |
| 85 | − id: '/beta', | |
| 86 | − path: '/beta', | |
| 87 | − getParentRoute: () => SettingsRoute, | |
| 88 | −} as any) | |
| 89 | 89 | const SettingsArchivedRoute = SettingsArchivedRouteImport.update({ |
| 90 | 90 | id: '/archived', |
| 91 | 91 | path: '/archived', |
| @@ -118,10 +118,10 @@ export interface FileRoutesByFullPath { · 26 unmodified lines | ||
| 118 | 118 | '/connect': typeof ConnectRoute |
| 119 | 119 | '/pair': typeof PairRoute |
| 120 | 120 | '/settings': typeof SettingsRouteWithChildren |
| 121 | + '/usage': typeof UsageRoute | |
| 121 | 122 | '/connect/callback': typeof ConnectCallbackRoute |
| 122 | 123 | '/settings/appearance': typeof SettingsAppearanceRoute |
| 123 | 124 | '/settings/archived': typeof SettingsArchivedRoute |
| 124 | − '/settings/beta': typeof SettingsBetaRoute | |
| 125 | 125 | '/settings/connections': typeof SettingsConnectionsRoute |
| 126 | 126 | '/settings/diagnostics': typeof SettingsDiagnosticsRoute |
| 127 | 127 | '/settings/general': typeof SettingsGeneralRoute |
| @@ -135,10 +135,10 @@ export interface FileRoutesByTo { · 7 unmodified lines | ||
| 135 | 135 | '/connect': typeof ConnectRoute |
| 136 | 136 | '/pair': typeof PairRoute |
| 137 | 137 | '/settings': typeof SettingsRouteWithChildren |
| 138 | + '/usage': typeof UsageRoute | |
| 138 | 139 | '/connect/callback': typeof ConnectCallbackRoute |
| 139 | 140 | '/settings/appearance': typeof SettingsAppearanceRoute |
| 140 | 141 | '/settings/archived': typeof SettingsArchivedRoute |
| 141 | − '/settings/beta': typeof SettingsBetaRoute | |
| 142 | 142 | '/settings/connections': typeof SettingsConnectionsRoute |
| 143 | 143 | '/settings/diagnostics': typeof SettingsDiagnosticsRoute |
| 144 | 144 | '/settings/general': typeof SettingsGeneralRoute |
| @@ -155,10 +155,10 @@ export interface FileRoutesById { · 10 unmodified lines | ||
| 155 | 155 | '/connect': typeof ConnectRoute |
| 156 | 156 | '/pair': typeof PairRoute |
| 157 | 157 | '/settings': typeof SettingsRouteWithChildren |
| 158 | + '/usage': typeof UsageRoute | |
| 158 | 159 | '/connect_/callback': typeof ConnectCallbackRoute |
| 159 | 160 | '/settings/appearance': typeof SettingsAppearanceRoute |
| 160 | 161 | '/settings/archived': typeof SettingsArchivedRoute |
| 161 | − '/settings/beta': typeof SettingsBetaRoute | |
| 162 | 162 | '/settings/connections': typeof SettingsConnectionsRoute |
| 163 | 163 | '/settings/diagnostics': typeof SettingsDiagnosticsRoute |
| 164 | 164 | '/settings/general': typeof SettingsGeneralRoute |
| @@ -176,10 +176,10 @@ export interface FileRouteTypes { · 11 unmodified lines | ||
| 176 | 176 | | '/connect' |
| 177 | 177 | | '/pair' |
| 178 | 178 | | '/settings' |
| 179 | + | '/usage' | |
| 179 | 180 | | '/connect/callback' |
| 180 | 181 | | '/settings/appearance' |
| 181 | 182 | | '/settings/archived' |
| 182 | − | '/settings/beta' | |
| 183 | 183 | | '/settings/connections' |
| 184 | 184 | | '/settings/diagnostics' |
| 185 | 185 | | '/settings/general' |
| @@ -193,10 +193,10 @@ export interface FileRouteTypes { · 7 unmodified lines | ||
| 193 | 193 | | '/connect' |
| 194 | 194 | | '/pair' |
| 195 | 195 | | '/settings' |
| 196 | + | '/usage' | |
| 196 | 197 | | '/connect/callback' |
| 197 | 198 | | '/settings/appearance' |
| 198 | 199 | | '/settings/archived' |
| 199 | − | '/settings/beta' | |
| 200 | 200 | | '/settings/connections' |
| 201 | 201 | | '/settings/diagnostics' |
| 202 | 202 | | '/settings/general' |
| @@ -212,10 +212,10 @@ export interface FileRouteTypes { · 9 unmodified lines | ||
| 212 | 212 | | '/connect' |
| 213 | 213 | | '/pair' |
| 214 | 214 | | '/settings' |
| 215 | + | '/usage' | |
| 215 | 216 | | '/connect_/callback' |
| 216 | 217 | | '/settings/appearance' |
| 217 | 218 | | '/settings/archived' |
| 218 | − | '/settings/beta' | |
| 219 | 219 | | '/settings/connections' |
| 220 | 220 | | '/settings/diagnostics' |
| 221 | 221 | | '/settings/general' |
| @@ -232,11 +232,19 @@ export interface RootRouteChildren { · 10 unmodified lines | ||
| 232 | 232 | ConnectRoute: typeof ConnectRoute |
| 233 | 233 | PairRoute: typeof PairRoute |
| 234 | 234 | SettingsRoute: typeof SettingsRouteWithChildren |
| 235 | + UsageRoute: typeof UsageRoute | |
| 235 | 236 | ConnectCallbackRoute: typeof ConnectCallbackRoute |
| 236 | 237 | } |
| 237 | 238 | |
| 238 | 239 | declare module '@tanstack/react-router' { |
| 239 | 240 | interface FileRoutesByPath { |
| 241 | + '/usage': { | |
| 242 | + id: '/usage' | |
| 243 | + path: '/usage' | |
| 244 | + fullPath: '/usage' | |
| 245 | + preLoaderRoute: typeof UsageRouteImport | |
| 246 | + parentRoute: typeof rootRouteImport | |
| 247 | + } | |
| 240 | 248 | '/settings': { |
| 241 | 249 | id: '/settings' |
| 242 | 250 | path: '/settings' |
| @@ -314,13 +322,6 @@ declare module '@tanstack/react-router' { · 71 unmodified lines | ||
| 314 | 322 | preLoaderRoute: typeof SettingsConnectionsRouteImport |
| 315 | 323 | parentRoute: typeof SettingsRoute |
| 316 | 324 | } |
| 317 | − '/settings/beta': { | |
| 318 | − id: '/settings/beta' | |
| 319 | − path: '/beta' | |
| 320 | − fullPath: '/settings/beta' | |
| 321 | − preLoaderRoute: typeof SettingsBetaRouteImport | |
| 322 | − parentRoute: typeof SettingsRoute | |
| 323 | − } | |
| 324 | 325 | '/settings/archived': { |
| 325 | 326 | id: '/settings/archived' |
| 326 | 327 | path: '/archived' |
| @@ -376,7 +377,6 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren) · 49 unmodified lines | ||
| 376 | 377 | interface SettingsRouteChildren { |
| 377 | 378 | SettingsAppearanceRoute: typeof SettingsAppearanceRoute |
| 378 | 379 | SettingsArchivedRoute: typeof SettingsArchivedRoute |
| 379 | − SettingsBetaRoute: typeof SettingsBetaRoute | |
| 380 | 380 | SettingsConnectionsRoute: typeof SettingsConnectionsRoute |
| 381 | 381 | SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute |
| 382 | 382 | SettingsGeneralRoute: typeof SettingsGeneralRoute |
| @@ -388,7 +388,6 @@ interface SettingsRouteChildren { · 5 unmodified lines | ||
| 388 | 388 | const SettingsRouteChildren: SettingsRouteChildren = { |
| 389 | 389 | SettingsAppearanceRoute: SettingsAppearanceRoute, |
| 390 | 390 | SettingsArchivedRoute: SettingsArchivedRoute, |
| 391 | − SettingsBetaRoute: SettingsBetaRoute, | |
| 392 | 391 | SettingsConnectionsRoute: SettingsConnectionsRoute, |
| 393 | 392 | SettingsDiagnosticsRoute: SettingsDiagnosticsRoute, |
| 394 | 393 | SettingsGeneralRoute: SettingsGeneralRoute, |
| @@ -406,6 +405,7 @@ const rootRouteChildren: RootRouteChildren = { · 11 unmodified lines | ||
| 406 | 405 | ConnectRoute: ConnectRoute, |
| 407 | 406 | PairRoute: PairRoute, |
| 408 | 407 | SettingsRoute: SettingsRouteWithChildren, |
| 408 | + UsageRoute: UsageRoute, | |
| 409 | 409 | ConnectCallbackRoute: ConnectCallbackRoute, |
| 410 | 410 | } |
| 411 | 411 | export const routeTree = rootRouteImport |
| @@ -3,7 +3,7 @@ import { useAtomValue } from "@effect/atom-react"; · 2 unmodified lines | ||
| 3 | 3 | import { useEffect, useMemo } from "react"; |
| 4 | 4 | |
| 5 | 5 | import { isCommandPaletteOpen } from "../commandPaletteBus"; |
| 6 | −import { useClientSettings, useSidebarV2Enabled } from "../hooks/useSettings"; | |
| 6 | +import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings"; | |
| 7 | 7 | import { openCommandPalette } from "../commandPaletteBus"; |
| 8 | 8 | import { useProjects } from "../state/entities"; |
| 9 | 9 | import { usePrimaryEnvironmentId } from "../state/environments"; |
| @@ -28,7 +28,7 @@ function ChatRouteGlobalShortcuts() { · 18 unmodified lines | ||
| 28 | 28 | const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } = |
| 29 | 29 | useHandleNewThread(); |
| 30 | 30 | const keybindings = useAtomValue(primaryServerKeybindingsAtom); |
| 31 | − const sidebarV2Enabled = useSidebarV2Enabled(); | |
| 31 | + const legacySidebarEnabled = useLegacySidebarEnabled(); | |
| 32 | 32 | const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); |
| 33 | 33 | const projects = useProjects(); |
| 34 | 34 | const primaryEnvironmentId = usePrimaryEnvironmentId(); |
| @@ -92,10 +92,10 @@ function ChatRouteGlobalShortcuts() { · 57 unmodified lines | ||
| 92 | 92 | if (command === "chat.new") { |
| 93 | 93 | event.preventDefault(); |
| 94 | 94 | event.stopPropagation(); |
| 95 | − // Sidebar v2 routes creation through the command palette whenever | |
| 96 | − // there is a real choice to make; v1 (and single-project setups) | |
| 97 | − // keep the immediate contextual create. | |
| 98 | − if (sidebarV2Enabled && projectGroupCount > 1) { | |
| 95 | + // The default sidebar routes creation through the command palette | |
| 96 | + // whenever there is a real choice to make; the legacy sidebar (and | |
| 97 | + // single-project setups) keep the immediate contextual create. | |
| 98 | + if (!legacySidebarEnabled && projectGroupCount > 1) { | |
| 99 | 99 | openCommandPalette({ open: "new-thread-in" }); |
| 100 | 100 | return; |
| 101 | 101 | } |
| @@ -167,7 +167,7 @@ function ChatRouteGlobalShortcuts() { · 65 unmodified lines | ||
| 167 | 167 | projectGroupCount, |
| 168 | 168 | routeThreadRef, |
| 169 | 169 | selectedThreadKeysSize, |
| 170 | − sidebarV2Enabled, | |
| 170 | + legacySidebarEnabled, | |
| 171 | 171 | terminalOpen, |
| 172 | 172 | ]); |
| 173 | 173 | |
| @@ -1,11 +0,0 @@ | ||
| 1 | −import { createFileRoute } from "@tanstack/react-router"; | |
| 2 | − | |
| 3 | −import { BetaSettingsPanel } from "../components/settings/BetaSettingsPanel"; | |
| 4 | − | |
| 5 | −function SettingsBetaRoute() { | |
| 6 | − return <BetaSettingsPanel />; | |
| 7 | −} | |
| 8 | − | |
| 9 | −export const Route = createFileRoute("/settings/beta")({ | |
| 10 | − component: SettingsBetaRoute, | |
| 11 | −}); | |
| @@ -0,0 +1,7 @@ | ||
| 1 | +import { createFileRoute } from "@tanstack/react-router"; | |
| 2 | + | |
| 3 | +import { UsagePage } from "../components/usage/UsagePage"; | |
| 4 | + | |
| 5 | +export const Route = createFileRoute("/usage")({ | |
| 6 | + component: UsagePage, | |
| 7 | +}); | |
| @@ -0,0 +1,126 @@ | ||
| 1 | +/** | |
| 2 | + * Multi-environment usage state. | |
| 3 | + * | |
| 4 | + * Every connected environment answers the same typed query; the client merges | |
| 5 | + * the results. Raw transcripts never leave the machine that produced them. | |
| 6 | + * | |
| 7 | + * @module state/usage | |
| 8 | + */ | |
| 9 | +import { useAtomValue } from "@effect/atom-react"; | |
| 10 | +import { | |
| 11 | + USAGE_CONTRACT_VERSION, | |
| 12 | + type EnvironmentId, | |
| 13 | + type UsageSummary, | |
| 14 | + type UsageSummaryInput, | |
| 15 | +} from "@t3tools/contracts"; | |
| 16 | +import * as Option from "effect/Option"; | |
| 17 | +import { AsyncResult, Atom } from "effect/unstable/reactivity"; | |
| 18 | +import { useCallback, useMemo } from "react"; | |
| 19 | + | |
| 20 | +import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "../usage/usageMerge"; | |
| 21 | +import { appAtomRegistry } from "../rpc/atomRegistry"; | |
| 22 | +import { environmentPresentations } from "./presentation"; | |
| 23 | +import { serverEnvironment } from "./server"; | |
| 24 | + | |
| 25 | +export interface EnvironmentUsageStatus { | |
| 26 | + readonly environmentId: EnvironmentId; | |
| 27 | + readonly label: string; | |
| 28 | + readonly isPending: boolean; | |
| 29 | + readonly error: string | null; | |
| 30 | + readonly summary: UsageSummary | null; | |
| 31 | +} | |
| 32 | + | |
| 33 | +/** | |
| 34 | + * Reads every environment's summary for one window. | |
| 35 | + * | |
| 36 | + * Keyed by the serialised window so switching ranges does not thrash the atom | |
| 37 | + * cache, and so each environment's query is shared with any other reader of the | |
| 38 | + * same window. | |
| 39 | + */ | |
| 40 | +const usageByWindowAtom = Atom.family((windowKey: string) => | |
| 41 | + Atom.make((get): readonly EnvironmentUsageStatus[] => { | |
| 42 | + const input = JSON.parse(windowKey) as UsageSummaryInput; | |
| 43 | + const presentations = get(environmentPresentations.presentationsAtom); | |
| 44 | + | |
| 45 | + const statuses: EnvironmentUsageStatus[] = []; | |
| 46 | + for (const [environmentId, presentation] of presentations) { | |
| 47 | + const result = get(serverEnvironment.usageSummary({ environmentId, input })); | |
| 48 | + statuses.push({ | |
| 49 | + environmentId, | |
| 50 | + label: presentation.entry.target.label, | |
| 51 | + isPending: result.waiting, | |
| 52 | + error: result._tag === "Failure" ? "This environment could not report usage." : null, | |
| 53 | + summary: Option.getOrNull(AsyncResult.value(result)), | |
| 54 | + }); | |
| 55 | + } | |
| 56 | + return statuses; | |
| 57 | + }).pipe(Atom.withLabel(`web-usage:window:${windowKey}`)), | |
| 58 | +); | |
| 59 | + | |
| 60 | +export interface UsageView { | |
| 61 | + readonly merged: MergedUsage; | |
| 62 | + readonly environments: readonly EnvironmentUsageStatus[]; | |
| 63 | + /** True until at least one environment has answered. */ | |
| 64 | + readonly isPending: boolean; | |
| 65 | + /** | |
| 66 | + * True while environments that have not failed are still answering. Failed | |
| 67 | + * environments are reported through their own error rows: totals will not | |
| 68 | + * improve by waiting on them, so they must not read as "still reporting". | |
| 69 | + */ | |
| 70 | + readonly isPartial: boolean; | |
| 71 | + readonly refresh: () => void; | |
| 72 | +} | |
| 73 | + | |
| 74 | +export function useUsage(input: UsageSummaryInput): UsageView { | |
| 75 | + const windowKey = useMemo( | |
| 76 | + () => | |
| 77 | + JSON.stringify({ | |
| 78 | + sinceDay: input.sinceDay, | |
| 79 | + untilDay: input.untilDay, | |
| 80 | + timeZone: input.timeZone, | |
| 81 | + }), | |
| 82 | + [input.sinceDay, input.untilDay, input.timeZone], | |
| 83 | + ); | |
| 84 | + const atom = usageByWindowAtom(windowKey); | |
| 85 | + const environments = useAtomValue(atom); | |
| 86 | + | |
| 87 | + // Refreshing only the derived atom would re-read the per-environment SWR | |
| 88 | + // queries within their stale window and change nothing. Refresh each | |
| 89 | + // environment's query so the button always rescans. | |
| 90 | + const refresh = useCallback(() => { | |
| 91 | + const input = JSON.parse(windowKey) as UsageSummaryInput; | |
| 92 | + for (const environment of environments) { | |
| 93 | + appAtomRegistry.refresh( | |
| 94 | + serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }), | |
| 95 | + ); | |
| 96 | + } | |
| 97 | + }, [environments, windowKey]); | |
| 98 | + | |
| 99 | + const merged = useMemo(() => { | |
| 100 | + const answered: EnvironmentUsage[] = environments.flatMap((environment) => | |
| 101 | + environment.summary === null | |
| 102 | + ? [] | |
| 103 | + : [ | |
| 104 | + { | |
| 105 | + environmentId: environment.environmentId, | |
| 106 | + label: environment.label, | |
| 107 | + summary: environment.summary, | |
| 108 | + }, | |
| 109 | + ], | |
| 110 | + ); | |
| 111 | + return mergeUsage(answered, USAGE_CONTRACT_VERSION); | |
| 112 | + }, [environments]); | |
| 113 | + | |
| 114 | + const answeredCount = environments.filter((environment) => environment.summary !== null).length; | |
| 115 | + const stillReporting = environments.filter( | |
| 116 | + (environment) => environment.summary === null && environment.error === null, | |
| 117 | + ).length; | |
| 118 | + | |
| 119 | + return { | |
| 120 | + merged, | |
| 121 | + environments, | |
| 122 | + isPending: answeredCount === 0 && stillReporting > 0, | |
| 123 | + isPartial: answeredCount > 0 && stillReporting > 0, | |
| 124 | + refresh, | |
| 125 | + }; | |
| 126 | +} | |
| @@ -0,0 +1,107 @@ | ||
| 1 | +/** | |
| 2 | + * Display formatting for the usage page. | |
| 3 | + * | |
| 4 | + * @module usageFormat | |
| 5 | + */ | |
| 6 | +import { UsageDay, type UsageSummaryInput } from "@t3tools/contracts"; | |
| 7 | + | |
| 8 | +const CURRENCY = new Intl.NumberFormat("en-US", { | |
| 9 | + style: "currency", | |
| 10 | + currency: "USD", | |
| 11 | + minimumFractionDigits: 2, | |
| 12 | + maximumFractionDigits: 2, | |
| 13 | +}); | |
| 14 | + | |
| 15 | +const INTEGER = new Intl.NumberFormat("en-US"); | |
| 16 | + | |
| 17 | +export function formatUsd(value: number): string { | |
| 18 | + return CURRENCY.format(value); | |
| 19 | +} | |
| 20 | + | |
| 21 | +export function formatCount(value: number): string { | |
| 22 | + return INTEGER.format(Math.round(value)); | |
| 23 | +} | |
| 24 | + | |
| 25 | +/** | |
| 26 | + * Compacts a token count to three significant figures with a unit suffix, so | |
| 27 | + * columns of numbers line up at a glance (`19.9B`, `76.7M`, `804K`). | |
| 28 | + */ | |
| 29 | +export function formatTokens(value: number): string { | |
| 30 | + const abs = Math.abs(value); | |
| 31 | + if (abs >= 1e12) return `${trim(value / 1e12)}T`; | |
| 32 | + if (abs >= 1e9) return `${trim(value / 1e9)}B`; | |
| 33 | + if (abs >= 1e6) return `${trim(value / 1e6)}M`; | |
| 34 | + if (abs >= 1e3) return `${trim(value / 1e3)}K`; | |
| 35 | + return INTEGER.format(Math.round(value)); | |
| 36 | +} | |
| 37 | + | |
| 38 | +function trim(value: number): string { | |
| 39 | + const abs = Math.abs(value); | |
| 40 | + const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2; | |
| 41 | + return value.toFixed(digits).replace(/\.0+$/, ""); | |
| 42 | +} | |
| 43 | + | |
| 44 | +export function formatPercent(share: number, digits = 1): string { | |
| 45 | + return `${(share * 100).toFixed(digits)}%`; | |
| 46 | +} | |
| 47 | + | |
| 48 | +/** `2026-08-07` to `Aug 7`. */ | |
| 49 | +export function formatDayShort(day: string): string { | |
| 50 | + const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part)); | |
| 51 | + if (year === undefined || month === undefined || dayOfMonth === undefined) return day; | |
| 52 | + const MONTHS = [ | |
| 53 | + "Jan", | |
| 54 | + "Feb", | |
| 55 | + "Mar", | |
| 56 | + "Apr", | |
| 57 | + "May", | |
| 58 | + "Jun", | |
| 59 | + "Jul", | |
| 60 | + "Aug", | |
| 61 | + "Sep", | |
| 62 | + "Oct", | |
| 63 | + "Nov", | |
| 64 | + "Dec", | |
| 65 | + ]; | |
| 66 | + return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`; | |
| 67 | +} | |
| 68 | + | |
| 69 | +/** Inclusive day list between two `YYYY-MM-DD` bounds. */ | |
| 70 | +export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] { | |
| 71 | + const days: string[] = []; | |
| 72 | + const start = Date.parse(`${sinceDay}T00:00:00Z`); | |
| 73 | + const end = Date.parse(`${untilDay}T00:00:00Z`); | |
| 74 | + if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days; | |
| 75 | + | |
| 76 | + for (let cursor = start; cursor <= end; cursor += 86_400_000) { | |
| 77 | + days.push(new Date(cursor).toISOString().slice(0, 10)); | |
| 78 | + } | |
| 79 | + return days; | |
| 80 | +} | |
| 81 | + | |
| 82 | +/** | |
| 83 | + * The window the page requests, expressed in the viewer's own time zone so days | |
| 84 | + * line up with what they actually experienced. | |
| 85 | + */ | |
| 86 | +export function makeWindow(days: number, now = new Date()): UsageSummaryInput { | |
| 87 | + const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; | |
| 88 | + const format = new Intl.DateTimeFormat("en-CA", { | |
| 89 | + timeZone, | |
| 90 | + year: "numeric", | |
| 91 | + month: "2-digit", | |
| 92 | + day: "2-digit", | |
| 93 | + }); | |
| 94 | + const untilDay = format.format(now); | |
| 95 | + // Subtracting fixed milliseconds from `now` lands on the wrong calendar day | |
| 96 | + // around a DST transition. Only "today" needs the zone; the window start is | |
| 97 | + // pure calendar arithmetic on that day, done in UTC where days are uniform. | |
| 98 | + const [year = 0, month = 1, dayOfMonth = 1] = untilDay | |
| 99 | + .split("-") | |
| 100 | + .map((part) => Number.parseInt(part, 10)); | |
| 101 | + const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1))); | |
| 102 | + return { | |
| 103 | + sinceDay: UsageDay.make(start.toISOString().slice(0, 10)), | |
| 104 | + untilDay: UsageDay.make(untilDay), | |
| 105 | + timeZone, | |
| 106 | + }; | |
| 107 | +} | |
| @@ -0,0 +1,258 @@ | ||
| 1 | +import { | |
| 2 | + USAGE_CONTRACT_VERSION, | |
| 3 | + type EnvironmentId, | |
| 4 | + type UsageBucket, | |
| 5 | + type UsageDay, | |
| 6 | + type UsageProviderKind, | |
| 7 | + type UsageSummary, | |
| 8 | +} from "@t3tools/contracts"; | |
| 9 | +import { describe, expect, it } from "vite-plus/test"; | |
| 10 | + | |
| 11 | +import { mergeUsage, type EnvironmentUsage } from "./usageMerge"; | |
| 12 | + | |
| 13 | +function bucket(overrides: Partial<UsageBucket> = {}): UsageBucket { | |
| 14 | + return { | |
| 15 | + day: "2026-08-07" as UsageDay, | |
| 16 | + provider: "claude", | |
| 17 | + model: "claude-fable-5", | |
| 18 | + totals: { | |
| 19 | + uncachedInputTokens: 100, | |
| 20 | + cachedInputTokens: 1000, | |
| 21 | + cacheCreationTokens: 10, | |
| 22 | + outputTokens: 50, | |
| 23 | + reasoningTokens: 0, | |
| 24 | + }, | |
| 25 | + costUsd: 10, | |
| 26 | + cacheSavingsUsd: 2, | |
| 27 | + costSource: "modelPriced", | |
| 28 | + records: 5, | |
| 29 | + unpricedRecords: 0, | |
| 30 | + sessions: 1, | |
| 31 | + ...overrides, | |
| 32 | + }; | |
| 33 | +} | |
| 34 | + | |
| 35 | +function summary( | |
| 36 | + buckets: readonly UsageBucket[], | |
| 37 | + sources: readonly { | |
| 38 | + provider: UsageProviderKind; | |
| 39 | + hostId: string; | |
| 40 | + homePath: string; | |
| 41 | + volumeId?: string; | |
| 42 | + distinctSessions?: number; | |
| 43 | + }[], | |
| 44 | + contractVersion: number = USAGE_CONTRACT_VERSION, | |
| 45 | +): UsageSummary { | |
| 46 | + return { | |
| 47 | + contractVersion, | |
| 48 | + readAt: "2026-08-07T00:00:00.000Z", | |
| 49 | + timeZone: "UTC", | |
| 50 | + sinceDay: "2026-08-01" as UsageDay, | |
| 51 | + untilDay: "2026-08-31" as UsageDay, | |
| 52 | + buckets, | |
| 53 | + sources: sources.map((source) => ({ | |
| 54 | + fingerprint: { | |
| 55 | + hostId: source.hostId, | |
| 56 | + provider: source.provider, | |
| 57 | + resolvedHomePath: source.homePath, | |
| 58 | + volumeId: source.volumeId ?? `vol-${source.hostId}`, | |
| 59 | + }, | |
| 60 | + status: "ok" as const, | |
| 61 | + scannedFiles: 1, | |
| 62 | + skippedFiles: 0, | |
| 63 | + malformedRecords: 0, | |
| 64 | + distinctSessions: source.distinctSessions ?? 1, | |
| 65 | + message: null, | |
| 66 | + })), | |
| 67 | + pricing: { status: "fresh", source: "litellm", fetchedAt: null, knownModels: 10 }, | |
| 68 | + scanDurationMs: 1, | |
| 69 | + }; | |
| 70 | +} | |
| 71 | + | |
| 72 | +function environment(id: string, usageSummary: UsageSummary): EnvironmentUsage { | |
| 73 | + return { environmentId: id as EnvironmentId, label: id, summary: usageSummary }; | |
| 74 | +} | |
| 75 | + | |
| 76 | +describe("mergeUsage", () => { | |
| 77 | + it("sums environments that read different transcript directories", () => { | |
| 78 | + const merged = mergeUsage( | |
| 79 | + [ | |
| 80 | + environment( | |
| 81 | + "env-a", | |
| 82 | + summary([bucket()], [{ provider: "claude", hostId: "mac", homePath: "/a/.claude" }]), | |
| 83 | + ), | |
| 84 | + environment( | |
| 85 | + "env-b", | |
| 86 | + summary([bucket()], [{ provider: "claude", hostId: "linux", homePath: "/b/.claude" }]), | |
| 87 | + ), | |
| 88 | + ], | |
| 89 | + USAGE_CONTRACT_VERSION, | |
| 90 | + ); | |
| 91 | + | |
| 92 | + expect(merged.costUsd).toBe(20); | |
| 93 | + expect(merged.records).toBe(10); | |
| 94 | + expect(merged.duplicateSources).toHaveLength(0); | |
| 95 | + }); | |
| 96 | + | |
| 97 | + it("counts a shared transcript directory once", () => { | |
| 98 | + // Two worktree servers on one machine resolve the same provider home. | |
| 99 | + const shared = { provider: "claude" as const, hostId: "mac", homePath: "/home/theo/.claude" }; | |
| 100 | + const merged = mergeUsage( | |
| 101 | + [ | |
| 102 | + environment("env-a", summary([bucket()], [shared])), | |
| 103 | + environment("env-b", summary([bucket()], [shared])), | |
| 104 | + ], | |
| 105 | + USAGE_CONTRACT_VERSION, | |
| 106 | + ); | |
| 107 | + | |
| 108 | + expect(merged.costUsd).toBe(10); | |
| 109 | + expect(merged.records).toBe(5); | |
| 110 | + expect(merged.sessions).toBe(1); | |
| 111 | + expect(merged.duplicateSources).toHaveLength(1); | |
| 112 | + expect(merged.contributingEnvironments).toEqual(["env-a"]); | |
| 113 | + }); | |
| 114 | + | |
| 115 | + it("drops only the duplicated provider, keeping the environment's other one", () => { | |
| 116 | + const sharedClaude = { | |
| 117 | + provider: "claude" as const, | |
| 118 | + hostId: "mac", | |
| 119 | + homePath: "/home/theo/.claude", | |
| 120 | + }; | |
| 121 | + const merged = mergeUsage( | |
| 122 | + [ | |
| 123 | + environment("env-a", summary([bucket()], [sharedClaude])), | |
| 124 | + environment( | |
| 125 | + "env-b", | |
| 126 | + summary( | |
| 127 | + [bucket(), bucket({ provider: "codex", model: "gpt-5.6-sol", costUsd: 4 })], | |
| 128 | + [sharedClaude, { provider: "codex", hostId: "mac", homePath: "/home/theo/.codex" }], | |
| 129 | + ), | |
| 130 | + ), | |
| 131 | + ], | |
| 132 | + USAGE_CONTRACT_VERSION, | |
| 133 | + ); | |
| 134 | + | |
| 135 | + // env-b's claude bucket is dropped, its codex bucket survives. | |
| 136 | + expect(merged.costUsd).toBe(14); | |
| 137 | + expect(merged.providers.map((provider) => provider.provider).sort()).toEqual([ | |
| 138 | + "claude", | |
| 139 | + "codex", | |
| 140 | + ]); | |
| 141 | + }); | |
| 142 | + | |
| 143 | + it("excludes an environment reporting an older contract version", () => { | |
| 144 | + const merged = mergeUsage( | |
| 145 | + [ | |
| 146 | + environment( | |
| 147 | + "env-a", | |
| 148 | + summary([bucket()], [{ provider: "claude", hostId: "mac", homePath: "/a" }]), | |
| 149 | + ), | |
| 150 | + environment( | |
| 151 | + "env-b", | |
| 152 | + summary( | |
| 153 | + [bucket()], | |
| 154 | + [{ provider: "claude", hostId: "linux", homePath: "/b" }], | |
| 155 | + USAGE_CONTRACT_VERSION - 1, | |
| 156 | + ), | |
| 157 | + ), | |
| 158 | + ], | |
| 159 | + USAGE_CONTRACT_VERSION, | |
| 160 | + ); | |
| 161 | + | |
| 162 | + expect(merged.costUsd).toBe(10); | |
| 163 | + expect(merged.staleEnvironments).toEqual(["env-b"]); | |
| 164 | + }); | |
| 165 | + | |
| 166 | + it("derives provider shares and cost quality", () => { | |
| 167 | + const merged = mergeUsage( | |
| 168 | + [ | |
| 169 | + environment( | |
| 170 | + "env-a", | |
| 171 | + summary( | |
| 172 | + [ | |
| 173 | + bucket({ costUsd: 75 }), | |
| 174 | + bucket({ provider: "codex", model: "gpt-5.6-sol", costUsd: 25, unpricedRecords: 5 }), | |
| 175 | + ], | |
| 176 | + [ | |
| 177 | + { provider: "claude", hostId: "mac", homePath: "/a/.claude" }, | |
| 178 | + { provider: "codex", hostId: "mac", homePath: "/a/.codex" }, | |
| 179 | + ], | |
| 180 | + ), | |
| 181 | + ), | |
| 182 | + ], | |
| 183 | + USAGE_CONTRACT_VERSION, | |
| 184 | + ); | |
| 185 | + | |
| 186 | + expect(merged.providers[0]?.provider).toBe("claude"); | |
| 187 | + expect(merged.providers[0]?.costShare).toBeCloseTo(0.75, 5); | |
| 188 | + expect(merged.costQuality.unpricedShare).toBeCloseTo(0.5, 5); | |
| 189 | + expect(merged.costQuality.cacheSavingsUsd).toBe(4); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + it("keeps two machines apart when hostname and home path collide", () => { | |
| 193 | + // Every Mac resolves /Users/theo/.claude, so a hostname clash used to make | |
| 194 | + // one machine's usage vanish. Filesystem identity separates them. | |
| 195 | + const shape = { provider: "claude" as const, hostId: "mac", homePath: "/Users/theo/.claude" }; | |
| 196 | + const merged = mergeUsage( | |
62 more lines aren’t shown here.
This diff is large: its 354 lines aren’t shown here.
This diff is large: its 14 lines aren’t shown here.
This diff is large: its 6 lines aren’t shown here.
This diff is large: its 37 lines aren’t shown here.
This diff is large: its 50 lines aren’t shown here.
This diff is large: its 66 lines aren’t shown here.
This diff is large: its 195 lines aren’t shown here.