diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 6c942d4ccb9..fd5b75b83c6 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -334,6 +334,8 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{ { key: "j", meta: true, shift: true, control: false }, // mod+K → command palette { key: "k", meta: true, shift: false, control: false }, + // mod+T → board + { key: "t", meta: true, shift: false, control: false }, // mod+, → settings (macOS convention) { key: ",", meta: true, shift: false, control: false }, // mod+W → close tab/panel diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 2eef6ac8416..af47ae338d5 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => { assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1"); assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9"); assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m"); + assert.equal(defaultsByCommand.get("board.open"), "mod+t"); assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b"); assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b"); assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d"); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index aa7547c8ba6..a1d54e8cfc3 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -28,6 +28,7 @@ import { LinkIcon, MessageSquareIcon, SettingsIcon, + SquareKanbanIcon, SquarePenIcon, } from "lucide-react"; import { @@ -1230,6 +1231,18 @@ function OpenCommandPaletteDialog(props: { }); } + actionItems.push({ + kind: "action", + value: "action:board", + searchTerms: ["board", "kanban", "overview", "dashboard"], + title: "Open board", + icon: , + shortcutCommand: "board.open", + run: async () => { + await navigate({ to: "/board" }); + }, + }); + actionItems.push({ kind: "action", value: "action:settings", diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index bc3e8ee832f..a4f5ae9789f 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -33,12 +33,12 @@ export function ProjectFavicon(input: { ); } -function ProjectFaviconFallback({ +export function ProjectFaviconFallback({ className, - icon: Icon, + icon: Icon = FolderIcon, }: { readonly className?: string | undefined; - readonly icon: ComponentType<{ className?: string }>; + readonly icon?: ComponentType<{ className?: string }>; }) { return ; } diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 59784bf8fac..e256dba36b7 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" import { archiveSelectedThreadEntries, buildMultiSelectThreadContextMenuItems, + buildSidebarV2ThreadContextMenuItems, createThreadJumpHintVisibilityController, getSidebarThreadIdsToPrewarm, getVisibleSidebarThreadIds, @@ -17,6 +18,7 @@ import { resolveSidebarStageBadgeLabel, resolveThreadRowClassName, resolveSidebarV2Status, + resolveSidebarV2TopStatus, resolveThreadStatusPill, resolveWorkingStartedAt, formatWorkingDurationLabel, @@ -163,6 +165,90 @@ describe("buildMultiSelectThreadContextMenuItems", () => { }); }); +describe("buildSidebarV2ThreadContextMenuItems", () => { + const baseInput = { + branch: null, + supportsSettlement: false, + isSettled: false, + supportsSnooze: false, + isSnoozed: false, + canSnoozeNow: true, + snoozePresets: [], + } as const; + + it("offers settlement actions matching the thread's state and server support", () => { + expect( + buildSidebarV2ThreadContextMenuItems({ + ...baseInput, + supportsSettlement: true, + })[0], + ).toEqual({ id: "settle", label: "Settle thread" }); + expect( + buildSidebarV2ThreadContextMenuItems({ + ...baseInput, + supportsSettlement: true, + isSettled: true, + })[0], + ).toEqual({ id: "unsettle", label: "Un-settle thread" }); + expect(buildSidebarV2ThreadContextMenuItems(baseInput)).toEqual([ + { id: "rename", label: "Rename thread" }, + { id: "mark-unread", label: "Mark unread" }, + { id: "delete", label: "Delete", destructive: true, icon: "trash" }, + ]); + }); + + it("leads with a new-thread item for the thread's branch", () => { + expect( + buildSidebarV2ThreadContextMenuItems({ + ...baseInput, + branch: "feature/login", + supportsSettlement: true, + })[0], + ).toEqual({ id: "new-thread-on-branch", label: "New thread on feature/login" }); + }); + + it("offers snooze presets when supported, disabled while the thread blocks on the user", () => { + const presets = [ + { + id: "hour", + label: "In 1 hour", + whenLabel: "10:00 AM", + snoozedUntil: "2026-07-24T10:00:00.000Z", + }, + ] as const; + expect( + buildSidebarV2ThreadContextMenuItems({ + ...baseInput, + supportsSnooze: true, + snoozePresets: presets, + })[0], + ).toEqual({ + id: "snooze", + label: "Snooze", + disabled: false, + children: [{ id: "snooze:hour", label: "In 1 hour (10:00 AM)" }], + }); + expect( + buildSidebarV2ThreadContextMenuItems({ + ...baseInput, + supportsSnooze: true, + canSnoozeNow: false, + snoozePresets: presets, + })[0], + ).toMatchObject({ id: "snooze", disabled: true }); + }); + + it("offers wake instead of snooze for a snoozed thread", () => { + expect( + buildSidebarV2ThreadContextMenuItems({ + ...baseInput, + supportsSnooze: true, + isSnoozed: true, + })[0], + ).toEqual({ id: "unsnooze", label: "Wake thread" }); + }); +}); + describe("resolveSidebarStageBadgeLabel", () => { it("returns Nightly for nightly primary server versions", () => { expect( @@ -654,6 +740,21 @@ describe("resolveSidebarV2Status", () => { }); }); +describe("resolveSidebarV2TopStatus", () => { + it("labels ready threads Done only when they carry an unread completion", () => { + expect(resolveSidebarV2TopStatus({ status: "ready", isUnread: true })).toMatchObject({ + label: "Done", + icon: "done", + }); + expect(resolveSidebarV2TopStatus({ status: "ready", isUnread: false })).toBeNull(); + // Unread only matters for ready threads; active statuses keep their label. + expect(resolveSidebarV2TopStatus({ status: "working", isUnread: true })).toMatchObject({ + label: "Working", + icon: "working", + }); + }); +}); + describe("sortThreadsForSidebarV2", () => { const sortable = (input: { id: string; createdAt: string }) => ({ id: input.id, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 7aee3100d0e..e77a90d87e8 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1,4 +1,8 @@ import * as React from "react"; +import { + effectiveSettled, + type ChangeRequestStateLike, +} from "@t3tools/client-runtime/state/thread-settled"; import type { ContextMenuItem } from "@t3tools/contracts"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; import { @@ -12,12 +16,17 @@ import type { ThreadRouteTarget } from "../threadRoutes"; import { cn } from "../lib/utils"; import { isLatestTurnSettled } from "../session-logic"; import { resolveServerBackedAppStageLabel } from "../branding.logic"; +import type { SnoozePreset } from "./Sidebar.snooze"; export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]"; export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100; // Visible sidebar rows are prewarmed into the thread-detail cache so opening a // nearby thread usually reuses an already-hot subscription. export const SIDEBAR_THREAD_PREWARM_LIMIT = 10; +// Settled-tail paging: recent history is the common lookup; the deep tail +// stays behind an explicit Show more. Shared by SidebarV2 and the board. +export const SETTLED_TAIL_INITIAL_COUNT = 10; +export const SETTLED_TAIL_PAGE_COUNT = 25; type SidebarProject = { id: string; title: string; @@ -94,6 +103,82 @@ export function buildMultiSelectThreadContextMenuItems(input: { ]; } +export type ThreadContextMenuAction = + | "rename" + | "mark-unread" + | "copy-path" + | "copy-thread-id" + | "delete"; + +export function buildThreadContextMenuItems(): readonly ContextMenuItem[] { + return [ + { id: "rename", label: "Rename thread" }, + { id: "mark-unread", label: "Mark unread" }, + { id: "copy-path", label: "Copy Path" }, + { id: "copy-thread-id", label: "Copy Thread ID" }, + { id: "delete", label: "Delete", destructive: true, icon: "trash" }, + ]; +} + +export type SidebarV2ThreadContextMenuAction = + | "new-thread-on-branch" + | "settle" + | "unsettle" + | "snooze" + | `snooze:${string}` + | "unsnooze" + | "rename" + | "mark-unread" + | "delete"; + +// Single source for the per-thread menu on both v2 surfaces (sidebar rows +// and board cards) so the two can't drift apart item-by-item. +export function buildSidebarV2ThreadContextMenuItems(input: { + branch: string | null; + supportsSettlement: boolean; + isSettled: boolean; + supportsSnooze: boolean; + isSnoozed: boolean; + canSnoozeNow: boolean; + snoozePresets: ReadonlyArray; +}): readonly ContextMenuItem[] { + return [ + ...(input.branch + ? [ + { + id: "new-thread-on-branch", + label: `New thread on ${input.branch}`, + } as const, + ] + : []), + ...(input.supportsSettlement + ? [ + input.isSettled + ? ({ id: "unsettle", label: "Un-settle thread" } as const) + : ({ id: "settle", label: "Settle thread" } as const), + ] + : []), + ...(input.supportsSnooze + ? [ + input.isSnoozed + ? ({ id: "unsnooze", label: "Wake thread" } as const) + : ({ + id: "snooze", + label: "Snooze", + disabled: !input.canSnoozeNow, + children: input.snoozePresets.map((preset) => ({ + id: `snooze:${preset.id}` as const, + label: `${preset.label} (${preset.whenLabel})`, + })), + } satisfies ContextMenuItem), + ] + : []), + { id: "rename", label: "Rename thread" }, + { id: "mark-unread", label: "Mark unread" }, + { id: "delete", label: "Delete", destructive: true, icon: "trash" }, + ]; +} + export interface ThreadStatusPill { label: | "Working" @@ -220,15 +305,63 @@ export function useThreadJumpHintVisibility(): { }; } +/** + * Whether `completedAt` is a completion the user has not seen yet: a missing + * last-visited timestamp counts as seen, an unparsable one as unseen. + */ +export function isCompletionUnseen( + completedAt: string | null | undefined, + lastVisitedAt: string | null | undefined, +): boolean { + if (!completedAt) return false; + const completedAtMs = Date.parse(completedAt); + if (Number.isNaN(completedAtMs)) return false; + if (!lastVisitedAt) return false; + + const lastVisitedAtMs = Date.parse(lastVisitedAt); + if (Number.isNaN(lastVisitedAtMs)) return true; + return completedAtMs > lastVisitedAtMs; +} + export function hasUnseenCompletion(thread: ThreadStatusInput): boolean { - if (!thread.latestTurn?.completedAt) return false; - const completedAt = Date.parse(thread.latestTurn.completedAt); - if (Number.isNaN(completedAt)) return false; - if (!thread.lastVisitedAt) return false; + return isCompletionUnseen(thread.latestTurn?.completedAt, thread.lastVisitedAt); +} - const lastVisitedAt = Date.parse(thread.lastVisitedAt); - if (Number.isNaN(lastVisitedAt)) return true; - return completedAt > lastVisitedAt; +/** + * Shared settled classification for display surfaces (sidebar v2, board), so + * they always agree on what is settled. Threads on servers without the + * settlement capability (old server, or descriptor not loaded yet) never + * classify as settled: the user could neither un-settle nor pin them, so + * auto-settling them would strand rows in a tail with no working affordances. + */ +export function isThreadSettledForDisplay( + thread: Parameters[0] & { readonly environmentId: string }, + input: { + serverConfigs: { + get(environmentId: string): + | { + readonly environment: { + readonly capabilities: { readonly threadSettlement?: boolean }; + }; + } + | undefined; + }; + now: string; + autoSettleAfterDays: number | null; + changeRequestState: ChangeRequestStateLike | null; + }, +): boolean { + const supportsSettlement = + input.serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === + true; + return ( + supportsSettlement && + effectiveSettled(thread, { + now: input.now, + autoSettleAfterDays: input.autoSettleAfterDays, + changeRequestState: input.changeRequestState, + }) + ); } export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean { @@ -424,6 +557,56 @@ export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2S return "ready"; } +export interface SidebarV2TopStatus { + label: "Working" | "Approval" | "Input" | "Failed" | "Done"; + icon: "working" | "done" | null; + className: string; +} + +// The v2 indicator presentation: colored label text (with an icon only for +// "in motion" and "done") instead of the v1 dot pill. Ready threads stay +// unlabeled unless they carry an unread completion, which surfaces as "Done". +export function resolveSidebarV2TopStatus(input: { + status: SidebarV2Status; + isUnread: boolean; +}): SidebarV2TopStatus | null { + switch (input.status) { + case "working": + return { + label: "Working", + icon: "working", + className: + "animate-sidebar-working-text text-sky-600 motion-reduce:animate-none dark:text-sky-400", + }; + case "approval": + return { + label: "Approval", + icon: null, + className: "text-amber-700 dark:text-amber-300", + }; + case "input": + return { + label: "Input", + icon: null, + className: "text-indigo-600 dark:text-indigo-300", + }; + case "failed": + return { + label: "Failed", + icon: null, + className: "text-red-700 dark:text-red-300", + }; + case "ready": + return input.isUnread + ? { + label: "Done", + icon: "done", + className: "text-emerald-700 dark:text-emerald-300", + } + : null; + } +} + /** NaN-safe Date.parse for sort comparators: a malformed timestamp must not poison the whole ordering, so it sinks to the epoch instead. */ export function parseTimestampMs(isoDate: string): number { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a1d95eaa734..d5fc28a533d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -8,6 +8,7 @@ import { Globe2Icon, LoaderIcon, SearchIcon, + SquareKanbanIcon, SquarePenIcon, TerminalIcon, TriangleAlertIcon, @@ -75,7 +76,7 @@ import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstra import { isElectron } from "../env"; import { useOpenPrLink } from "../lib/openPullRequestLink"; import { isTerminalFocused } from "../lib/terminalFocus"; -import { isMacPlatform } from "../lib/utils"; +import { cn, isMacPlatform } from "../lib/utils"; import { readThreadShell, useProject, @@ -172,6 +173,7 @@ import { openCommandPalette } from "../commandPaletteBus"; import { archiveSelectedThreadEntries, buildMultiSelectThreadContextMenuItems, + buildThreadContextMenuItems, getSidebarThreadIdsToPrewarm, resolveAdjacentThreadId, isContextMenuPointerDown, @@ -2488,6 +2490,42 @@ const SidebarProjectListRow = memo(function SidebarProjectListRow(props: Sidebar ); }); +// Self-contained so its router hooks don't force new props through the +// memoized sidebar content on every navigation. +function SidebarBoardLink({ shortcutLabel }: { shortcutLabel: string | null }) { + const navigate = useNavigate(); + const pathname = useLocation({ select: (location) => location.pathname }); + const { isMobile, setOpenMobile } = useSidebar(); + const isActive = pathname === "/board"; + + return ( + { + if (isMobile) { + setOpenMobile(false); + } + void navigate({ to: "/board" }); + }} + > + + Board + {shortcutLabel ? ( + {shortcutLabel} + ) : null} + + ); +} + function LocalSecondaryStatus() { const { environments } = useEnvironments(); // The desktop reports which local secondary backends (e.g. the WSL backend) @@ -2752,6 +2790,7 @@ interface SidebarProjectsContentProps { routeThreadKey: string | null; newThreadShortcutLabel: string | null; commandPaletteShortcutLabel: string | null; + boardShortcutLabel: string | null; threadJumpLabelByKey: ReadonlyMap; attachThreadListAutoAnimateRef: (node: HTMLElement | null) => void; expandThreadListForProject: (projectKey: string) => void; @@ -2792,6 +2831,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent( routeThreadKey, newThreadShortcutLabel, commandPaletteShortcutLabel, + boardShortcutLabel, threadJumpLabelByKey, attachThreadListAutoAnimateRef, expandThreadListForProject, @@ -2845,6 +2885,9 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent( ) : null} + + + {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( @@ -3413,6 +3456,16 @@ export default function Sidebar() { platform, context: shortcutContext, }); + if (command === "board.open") { + event.preventDefault(); + event.stopPropagation(); + if (isMobile) { + setOpenMobile(false); + } + void navigate({ to: "/board" }); + return; + } + const traversalDirection = threadTraversalDirectionFromCommand(command); if (traversalDirection !== null) { const targetThreadKey = resolveAdjacentThreadId({ @@ -3460,12 +3513,15 @@ export default function Sidebar() { }; }, [ getCurrentSidebarShortcutContext, + isMobile, keybindings, + navigate, navigateToThread, orderedSidebarThreadKeys, platform, routeThreadKey, sidebarThreadByKey, + setOpenMobile, threadJumpThreadKeys, ]); @@ -3498,6 +3554,11 @@ export default function Sidebar() { "commandPalette.toggle", newThreadShortcutLabelOptions, ); + const boardShortcutLabel = shortcutLabelForCommand( + keybindings, + "board.open", + newThreadShortcutLabelOptions, + ); const handleDesktopUpdateButtonClick = useCallback(() => { const bridge = window.desktopBridge; if (!bridge || !desktopUpdateState) return; @@ -3623,6 +3684,7 @@ export default function Sidebar() { routeThreadKey={routeThreadKey} newThreadShortcutLabel={newThreadShortcutLabel} commandPaletteShortcutLabel={commandPaletteShortcutLabel} + boardShortcutLabel={boardShortcutLabel} threadJumpLabelByKey={visibleThreadJumpLabelByKey} attachThreadListAutoAnimateRef={attachThreadListAutoAnimateRef} expandThreadListForProject={expandThreadListForProject} diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index 8c5891ebe7e..48bae67b553 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -31,6 +31,7 @@ import { PlusIcon, SearchIcon, ServerIcon, + SquareKanbanIcon, SquarePenIcon, Trash2Icon, Undo2Icon, @@ -46,7 +47,7 @@ import { type MouseEvent as ReactMouseEvent, type ReactNode, } from "react"; -import { useParams, useRouter } from "@tanstack/react-router"; +import { useLocation, useParams, useRouter } from "@tanstack/react-router"; import { isAtomCommandInterrupted, @@ -101,6 +102,9 @@ import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat" import type { SidebarThreadSummary } from "../types"; import { cn } from "~/lib/utils"; import { + SETTLED_TAIL_INITIAL_COUNT, + SETTLED_TAIL_PAGE_COUNT, + buildSidebarV2ThreadContextMenuItems, formatWorkingDurationLabel, firstValidTimestampMs, hasUnseenCompletion, @@ -154,10 +158,6 @@ import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover"; import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; import { useComposerDraftStore } from "../composerDraftStore"; -// Settled-tail paging: recent history is the common lookup; the deep tail -// stays behind an explicit Show more. -const SETTLED_TAIL_INITIAL_COUNT = 10; -const SETTLED_TAIL_PAGE_COUNT = 25; const PROJECT_GROUPING_MODE_LABELS: Record = { repository: "Group by repository", repository_path: "Group by repository path", @@ -1984,41 +1984,15 @@ export default function SidebarV2() { const snoozePresets = resolveSnoozePresets(new Date()); const clicked = await settlePromise(() => api.contextMenu.show( - [ - ...(thread.branch - ? [ - { - id: "new-thread-on-branch", - label: `New thread on ${thread.branch}`, - }, - ] - : []), - ...(supportsSettlement - ? [ - isSettled - ? { id: "unsettle", label: "Un-settle thread" } - : { id: "settle", label: "Settle thread" }, - ] - : []), - ...(supportsSnooze - ? [ - isSnoozed - ? { id: "unsnooze", label: "Wake thread" } - : { - id: "snooze", - label: "Snooze", - disabled: !canSnooze(thread, { now: new Date().toISOString() }), - children: snoozePresets.map((preset) => ({ - id: `snooze:${preset.id}`, - label: `${preset.label} (${preset.whenLabel})`, - })), - }, - ] - : []), - { id: "rename", label: "Rename thread" }, - { id: "mark-unread", label: "Mark unread" }, - { id: "delete", label: "Delete", destructive: true, icon: "trash" }, - ], + buildSidebarV2ThreadContextMenuItems({ + branch: thread.branch, + supportsSettlement, + isSettled, + supportsSnooze, + isSnoozed, + canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), + snoozePresets, + }), position, ), ); @@ -2132,6 +2106,13 @@ export default function SidebarV2() { modelPickerOpen: isModelPickerOpen(), }, }); + if (command === "board.open") { + event.preventDefault(); + event.stopPropagation(); + if (isMobile) setOpenMobile(false); + void router.navigate({ to: "/board" }); + return; + } const navigateToThreadKey = (targetThreadKey: string | null) => { if (!targetThreadKey) return false; const targetThread = threadByKey.get(targetThreadKey); @@ -2159,11 +2140,14 @@ export default function SidebarV2() { window.addEventListener("keydown", onWindowKeyDown); return () => window.removeEventListener("keydown", onWindowKeyDown); }, [ + isMobile, keybindings, navigateToThread, orderedThreadKeys, routeTerminalOpen, routeThreadKey, + router, + setOpenMobile, threadByKey, ]); @@ -2205,12 +2189,20 @@ export default function SidebarV2() { openCommandPalette({ open: "new-thread-in" }); }, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]); + const pathname = useLocation({ select: (l) => l.pathname }); + const isBoardActive = pathname === "/board"; + const handleBoardClick = useCallback(() => { + if (isMobile) setOpenMobile(false); + void router.navigate({ to: "/board" }); + }, [isMobile, router, setOpenMobile]); + const commandPaletteShortcutLabel = shortcutLabelForCommand(keybindings, "commandPalette.toggle"); // Same resolution as v1: prefer the local-thread binding, fall back to // chat.new, no platform gating — web users have working shortcuts too. const newThreadShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal") ?? shortcutLabelForCommand(keybindings, "chat.new"); + const boardShortcutLabel = shortcutLabelForCommand(keybindings, "board.open"); return ( <> @@ -2238,6 +2230,31 @@ export default function SidebarV2() { ) : null} +
+ + + } + > + + + + {boardShortcutLabel ? `Board (${boardShortcutLabel})` : "Board"} + + +
; +}) { + if (thread.interactionMode !== "plan") { + return null; + } + + return ( + + + } + > + + + Plan-only thread + + ); +} + +/** + * Renders in the status pill slot with the same visual language as + * `ThreadStatusLabel`. Settled-ness is context-dependent (auto-settle window, + * PR state, server capability), so callers decide when to render this instead + * of the indicator re-deriving it from the thread. + */ +export function ThreadSettledIndicator({ thread }: { thread: Pick }) { + return ( + + + } + > + + Settled + + Settled + + ); +} + +/** + * The sidebar-v2 status indicator: colored label text, with an icon only for + * the working and done states. Shared by the v2 sidebar rows and board cards + * so both surfaces speak the same status language. + */ +export function ThreadStatusV2Indicator({ + status, + className, +}: { + status: SidebarV2TopStatus; + className?: string; +}) { + return ( + + {status.icon === "working" ? ( + + ) : status.icon === "done" ? ( + + ) : null} + {status.label} + + ); +} + export function ThreadStatusLabel({ status, compact = false, diff --git a/apps/web/src/components/board/Board.logic.test.ts b/apps/web/src/components/board/Board.logic.test.ts new file mode 100644 index 00000000000..b6b5445fd23 --- /dev/null +++ b/apps/web/src/components/board/Board.logic.test.ts @@ -0,0 +1,607 @@ +import { EnvironmentId, ProjectId, type VcsStatusResult } from "@t3tools/contracts"; +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { describe, expect, it } from "vite-plus/test"; +import { + BOARD_ARCHIVE_DROPPABLE_ID, + BOARD_SETTLED_COLUMN_DROPPABLE_ID, + BOARD_TRASH_DROPPABLE_ID, + BOARD_UNSETTLE_DROPPABLE_ID, + boardWorktreeGroupDragId, + boardWorktreeKey, + buildBoardColumns, + buildBoardProjectFilterPredicate, + countBoardColumnThreads, + deriveBoardColumn, + parseBoardWorktreeGroupDragId, + resolveBoardDropIntent, + sliceBoardSettledItems, + sortBoardThreads, + type BoardColumnItem, + type BoardColumnInput, +} from "./Board.logic"; + +const localEnvironmentId = EnvironmentId.make("environment-local"); +const remoteEnvironmentId = EnvironmentId.make("environment-remote"); + +function columnThreadIds( + items: readonly BoardColumnItem[], +): string[] { + return items.flatMap((item) => + item.kind === "thread" ? [item.thread.id] : item.threads.map((thread) => thread.id), + ); +} + +function makeGitStatus(overrides: Partial = {}): VcsStatusResult { + return { + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "feature/board", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + ...overrides, + }; +} + +function makePr(state: "open" | "closed" | "merged"): NonNullable { + return { + number: 42, + title: "Board view", + url: "https://github.com/example/repo/pull/42", + baseRef: "main", + headRef: "feature/board", + state, + }; +} + +function makeColumnInput(overrides: Partial = {}): BoardColumnInput { + return { + threadStatusLabel: null, + interactionMode: "default", + isSettled: false, + latestTurnCompletedAt: null, + readySessionUpdatedAt: null, + lastVisitedAt: null, + threadBranch: "feature/board", + hasDedicatedWorktree: false, + hasWorkingThreadForWorktree: false, + gitStatus: makeGitStatus(), + ...overrides, + }; +} + +describe("deriveBoardColumn", () => { + it("puts attention status pills in review ahead of working or merged lifecycle state", () => { + const gitStatus = makeGitStatus({ pr: makePr("merged") }); + expect( + deriveBoardColumn(makeColumnInput({ threadStatusLabel: "Pending Approval", gitStatus })), + ).toBe("review"); + expect( + deriveBoardColumn(makeColumnInput({ threadStatusLabel: "Awaiting Input", gitStatus })), + ).toBe("review"); + expect( + deriveBoardColumn( + makeColumnInput({ + interactionMode: "plan", + threadStatusLabel: "Plan Ready", + gitStatus, + }), + ), + ).toBe("review"); + expect(deriveBoardColumn(makeColumnInput({ threadStatusLabel: "Completed", gitStatus }))).toBe( + "review", + ); + }); + + it("puts working and connecting status pills in working, even with a merged PR", () => { + const gitStatus = makeGitStatus({ pr: makePr("merged") }); + expect(deriveBoardColumn(makeColumnInput({ threadStatusLabel: "Working", gitStatus }))).toBe( + "working", + ); + expect(deriveBoardColumn(makeColumnInput({ threadStatusLabel: "Connecting", gitStatus }))).toBe( + "working", + ); + }); + + it("defaults to review while git status is unloaded or the cwd is not a repo", () => { + expect(deriveBoardColumn(makeColumnInput({ gitStatus: null }))).toBe("review"); + expect( + deriveBoardColumn(makeColumnInput({ gitStatus: makeGitStatus({ isRepo: false }) })), + ).toBe("review"); + }); + + it("ignores git status from a shared cwd checked out on a different branch", () => { + const gitStatus = makeGitStatus({ + refName: "someone-elses-branch", + hasWorkingTreeChanges: true, + pr: makePr("open"), + }); + expect(deriveBoardColumn(makeColumnInput({ gitStatus }))).toBe("review"); + }); + + it("applies git status from a dedicated worktree regardless of ref name", () => { + const gitStatus = makeGitStatus({ refName: "detached-head", hasWorkingTreeChanges: true }); + expect(deriveBoardColumn(makeColumnInput({ hasDedicatedWorktree: true, gitStatus }))).toBe( + "review", + ); + }); + + it("puts a branch ahead of upstream in review", () => { + expect( + deriveBoardColumn(makeColumnInput({ gitStatus: makeGitStatus({ aheadCount: 2 }) })), + ).toBe("review"); + }); + + it("puts a never-pushed branch ahead of (or with unknown distance to) the default in review", () => { + expect( + deriveBoardColumn( + makeColumnInput({ + gitStatus: makeGitStatus({ hasUpstream: false, aheadOfDefaultCount: 3 }), + }), + ), + ).toBe("review"); + expect( + deriveBoardColumn(makeColumnInput({ gitStatus: makeGitStatus({ hasUpstream: false }) })), + ).toBe("review"); + }); + + it("puts a clean fully pushed feature branch without a PR in published", () => { + expect(deriveBoardColumn(makeColumnInput())).toBe("published"); + }); + + it("puts an open PR with unpublished work in review", () => { + const gitStatus = makeGitStatus({ + hasWorkingTreeChanges: true, + pr: makePr("open"), + }); + expect(deriveBoardColumn(makeColumnInput({ gitStatus }))).toBe("review"); + }); + + it("does not move a sibling thread to review for a dirty worktree that is still working", () => { + const gitStatus = makeGitStatus({ + hasWorkingTreeChanges: true, + pr: makePr("open"), + }); + expect( + deriveBoardColumn( + makeColumnInput({ + hasDedicatedWorktree: true, + hasWorkingThreadForWorktree: true, + gitStatus, + }), + ), + ).toBe("published"); + }); + + it("still moves locally-ahead siblings to review while their worktree is working", () => { + expect( + deriveBoardColumn( + makeColumnInput({ + hasDedicatedWorktree: true, + hasWorkingThreadForWorktree: true, + gitStatus: makeGitStatus({ aheadCount: 1, pr: makePr("open") }), + }), + ), + ).toBe("review"); + }); + + it("puts a clean open PR in published", () => { + expect( + deriveBoardColumn(makeColumnInput({ gitStatus: makeGitStatus({ pr: makePr("open") }) })), + ).toBe("published"); + }); + + it("keeps an unsettled merged PR in published instead of guessing settled", () => { + expect( + deriveBoardColumn(makeColumnInput({ gitStatus: makeGitStatus({ pr: makePr("merged") }) })), + ).toBe("published"); + }); + + it("lets the settled flag win regardless of git or completion state", () => { + expect(deriveBoardColumn(makeColumnInput({ isSettled: true, gitStatus: null }))).toBe( + "settled", + ); + expect( + deriveBoardColumn( + makeColumnInput({ + isSettled: true, + gitStatus: makeGitStatus({ hasWorkingTreeChanges: true, aheadCount: 1 }), + }), + ), + ).toBe("settled"); + expect( + deriveBoardColumn(makeColumnInput({ isSettled: true, threadStatusLabel: "Completed" })), + ).toBe("settled"); + }); + + it("puts an unseen turn completion in review regardless of git state", () => { + const unseen = { + latestTurnCompletedAt: "2026-07-22T10:00:00.000Z", + lastVisitedAt: "2026-07-22T09:00:00.000Z", + }; + expect(deriveBoardColumn(makeColumnInput({ ...unseen, gitStatus: null }))).toBe("review"); + expect( + deriveBoardColumn( + makeColumnInput({ ...unseen, gitStatus: makeGitStatus({ pr: makePr("merged") }) }), + ), + ).toBe("review"); + }); + + it("keeps a working status pill in working even with an unseen completion", () => { + expect( + deriveBoardColumn( + makeColumnInput({ + threadStatusLabel: "Working", + latestTurnCompletedAt: "2026-07-22T10:00:00.000Z", + lastVisitedAt: "2026-07-22T09:00:00.000Z", + }), + ), + ).toBe("working"); + }); + + it("keeps a visited ready session in review when its latest turn summary is unavailable", () => { + expect( + deriveBoardColumn( + makeColumnInput({ + latestTurnCompletedAt: null, + readySessionUpdatedAt: "2026-07-22T03:45:04.819Z", + lastVisitedAt: "2026-07-22T03:45:04.819Z", + gitStatus: null, + }), + ), + ).toBe("review"); + }); + + it("lets in-flight git work outrank a seen completion", () => { + const seen = { + latestTurnCompletedAt: "2026-07-22T09:00:00.000Z", + lastVisitedAt: "2026-07-22T10:00:00.000Z", + }; + expect( + deriveBoardColumn( + makeColumnInput({ ...seen, gitStatus: makeGitStatus({ hasWorkingTreeChanges: true }) }), + ), + ).toBe("review"); + expect(deriveBoardColumn(makeColumnInput({ ...seen }))).toBe("published"); + }); + + it("keeps a plan-only thread's column off its worktree's git state", () => { + // This git state would classify as published; a plan-mode thread does not + // own it (the implementation thread does), so the plan thread stays in + // review until settled. + const badgelessPlan = { + interactionMode: "plan" as const, + threadStatusLabel: null, + hasDedicatedWorktree: true, + gitStatus: makeGitStatus({ pr: makePr("open") }), + }; + expect( + deriveBoardColumn(makeColumnInput({ ...badgelessPlan, interactionMode: "default" })), + ).toBe("published"); + expect(deriveBoardColumn(makeColumnInput(badgelessPlan))).toBe("review"); + expect(deriveBoardColumn(makeColumnInput({ ...badgelessPlan, isSettled: true }))).toBe( + "settled", + ); + }); + + it("puts a clean default branch in review", () => { + const gitStatus = makeGitStatus({ refName: "main", isDefaultRef: true }); + expect(deriveBoardColumn(makeColumnInput({ threadBranch: "main", gitStatus }))).toBe("review"); + }); +}); + +describe("sortBoardThreads", () => { + const byUpdatedAt = (thread: { updatedAt: string }) => thread.updatedAt; + + it("orders by the selected timestamp descending", () => { + const sorted = sortBoardThreads( + [ + { id: "thread-1", updatedAt: "2026-07-20T10:00:00.000Z" }, + { id: "thread-2", updatedAt: "2026-07-21T10:00:00.000Z" }, + { id: "thread-3", updatedAt: "2026-07-19T10:00:00.000Z" }, + ], + byUpdatedAt, + ); + expect(sorted.map((thread) => thread.id)).toEqual(["thread-2", "thread-1", "thread-3"]); + }); + + it("breaks timestamp ties by thread id", () => { + const sorted = sortBoardThreads( + [ + { id: "thread-b", updatedAt: "2026-07-20T10:00:00.000Z" }, + { id: "thread-a", updatedAt: "2026-07-20T10:00:00.000Z" }, + ], + byUpdatedAt, + ); + expect(sorted.map((thread) => thread.id)).toEqual(["thread-a", "thread-b"]); + }); + + it("sorts invalid timestamps last", () => { + const sorted = sortBoardThreads( + [ + { id: "thread-1", updatedAt: "not-a-date" }, + { id: "thread-2", updatedAt: "2026-07-20T10:00:00.000Z" }, + ], + byUpdatedAt, + ); + expect(sorted.map((thread) => thread.id)).toEqual(["thread-2", "thread-1"]); + }); +}); + +describe("buildBoardColumns", () => { + it("sorts working threads by active session start (falling back to update time) and other columns by update time", () => { + const threads = [ + { + id: "thread-review-old", + updatedAt: "2026-07-18T10:00:00.000Z", + workingStartedAt: null, + }, + { + id: "thread-review-new", + updatedAt: "2026-07-21T10:00:00.000Z", + workingStartedAt: null, + }, + { + id: "thread-working-old", + updatedAt: "2026-07-22T10:00:00.000Z", + workingStartedAt: "2026-07-19T10:00:00.000Z", + }, + { + id: "thread-working-new", + updatedAt: "2026-07-20T10:00:00.000Z", + workingStartedAt: "2026-07-21T10:00:00.000Z", + }, + { + id: "thread-working-fallback", + updatedAt: "2026-07-23T10:00:00.000Z", + workingStartedAt: null, + }, + ]; + const columns = buildBoardColumns( + threads, + (thread) => (thread.id.startsWith("thread-working") ? "working" : "review"), + (thread) => thread.workingStartedAt, + ); + expect(columnThreadIds(columns.review)).toEqual(["thread-review-new", "thread-review-old"]); + expect(columnThreadIds(columns.working)).toEqual([ + "thread-working-fallback", + "thread-working-new", + "thread-working-old", + ]); + expect(columns.published).toEqual([]); + expect(columns.settled).toEqual([]); + }); + + it("hosts shared groups in their earliest column and orders members by actual column then time", () => { + const threads = [ + { + id: "group-review-old", + updatedAt: "2026-07-19T10:00:00.000Z", + workingStartedAt: null, + column: "review" as const, + groupKey: "shared-worktree", + }, + { + id: "group-working-old", + updatedAt: "2026-07-24T10:00:00.000Z", + workingStartedAt: "2026-07-20T10:00:00.000Z", + column: "working" as const, + groupKey: "shared-worktree", + }, + { + id: "group-published", + updatedAt: "2026-07-25T10:00:00.000Z", + workingStartedAt: null, + column: "published" as const, + groupKey: "shared-worktree", + }, + { + id: "group-review-new", + updatedAt: "2026-07-23T10:00:00.000Z", + workingStartedAt: null, + column: "review" as const, + groupKey: "shared-worktree", + }, + { + id: "group-working-new", + updatedAt: "2026-07-18T10:00:00.000Z", + workingStartedAt: "2026-07-22T10:00:00.000Z", + column: "working" as const, + groupKey: "shared-worktree", + }, + ]; + const columns = buildBoardColumns( + threads, + (thread) => thread.column, + (thread) => thread.workingStartedAt, + (thread) => thread.groupKey, + ); + + expect(columns.working).toEqual([ + { + kind: "worktreeGroup", + worktreeKey: "shared-worktree", + threads: [threads[4], threads[1], threads[3], threads[0], threads[2]], + }, + ]); + expect(columns.review).toEqual([]); + expect(columns.published).toEqual([]); + expect(columns.settled).toEqual([]); + }); + + it("uses the earliest represented column rather than moving every group to working", () => { + const threads = [ + { + id: "standalone-working", + updatedAt: "2026-07-22T10:00:00.000Z", + column: "working" as const, + groupKey: null, + }, + { + id: "group-settled", + updatedAt: "2026-07-23T10:00:00.000Z", + column: "settled" as const, + groupKey: "later-group", + }, + { + id: "group-review", + updatedAt: "2026-07-21T10:00:00.000Z", + column: "review" as const, + groupKey: "later-group", + }, + ]; + const columns = buildBoardColumns( + threads, + (thread) => thread.column, + () => null, + (thread) => thread.groupKey, + ); + + expect(columns.working).toEqual([{ kind: "thread", thread: threads[0] }]); + expect(columns.review).toEqual([ + { + kind: "worktreeGroup", + worktreeKey: "later-group", + threads: [threads[2], threads[1]], + }, + ]); + expect(columns.settled).toEqual([]); + }); +}); + +describe("countBoardColumnThreads", () => { + it("counts a worktree group as its member count", () => { + const items: BoardColumnItem<{ readonly id: string }>[] = [ + { kind: "thread", thread: { id: "thread-1" } }, + { + kind: "worktreeGroup", + worktreeKey: "shared-worktree", + threads: [{ id: "thread-2" }, { id: "thread-3" }], + }, + ]; + expect(countBoardColumnThreads(items)).toBe(3); + expect(countBoardColumnThreads([])).toBe(0); + }); +}); + +describe("sliceBoardSettledItems", () => { + const thread = (id: string): BoardColumnItem<{ readonly id: string }> => ({ + kind: "thread", + thread: { id }, + }); + const group = ( + worktreeKey: string, + ...ids: string[] + ): BoardColumnItem<{ readonly id: string }> => ({ + kind: "worktreeGroup", + worktreeKey, + threads: ids.map((id) => ({ id })), + }); + + it("returns the same array with no hidden count when the total fits the limit", () => { + const items = [thread("thread-1"), group("shared-worktree", "thread-2", "thread-3")]; + const result = sliceBoardSettledItems(items, 3); + expect(result.visibleItems).toBe(items); + expect(result.hiddenThreadCount).toBe(0); + }); + + it("slices plain thread items at the limit", () => { + const items = [thread("thread-1"), thread("thread-2"), thread("thread-3")]; + const result = sliceBoardSettledItems(items, 2); + expect(columnThreadIds(result.visibleItems)).toEqual(["thread-1", "thread-2"]); + expect(result.hiddenThreadCount).toBe(1); + }); + + it("includes a group straddling the limit whole and counts its members", () => { + const items = [ + thread("thread-1"), + group("shared-worktree", "thread-2", "thread-3", "thread-4"), + thread("thread-5"), + ]; + const result = sliceBoardSettledItems(items, 2); + expect(result.visibleItems).toEqual([items[0], items[1]]); + expect(result.hiddenThreadCount).toBe(1); + }); + + it("returns no visible items for a zero limit with non-empty input", () => { + const items = [thread("thread-1"), thread("thread-2")]; + const result = sliceBoardSettledItems(items, 0); + expect(result.visibleItems).toEqual([]); + expect(result.hiddenThreadCount).toBe(2); + }); +}); + +describe("buildBoardProjectFilterPredicate", () => { + const projectId = ProjectId.make("project-1"); + const otherProjectId = ProjectId.make("project-2"); + const snapshots = [ + { + projectKey: "logical-project-1", + memberProjectRefs: [ + scopeProjectRef(localEnvironmentId, projectId), + scopeProjectRef(remoteEnvironmentId, projectId), + ], + }, + ]; + + it("matches everything when no project is selected or the stored key no longer resolves", () => { + const noSelection = buildBoardProjectFilterPredicate({ selectedProjectKey: null, snapshots }); + expect(noSelection({ environmentId: localEnvironmentId, projectId: otherProjectId })).toBe( + true, + ); + const staleSelection = buildBoardProjectFilterPredicate({ + selectedProjectKey: "removed-project", + snapshots, + }); + expect(staleSelection({ environmentId: localEnvironmentId, projectId: otherProjectId })).toBe( + true, + ); + }); + + it("matches threads from any member project of the selected group", () => { + const predicate = buildBoardProjectFilterPredicate({ + selectedProjectKey: "logical-project-1", + snapshots, + }); + expect(predicate({ environmentId: localEnvironmentId, projectId })).toBe(true); + expect(predicate({ environmentId: remoteEnvironmentId, projectId })).toBe(true); + expect(predicate({ environmentId: localEnvironmentId, projectId: otherProjectId })).toBe(false); + }); +}); + +describe("boardWorktreeKey", () => { + it("returns null without a dedicated worktree", () => { + expect(boardWorktreeKey({ environmentId: localEnvironmentId, worktreePath: null })).toBeNull(); + expect(boardWorktreeKey({ environmentId: localEnvironmentId, worktreePath: " " })).toBeNull(); + }); +}); + +describe("resolveBoardDropIntent", () => { + it("maps the drop-zone droppables to their intents and everything else to null", () => { + expect(resolveBoardDropIntent(BOARD_ARCHIVE_DROPPABLE_ID)).toBe("archive"); + expect(resolveBoardDropIntent(BOARD_TRASH_DROPPABLE_ID)).toBe("trash"); + expect(resolveBoardDropIntent(BOARD_UNSETTLE_DROPPABLE_ID)).toBe("unsettle"); + expect(resolveBoardDropIntent(BOARD_SETTLED_COLUMN_DROPPABLE_ID)).toBe("settle"); + expect(resolveBoardDropIntent("board-column-review")).toBeNull(); + expect(resolveBoardDropIntent(null)).toBeNull(); + }); +}); + +describe("parseBoardWorktreeGroupDragId", () => { + it("round-trips the worktree key through the group drag id and rejects thread drag ids", () => { + const worktreeKey = boardWorktreeKey({ + environmentId: localEnvironmentId, + worktreePath: "/wt", + }); + expect(worktreeKey).not.toBeNull(); + const dragId = boardWorktreeGroupDragId(worktreeKey ?? ""); + + expect(dragId).not.toBe(worktreeKey); + expect(parseBoardWorktreeGroupDragId(dragId)).toBe(worktreeKey); + expect(parseBoardWorktreeGroupDragId("environment-local thread-1")).toBeNull(); + }); +}); diff --git a/apps/web/src/components/board/Board.logic.ts b/apps/web/src/components/board/Board.logic.ts new file mode 100644 index 00000000000..8414edbc3a4 --- /dev/null +++ b/apps/web/src/components/board/Board.logic.ts @@ -0,0 +1,385 @@ +import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment"; +import type { + EnvironmentId, + ProjectId, + ProviderInteractionMode, + ScopedProjectRef, + VcsStatusResult, +} from "@t3tools/contracts"; +import { toSortableTimestamp } from "../../lib/threadSort"; +import { isCompletionUnseen, type ThreadStatusPill } from "../Sidebar.logic"; +import { resolveThreadPr } from "../ThreadStatusIndicators"; + +export type BoardColumnId = "working" | "review" | "published" | "settled"; + +export const BOARD_COLUMN_IDS: readonly BoardColumnId[] = [ + "working", + "review", + "published", + "settled", +]; + +export const BOARD_COLUMN_LABELS: Record = { + working: "Working", + review: "Review", + published: "Published", + settled: "Settled", +}; + +export const BOARD_TRASH_DROPPABLE_ID = "board-trash"; +export const BOARD_ARCHIVE_DROPPABLE_ID = "board-archive"; +export const BOARD_UNSETTLE_DROPPABLE_ID = "board-unsettle"; +export const BOARD_SETTLED_COLUMN_DROPPABLE_ID = "board-column-settled"; + +export type BoardDropIntent = "archive" | "trash" | "settle" | "unsettle"; + +/** Drag-overlay feedback per drop intent, shared by the card and group overlays. */ +export const BOARD_DROP_INTENT_OVERLAY_CLASSES: Record = { + archive: "scale-90 border-amber-500 opacity-60", + trash: "scale-90 border-destructive opacity-60", + settle: "scale-90 border-primary opacity-60", + unsettle: "scale-90 border-emerald-500 opacity-60", +}; + +/** + * Intent implied by the droppable currently under the pointer, or null when + * the drag is over neither zone. Drives feedback on the dragged card itself — + * the card usually covers the drop zone, hiding the zone's own highlight. + */ +export function resolveBoardDropIntent( + droppableId: string | number | null | undefined, +): BoardDropIntent | null { + if (droppableId === BOARD_ARCHIVE_DROPPABLE_ID) return "archive"; + if (droppableId === BOARD_TRASH_DROPPABLE_ID) return "trash"; + if (droppableId === BOARD_UNSETTLE_DROPPABLE_ID) return "unsettle"; + if (droppableId === BOARD_SETTLED_COLUMN_DROPPABLE_ID) return "settle"; + return null; +} + +const BOARD_WORKTREE_GROUP_DRAG_PREFIX = "board-worktree-group\u0000"; + +/** Draggable id for a whole worktree group; drops act on every member thread. */ +export function boardWorktreeGroupDragId(worktreeKey: string): string { + return `${BOARD_WORKTREE_GROUP_DRAG_PREFIX}${worktreeKey}`; +} + +/** Worktree key encoded in a group draggable id, or null for thread drags. */ +export function parseBoardWorktreeGroupDragId( + dragId: string | number | null | undefined, +): string | null { + return typeof dragId === "string" && dragId.startsWith(BOARD_WORKTREE_GROUP_DRAG_PREFIX) + ? dragId.slice(BOARD_WORKTREE_GROUP_DRAG_PREFIX.length) + : null; +} + +export interface BoardColumnInput { + threadStatusLabel: ThreadStatusPill["label"] | null; + interactionMode: ProviderInteractionMode; + isSettled: boolean; + latestTurnCompletedAt: string | null; + readySessionUpdatedAt: string | null; + lastVisitedAt: string | null; + threadBranch: string | null; + hasDedicatedWorktree: boolean; + hasWorkingThreadForWorktree: boolean; + gitStatus: VcsStatusResult | null; +} + +/** + * Whether the thread completed after the user's last visit. Falls back to the + * ready-session timestamp for providers whose shell cannot retain a + * latest-turn summary; both sources follow the sidebar's `isCompletionUnseen` + * rules. + */ +export function hasUnseenBoardCompletion( + input: Pick< + BoardColumnInput, + "latestTurnCompletedAt" | "readySessionUpdatedAt" | "lastVisitedAt" + >, +): boolean { + return isCompletionUnseen( + input.latestTurnCompletedAt ?? input.readySessionUpdatedAt, + input.lastVisitedAt, + ); +} + +/** + * Cache key for the board's aggregated VCS status map. Matches the dedupe + * granularity of the underlying subscription family: one entry per unique + * (environmentId, cwd) pair. + */ +export function boardGitKey(environmentId: EnvironmentId, cwd: string): string { + return `${environmentId}\u0000${cwd}`; +} + +/** + * Git status a thread may be attributed at all, or null. Threads sharing the + * project-root cwd must not inherit another branch's state, so without a + * dedicated worktree the checked-out ref has to match the thread's branch. + */ +export function resolveAppliedBoardGitStatus( + input: Pick, +): VcsStatusResult | null { + if (input.gitStatus === null || !input.gitStatus.isRepo) { + return null; + } + if (input.hasDedicatedWorktree) { + return input.gitStatus; + } + return input.threadBranch !== null && input.gitStatus.refName === input.threadBranch + ? input.gitStatus + : null; +} + +/** + * Lifecycle column for a thread. The server-backed settled flag is + * authoritative — safe to check first because `effectiveSettled` is never + * true for running or blocked threads, and it keeps a just-settled card from + * bouncing back to review on an unseen completion pill. Attention states win + * over the remaining lifecycle states: a thread blocked on the user + * (question/permission prompt) or holding an unseen completion sits in + * "review" regardless of git state. An actionable ready plan is also always + * reviewable. Git-driven columns still only move a card rightward as statuses + * stream in: unknown/unattributable git state falls through instead of + * guessing. + */ +export function deriveBoardColumn(input: BoardColumnInput): BoardColumnId { + if (input.isSettled) { + return "settled"; + } + + switch (input.threadStatusLabel) { + case "Pending Approval": + case "Awaiting Input": + case "Plan Ready": + case "Completed": + return "review"; + case "Working": + case "Connecting": + return "working"; + case null: + break; + default: { + const exhaustiveStatusLabel: never = input.threadStatusLabel; + return exhaustiveStatusLabel; + } + } + + if (hasUnseenBoardCompletion(input)) { + return "review"; + } + + // A plan-mode thread does not own worktree changes made by the separate + // implementation thread that consumed its plan. Keep its column tied to + // its own attention/completion state instead of the shared worktree. + const gitStatus = input.interactionMode === "plan" ? null : resolveAppliedBoardGitStatus(input); + if (gitStatus !== null) { + const hasUnpublishedWork = + (gitStatus.hasWorkingTreeChanges && !input.hasWorkingThreadForWorktree) || + gitStatus.aheadCount > 0 || + (!gitStatus.hasUpstream && (gitStatus.aheadOfDefaultCount ?? 0) > 0); + if (hasUnpublishedWork) { + return "review"; + } + + // A merged PR is not special-cased here: it settles the thread through + // `effectiveSettled` upstream. When that is unavailable (pinned active, + // server without the settlement capability) the branch classifies by its + // git state alone, since it could not be moved out of Settled anyway. + const pr = resolveThreadPr(input); + const isCleanPushedFeatureBranch = + gitStatus.aheadCount === 0 && gitStatus.hasUpstream && !gitStatus.isDefaultRef; + if (pr?.state === "open" || isCleanPushedFeatureBranch) { + return "published"; + } + } + + return "review"; +} + +export interface BoardSortableThread { + readonly id: string; + readonly updatedAt: string; +} + +/** Sorts board threads newest-first by the timestamp selected for the column. */ +export function sortBoardThreads( + threads: readonly T[], + getSortTimestamp: (thread: T) => string | null, +): T[] { + return [...threads].sort((left, right) => { + const leftTimestamp = + toSortableTimestamp(getSortTimestamp(left) ?? undefined) ?? Number.NEGATIVE_INFINITY; + const rightTimestamp = + toSortableTimestamp(getSortTimestamp(right) ?? undefined) ?? Number.NEGATIVE_INFINITY; + if (leftTimestamp !== rightTimestamp) { + return rightTimestamp > leftTimestamp ? 1 : -1; + } + return left.id < right.id ? -1 : left.id > right.id ? 1 : 0; + }); +} + +export type BoardColumnItem = + | { readonly kind: "thread"; readonly thread: T } + | { + readonly kind: "worktreeGroup"; + readonly worktreeKey: string; + readonly threads: readonly T[]; + }; + +/** + * Builds board items in lifecycle order. A shared group is emitted on its + * first encounter, which is its earliest column and most recent member there. + * Its members are already ordered by actual column, then that column's time. + */ +export function buildBoardColumns( + threads: readonly T[], + getColumn: (thread: T) => BoardColumnId, + getWorkingStartedAt: (thread: T) => string | null, + getGroupKey: (thread: T) => string | null = () => null, +): Record[]> { + const threadsByColumn: Record = { + working: [], + review: [], + published: [], + settled: [], + }; + for (const thread of threads) { + threadsByColumn[getColumn(thread)].push(thread); + } + for (const columnId of BOARD_COLUMN_IDS) { + threadsByColumn[columnId] = sortBoardThreads( + threadsByColumn[columnId], + columnId === "working" + ? (thread) => getWorkingStartedAt(thread) ?? thread.updatedAt + : (thread) => thread.updatedAt, + ); + } + + const groupMembersByKey = new Map(); + for (const columnId of BOARD_COLUMN_IDS) { + for (const thread of threadsByColumn[columnId]) { + const groupKey = getGroupKey(thread); + if (groupKey === null) { + continue; + } + const members = groupMembersByKey.get(groupKey); + if (members) { + members.push(thread); + } else { + groupMembersByKey.set(groupKey, [thread]); + } + } + } + + const columns: Record[]> = { + working: [], + review: [], + published: [], + settled: [], + }; + const emittedGroupKeys = new Set(); + for (const columnId of BOARD_COLUMN_IDS) { + for (const thread of threadsByColumn[columnId]) { + const groupKey = getGroupKey(thread); + const groupMembers = groupKey === null ? undefined : groupMembersByKey.get(groupKey); + if (groupKey === null || groupMembers === undefined || groupMembers.length < 2) { + columns[columnId].push({ kind: "thread", thread }); + continue; + } + if (emittedGroupKeys.has(groupKey)) { + continue; + } + emittedGroupKeys.add(groupKey); + columns[columnId].push({ + kind: "worktreeGroup", + worktreeKey: groupKey, + threads: groupMembers, + }); + } + } + return columns; +} + +/** Total threads across column items; a worktree group counts each member. */ +export function countBoardColumnThreads(items: readonly BoardColumnItem[]): number { + return items.reduce( + (count, item) => count + (item.kind === "thread" ? 1 : item.threads.length), + 0, + ); +} + +/** + * Settled-tail slice for the board column. The limit counts threads (a + * worktree group counts as its member count) so paging matches the sidebar's + * thread-based tail; a group straddling the limit is included whole since a + * group card cannot render partially. + */ +export function sliceBoardSettledItems( + items: readonly BoardColumnItem[], + limit: number, +): { visibleItems: readonly BoardColumnItem[]; hiddenThreadCount: number } { + const total = countBoardColumnThreads(items); + if (total <= limit) { + return { visibleItems: items, hiddenThreadCount: 0 }; + } + const visibleItems: BoardColumnItem[] = []; + let shown = 0; + for (const item of items) { + if (shown >= limit) break; + visibleItems.push(item); + shown += item.kind === "thread" ? 1 : item.threads.length; + } + return { visibleItems, hiddenThreadCount: total - shown }; +} + +export interface BoardWorktreeThread { + readonly environmentId: EnvironmentId; + readonly worktreePath: string | null; +} + +/** + * Identity of a thread's dedicated worktree for board grouping, or null when + * the thread runs in the shared project checkout. Only dedicated worktrees + * group: threads in the project root are unrelated lines of work even though + * they share a checkout. + */ +export function boardWorktreeKey(thread: BoardWorktreeThread): string | null { + const worktreePath = thread.worktreePath?.trim(); + if (!worktreePath) { + return null; + } + return `${thread.environmentId}\u0000${worktreePath}`; +} + +export interface BoardProjectFilterThread { + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; +} + +/** + * Predicate matching threads against a selected sidebar project group. + * Membership is by scoped project ref so locally+remotely-open copies of the + * same repository stay one entry, matching the sidebar's grouping. An + * unresolvable stored key (project removed, grouping changed) matches + * everything, i.e. falls back to "All projects". + */ +export function buildBoardProjectFilterPredicate(input: { + selectedProjectKey: string | null; + snapshots: ReadonlyArray<{ + readonly projectKey: string; + readonly memberProjectRefs: readonly ScopedProjectRef[]; + }>; +}): (thread: BoardProjectFilterThread) => boolean { + const selectedSnapshot = + input.selectedProjectKey === null + ? null + : (input.snapshots.find((snapshot) => snapshot.projectKey === input.selectedProjectKey) ?? + null); + if (selectedSnapshot === null) { + return () => true; + } + const memberKeys = new Set(selectedSnapshot.memberProjectRefs.map(scopedProjectKey)); + return (thread) => + memberKeys.has(scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId))); +} diff --git a/apps/web/src/components/board/BoardCard.test.tsx b/apps/web/src/components/board/BoardCard.test.tsx new file mode 100644 index 00000000000..5ed33b8c54e --- /dev/null +++ b/apps/web/src/components/board/BoardCard.test.tsx @@ -0,0 +1,200 @@ +import { DndContext } from "@dnd-kit/core"; +import { + DEFAULT_RUNTIME_MODE, + EnvironmentId, + ProjectId, + ProviderInstanceId, + ThreadId, + type VcsStatusResult, +} from "@t3tools/contracts"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vite-plus/test"; + +import type { SidebarThreadSummary } from "../../types"; +import { BoardCard, BoardCardDragOverlay } from "./BoardCard"; + +const environmentId = EnvironmentId.make("environment-local"); + +function makeThread(overrides: Partial = {}): SidebarThreadSummary { + return { + id: ThreadId.make("thread-1"), + environmentId, + projectId: ProjectId.make("project-1"), + title: "Fix board keyboard semantics", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: DEFAULT_RUNTIME_MODE, + interactionMode: "default", + session: null, + createdAt: "2026-07-22T09:00:00.000Z", + updatedAt: "2026-07-22T10:00:00.000Z", + archivedAt: null, + latestTurn: null, + latestUserMessageAt: "2026-07-22T09:30:00.000Z", + branch: "feature/board", + worktreePath: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + settledOverride: null, + settledAt: null, + ...overrides, + }; +} + +function makeGitStatus(): VcsStatusResult { + return { + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "feature/board", + hasWorkingTreeChanges: false, + workingTree: { files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: { + number: 42, + title: "Board controls", + url: "https://github.com/example/repo/pull/42", + baseRef: "main", + headRef: "feature/board", + state: "open", + }, + }; +} + +function renderCard(thread: SidebarThreadSummary = makeThread(), isSettled = false): string { + return renderToStaticMarkup( + + {}} + onShowContextMenu={() => {}} + dragClickGuard={{ + startDrag: () => {}, + finishDrag: () => {}, + consumeSuppressedClick: () => false, + dispose: () => {}, + }} + /> + , + ); +} + +describe("BoardCard", () => { + it("uses a noninteractive card root and a native open-thread button", () => { + const markup = renderCard(); + const rootTag = markup.match(/]*data-testid="board-card-thread-1"[^>]*>/)?.[0]; + + expect(rootTag).toBeDefined(); + expect(rootTag).not.toContain('role="button"'); + expect(rootTag).not.toContain('tabindex="0"'); + expect(markup).toContain('", openButtonStart); + const prButtonStart = markup.indexOf(' + ) : ( + + #{pr.number} + + ) + ) : null} + {dirtyFileCount > 0 ? ( + + {dirtyFileCount} {dirtyFileCount === 1 ? "file" : "files"} + + ) : null} + {aheadCount > 0 ? ( + ↑{aheadCount} + ) : null} + {gitStatusPending ? ( + + ) : null} + + + {driverKind ? ( + + } + > + + + {modelLabel} + + ) : null} + +
+ + ); +} + +export const BoardCard = memo(function BoardCard({ + thread, + project, + gitStatus, + gitStatusPending, + isSettled, + onOpenThread, + onShowContextMenu, + dragClickGuard, +}: BoardCardProps) { + const threadRef = scopeThreadRef(thread.environmentId, thread.id); + const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ + id: scopedThreadKey(threadRef), + data: { threadRef }, + }); + + const openThread = () => { + if (dragClickGuard.consumeSuppressedClick()) { + return; + } + onOpenThread(threadRef); + }; + + const showContextMenu = (event: MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + onShowContextMenu(thread, { x: event.clientX, y: event.clientY }); + }; + + return ( +
+ { + event.stopPropagation(); + openThread(); + }} + /> +
+ ); +}); + +/** Non-interactive clone rendered inside the DragOverlay while dragging. */ +export function BoardCardDragOverlay({ + thread, + project, + gitStatus, + gitStatusPending, + isSettled, + dropIntent = null, +}: Pick & { + dropIntent?: BoardDropIntent | null; +}) { + return ( + + ); +} diff --git a/apps/web/src/components/board/BoardColumn.tsx b/apps/web/src/components/board/BoardColumn.tsx new file mode 100644 index 00000000000..88d2ef79ea9 --- /dev/null +++ b/apps/web/src/components/board/BoardColumn.tsx @@ -0,0 +1,68 @@ +import { useDroppable } from "@dnd-kit/core"; +import type { ReactNode } from "react"; + +import { cn } from "../../lib/utils"; +import { ScrollArea } from "../ui/scroll-area"; +import { BOARD_COLUMN_LABELS, type BoardColumnId } from "./Board.logic"; + +/** Small rounded count pill used by column headers and worktree groups. */ +export function BoardCountPill({ count, className }: { count: number; className?: string }) { + return ( + + {count} + + ); +} + +export function BoardColumn({ + columnId, + count, + children, +}: { + columnId: BoardColumnId; + count: number; + children: ReactNode; +}) { + // Only the settled column accepts drops (dropping a card there settles the + // thread); the droppable ids are per-column so the intent resolver only + // matches the settled one. + const { isOver, setNodeRef } = useDroppable({ + id: `board-column-${columnId}`, + disabled: columnId !== "settled", + }); + + return ( +
+
+ {BOARD_COLUMN_LABELS[columnId]} + +
+ {/* Horizontal touch pans must chain to the board's scroll container; + the viewport's default overscroll containment would swallow them. */} + +
+ {count === 0 ? ( +
+ No threads +
+ ) : ( + children + )} +
+
+
+ ); +} diff --git a/apps/web/src/components/board/BoardDragClickGuard.test.ts b/apps/web/src/components/board/BoardDragClickGuard.test.ts new file mode 100644 index 00000000000..b35ef0580d0 --- /dev/null +++ b/apps/web/src/components/board/BoardDragClickGuard.test.ts @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { createBoardDragClickGuard } from "./BoardDragClickGuard"; + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("createBoardDragClickGuard", () => { + it("does not suppress ordinary clicks", () => { + const guard = createBoardDragClickGuard(); + + expect(guard.consumeSuppressedClick()).toBe(false); + }); + + it("suppresses the click generated when a drag finishes", () => { + const guard = createBoardDragClickGuard(); + + guard.startDrag(); + guard.finishDrag(); + + expect(guard.consumeSuppressedClick()).toBe(true); + expect(guard.consumeSuppressedClick()).toBe(false); + }); + + it("releases suppression when a finished drag produces no click", () => { + vi.useFakeTimers(); + const guard = createBoardDragClickGuard(); + + guard.startDrag(); + guard.finishDrag(); + vi.runOnlyPendingTimers(); + + expect(guard.consumeSuppressedClick()).toBe(false); + }); + + it("does not let an earlier reset clear suppression for a newer drag", () => { + vi.useFakeTimers(); + const guard = createBoardDragClickGuard(); + + guard.startDrag(); + guard.finishDrag(); + guard.startDrag(); + vi.runOnlyPendingTimers(); + + expect(guard.consumeSuppressedClick()).toBe(true); + }); +}); diff --git a/apps/web/src/components/board/BoardDragClickGuard.ts b/apps/web/src/components/board/BoardDragClickGuard.ts new file mode 100644 index 00000000000..cd99579db08 --- /dev/null +++ b/apps/web/src/components/board/BoardDragClickGuard.ts @@ -0,0 +1,47 @@ +export interface BoardDragClickGuard { + startDrag: () => void; + finishDrag: () => void; + consumeSuppressedClick: () => boolean; + dispose: () => void; +} + +/** + * Prevents the click synthesized by the pointer release that finishes a drag + * from opening a thread. If that release produces no click, the suppression + * expires on the next task instead of swallowing a later, intentional click. + */ +export function createBoardDragClickGuard(): BoardDragClickGuard { + let suppressClick = false; + let resetTimer: ReturnType | null = null; + + const clearResetTimer = () => { + if (resetTimer !== null) { + clearTimeout(resetTimer); + resetTimer = null; + } + }; + + return { + startDrag() { + clearResetTimer(); + suppressClick = true; + }, + finishDrag() { + clearResetTimer(); + resetTimer = setTimeout(() => { + suppressClick = false; + resetTimer = null; + }, 0); + }, + consumeSuppressedClick() { + if (!suppressClick) { + return false; + } + suppressClick = false; + return true; + }, + dispose() { + clearResetTimer(); + }, + }; +} diff --git a/apps/web/src/components/board/BoardDropZones.tsx b/apps/web/src/components/board/BoardDropZones.tsx new file mode 100644 index 00000000000..5c613567749 --- /dev/null +++ b/apps/web/src/components/board/BoardDropZones.tsx @@ -0,0 +1,78 @@ +import { useDroppable } from "@dnd-kit/core"; +import { ArchiveIcon, ArchiveRestoreIcon, Trash2Icon, type LucideIcon } from "lucide-react"; + +import { cn } from "../../lib/utils"; +import { + BOARD_ARCHIVE_DROPPABLE_ID, + BOARD_TRASH_DROPPABLE_ID, + BOARD_UNSETTLE_DROPPABLE_ID, +} from "./Board.logic"; + +function BoardDropZone({ + droppableId, + testId, + label, + icon: Icon, + activeClass, +}: { + droppableId: string; + testId: string; + label: string; + icon: LucideIcon; + activeClass: string; +}) { + const { isOver, setNodeRef } = useDroppable({ id: droppableId }); + + return ( +
+ + {label} +
+ ); +} + +/** + * Floating droppables shown while a drag is active: archive and delete are + * always available, and restore (un-settle) appears when the drag includes a + * settled thread. Columns are derived state, so settling happens by dropping + * on the Settled column itself rather than a zone here. + */ +export function BoardDropZones({ showRestoreZone }: { showRestoreZone: boolean }) { + return ( + // w-max: shrink-to-fit against left:50% would otherwise cap the width at + // half the board and wrap the labels on narrow viewports. +
+ {showRestoreZone ? ( + + ) : null} + + +
+ ); +} diff --git a/apps/web/src/components/board/BoardScroll.test.ts b/apps/web/src/components/board/BoardScroll.test.ts new file mode 100644 index 00000000000..2a8ad4744e7 --- /dev/null +++ b/apps/web/src/components/board/BoardScroll.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { scrollBoardFromWheel, shouldScrollColumnFromWheel } from "./BoardScroll"; + +function makeContainer(overrides: Partial = {}): MockScrollContainer { + return { + clientWidth: 500, + scrollLeft: 200, + scrollWidth: 1_500, + ...overrides, + }; +} + +interface MockScrollContainer { + clientWidth: number; + scrollLeft: number; + scrollWidth: number; +} + +describe("shouldScrollColumnFromWheel", () => { + const verticalWheel = { deltaX: 0, deltaY: 50 }; + + it("keeps vertical wheel movement in a column that can scroll in that direction", () => { + expect( + shouldScrollColumnFromWheel( + { clientHeight: 500, scrollHeight: 1_000, scrollTop: 200 }, + verticalWheel, + ), + ).toBe(true); + expect( + shouldScrollColumnFromWheel( + { clientHeight: 500, scrollHeight: 1_000, scrollTop: 200 }, + { deltaX: 0, deltaY: -50 }, + ), + ).toBe(true); + }); + + it("releases vertical movement to the board at the matching column edge", () => { + expect( + shouldScrollColumnFromWheel( + { clientHeight: 500, scrollHeight: 1_000, scrollTop: 500 }, + verticalWheel, + ), + ).toBe(false); + expect( + shouldScrollColumnFromWheel( + { clientHeight: 500, scrollHeight: 1_000, scrollTop: 0 }, + { deltaX: 0, deltaY: -50 }, + ), + ).toBe(false); + }); + + it("releases horizontal gestures and non-overflowing columns to the board", () => { + expect( + shouldScrollColumnFromWheel( + { clientHeight: 500, scrollHeight: 1_000, scrollTop: 200 }, + { deltaX: 50, deltaY: 10 }, + ), + ).toBe(false); + expect( + shouldScrollColumnFromWheel( + { clientHeight: 500, scrollHeight: 500, scrollTop: 0 }, + verticalWheel, + ), + ).toBe(false); + }); +}); + +describe("scrollBoardFromWheel", () => { + it("maps vertical wheel movement to horizontal board movement", () => { + const container = makeContainer(); + + expect( + scrollBoardFromWheel(container, { + ctrlKey: false, + deltaMode: 0, + deltaX: 0, + deltaY: 80, + }), + ).toBe(true); + expect(container.scrollLeft).toBe(280); + + scrollBoardFromWheel(container, { + ctrlKey: false, + deltaMode: 0, + deltaX: 0, + deltaY: -50, + }); + expect(container.scrollLeft).toBe(230); + + // Horizontal trackpad movement wins when it is the dominant axis. + scrollBoardFromWheel(container, { + ctrlKey: false, + deltaMode: 0, + deltaX: 60, + deltaY: 10, + }); + expect(container.scrollLeft).toBe(290); + }); + + it("normalizes line and page wheel deltas", () => { + const lineContainer = makeContainer(); + const pageContainer = makeContainer(); + + scrollBoardFromWheel(lineContainer, { + ctrlKey: false, + deltaMode: 1, + deltaX: 0, + deltaY: 2, + }); + scrollBoardFromWheel(pageContainer, { + ctrlKey: false, + deltaMode: 2, + deltaX: 0, + deltaY: 1, + }); + + expect(lineContainer.scrollLeft).toBe(232); + expect(pageContainer.scrollLeft).toBe(700); + }); + + it("clamps movement at both ends while retaining ownership of board scrolling", () => { + const rightEdge = makeContainer({ scrollLeft: 990 }); + const leftEdge = makeContainer({ scrollLeft: 10 }); + + expect( + scrollBoardFromWheel(rightEdge, { + ctrlKey: false, + deltaMode: 0, + deltaX: 0, + deltaY: 100, + }), + ).toBe(true); + expect(rightEdge.scrollLeft).toBe(1_000); + + expect( + scrollBoardFromWheel(leftEdge, { + ctrlKey: false, + deltaMode: 0, + deltaX: 0, + deltaY: -100, + }), + ).toBe(true); + expect(leftEdge.scrollLeft).toBe(0); + }); + + it("leaves pinch zoom and non-overflowing boards untouched", () => { + const zoomContainer = makeContainer(); + const fittingContainer = makeContainer({ clientWidth: 1_500 }); + const wheel = { ctrlKey: false, deltaMode: 0, deltaX: 0, deltaY: 100 }; + + expect(scrollBoardFromWheel(zoomContainer, { ...wheel, ctrlKey: true })).toBe(false); + expect(zoomContainer.scrollLeft).toBe(200); + expect(scrollBoardFromWheel(fittingContainer, wheel)).toBe(false); + expect(fittingContainer.scrollLeft).toBe(200); + }); +}); diff --git a/apps/web/src/components/board/BoardScroll.ts b/apps/web/src/components/board/BoardScroll.ts new file mode 100644 index 00000000000..ed607d99793 --- /dev/null +++ b/apps/web/src/components/board/BoardScroll.ts @@ -0,0 +1,84 @@ +const PIXELS_PER_WHEEL_LINE = 16; + +interface BoardScrollContainer { + readonly clientWidth: number; + scrollLeft: number; + readonly scrollWidth: number; +} + +interface BoardWheelInput { + readonly ctrlKey: boolean; + readonly deltaMode: number; + readonly deltaX: number; + readonly deltaY: number; +} + +interface ColumnScrollContainer { + readonly clientHeight: number; + readonly scrollHeight: number; + readonly scrollTop: number; +} + +interface WheelAxes { + readonly deltaX: number; + readonly deltaY: number; +} + +/** Returns true when a vertical gesture can still move an overflowing column. */ +export function shouldScrollColumnFromWheel( + container: ColumnScrollContainer, + event: WheelAxes, +): boolean { + if ( + !Number.isFinite(event.deltaY) || + event.deltaY === 0 || + Math.abs(event.deltaX) >= Math.abs(event.deltaY) + ) { + return false; + } + + const maxScrollTop = Math.max(0, container.scrollHeight - container.clientHeight); + if (maxScrollTop === 0) { + return false; + } + + return event.deltaY < 0 ? container.scrollTop > 0 : container.scrollTop < maxScrollTop; +} + +/** + * Redirects the wheel's dominant axis into the board's native horizontal + * scroll position. Handling horizontal input here as well keeps nested column + * scroll areas from swallowing trackpad gestures before they reach the board. + */ +export function scrollBoardFromWheel( + container: BoardScrollContainer, + event: BoardWheelInput, +): boolean { + if (event.ctrlKey) { + // Ctrl+wheel is commonly a trackpad pinch gesture. Leave browser zoom alone. + return false; + } + + const maxScrollLeft = Math.max(0, container.scrollWidth - container.clientWidth); + if (maxScrollLeft === 0) { + return false; + } + + const dominantDelta = + Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY; + if (!Number.isFinite(dominantDelta) || dominantDelta === 0) { + return false; + } + + const multiplier = + event.deltaMode === 1 + ? PIXELS_PER_WHEEL_LINE + : event.deltaMode === 2 + ? container.clientWidth + : 1; + container.scrollLeft = Math.min( + maxScrollLeft, + Math.max(0, container.scrollLeft + dominantDelta * multiplier), + ); + return true; +} diff --git a/apps/web/src/components/board/BoardView.tsx b/apps/web/src/components/board/BoardView.tsx new file mode 100644 index 00000000000..a06a82c4d56 --- /dev/null +++ b/apps/web/src/components/board/BoardView.tsx @@ -0,0 +1,998 @@ +import { + DndContext, + DragOverlay, + MouseSensor, + pointerWithin, + TouchSensor, + useSensor, + useSensors, + type DragEndEvent, + type DragOverEvent, + type DragStartEvent, +} from "@dnd-kit/core"; +import { + scopedProjectKey, + scopedThreadKey, + scopeProjectRef, + scopeThreadRef, +} from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + settlePromise, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; +import type { ScopedThreadRef, VcsStatusResult } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import * as Schema from "effect/Schema"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; + +import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal"; +import { isElectron } from "../../env"; +import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; +import { useLocalStorage } from "../../hooks/useLocalStorage"; +import { useNowMinute } from "../../hooks/useNowMinute"; +import { useClientSettings } from "../../hooks/useSettings"; +import { useThreadActions } from "../../hooks/useThreadActions"; +import { cn } from "../../lib/utils"; +import { readLocalApi } from "../../localApi"; +import { selectProjectGroupingSettings } from "../../logicalProject"; +import { + buildSidebarProjectSnapshots, + type SidebarProjectSnapshot, +} from "../../sidebarProjectGrouping"; +import { + useAllEnvironmentShellsBootstrapped, + useProjects, + useServerConfigs, + useThreadShells, +} from "../../state/entities"; +import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import type { Project, SidebarThreadSummary } from "../../types"; +import { useUiStateStore } from "../../uiStateStore"; +import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "../../workspaceTitlebar"; +import { ProjectFavicon, ProjectFaviconFallback } from "../ProjectFavicon"; +import { + SETTLED_TAIL_INITIAL_COUNT, + SETTLED_TAIL_PAGE_COUNT, + archiveSelectedThreadEntries, + buildSidebarV2ThreadContextMenuItems, + isThreadSettledForDisplay, + resolveThreadStatusPill, +} from "../Sidebar.logic"; +import { resolveSnoozePresets, snoozeWakeDescription } from "../Sidebar.snooze"; +import { resolveThreadPr } from "../ThreadStatusIndicators"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SidebarInset } from "../ui/sidebar"; +import { Spinner } from "../ui/spinner"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { + BOARD_COLUMN_IDS, + boardGitKey, + boardWorktreeKey, + buildBoardColumns, + buildBoardProjectFilterPredicate, + countBoardColumnThreads, + deriveBoardColumn, + parseBoardWorktreeGroupDragId, + resolveBoardDropIntent, + sliceBoardSettledItems, + type BoardDropIntent, +} from "./Board.logic"; +import { BoardCard, BoardCardDragOverlay } from "./BoardCard"; +import { BoardColumn } from "./BoardColumn"; +import { createBoardDragClickGuard } from "./BoardDragClickGuard"; +import { BoardDropZones } from "./BoardDropZones"; +import { scrollBoardFromWheel, shouldScrollColumnFromWheel } from "./BoardScroll"; +import { BoardWorktreeGroup, BoardWorktreeGroupDragOverlay } from "./BoardWorktreeGroup"; +import { useBoardVcsStatuses, type BoardVcsTarget } from "./useBoardVcsStatuses"; + +const BOARD_PROJECT_FILTER_STORAGE_KEY = "t3code:board:project-filter:v1"; +const BOARD_PROJECT_FILTER_ALL = "all"; +const BoardProjectFilterSchema = Schema.NullOr(Schema.String); + +interface BoardThreadGitContext { + readonly project: Project | null; + readonly gitStatus: VcsStatusResult | null; + readonly gitStatusPending: boolean; +} + +/** Error toast for a failed thread action; interruptions and successes are silent. */ +function reportThreadActionFailure(result: AtomCommandResult, title: string) { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) { + return; + } + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); +} + +export function BoardView() { + const bootstrapped = useAllEnvironmentShellsBootstrapped(); + + return ( + +
+ {bootstrapped ? ( + + ) : ( +
+ +
+ )} +
+
+ ); +} + +function BoardContent() { + const projects = useProjects(); + const threadShells = useThreadShells(); + const { environments } = useEnvironments(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); + const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays); + const serverConfigs = useServerConfigs(); + const { + archiveThread, + confirmAndDeleteThread, + confirmAndDeleteThreads, + renameThread, + settleThread, + snoozeThread, + unsettleThread, + unsnoozeThread, + } = useThreadActions(); + const handleNewThread = useNewThreadHandler(); + const navigate = useNavigate(); + const boardScrollRef = useRef(null); + const markThreadUnread = useUiStateStore((state) => state.markThreadUnread); + const [threadRenameTarget, setThreadRenameTarget] = useState(null); + const [threadRenameTitle, setThreadRenameTitle] = useState(""); + + useEffect(() => { + const scrollContainer = boardScrollRef.current; + if (scrollContainer === null) { + return; + } + + const handleWheel = (event: WheelEvent) => { + const columnScrollViewport = + event.target instanceof Element + ? event.target.closest( + '[data-testid^="board-column-"] [data-slot="scroll-area-viewport"]', + ) + : null; + if ( + columnScrollViewport instanceof HTMLElement && + shouldScrollColumnFromWheel(columnScrollViewport, event) + ) { + return; + } + + if (scrollBoardFromWheel(scrollContainer, event)) { + event.preventDefault(); + } + }; + + // React's delegated wheel events can be passive. This listener must be + // non-passive so gestures released by nested columns can move the board. + scrollContainer.addEventListener("wheel", handleWheel, { passive: false }); + return () => scrollContainer.removeEventListener("wheel", handleWheel); + }, []); + + const [storedProjectFilter, setStoredProjectFilter] = useLocalStorage( + BOARD_PROJECT_FILTER_STORAGE_KEY, + null, + BoardProjectFilterSchema, + ); + + const environmentLabelById = useMemo( + () => + new Map( + environments.map((environment) => [environment.environmentId, environment.label] as const), + ), + [environments], + ); + const desktopLocalEnvironmentIds = useMemo( + () => + new Set( + environments + .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target)) + .map((environment) => environment.environmentId), + ), + [environments], + ); + const projectSnapshots = useMemo( + () => + buildSidebarProjectSnapshots({ + projects, + settings: projectGroupingSettings, + primaryEnvironmentId, + resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, + isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId), + }), + [ + desktopLocalEnvironmentIds, + environmentLabelById, + primaryEnvironmentId, + projectGroupingSettings, + projects, + ], + ); + + const projectByKey = useMemo( + () => + new Map( + projects.map( + (project) => + [ + scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), + project, + ] as const, + ), + ), + [projects], + ); + + const threads = useMemo( + () => threadShells.filter((thread) => thread.archivedAt === null), + [threadShells], + ); + const filterPredicate = useMemo( + () => + buildBoardProjectFilterPredicate({ + selectedProjectKey: storedProjectFilter, + snapshots: projectSnapshots, + }), + [projectSnapshots, storedProjectFilter], + ); + const filteredThreads = useMemo( + () => threads.filter(filterPredicate), + [filterPredicate, threads], + ); + + const resolveThreadGitCwd = useCallback( + (thread: SidebarThreadSummary): string | null => { + if (thread.branch == null) { + return null; + } + const project = projectByKey.get( + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), + ); + return thread.worktreePath ?? project?.workspaceRoot ?? null; + }, + [projectByKey], + ); + + const vcsTargets = useMemo( + () => + filteredThreads.flatMap((thread) => { + const cwd = resolveThreadGitCwd(thread); + return cwd === null ? [] : [{ environmentId: thread.environmentId, cwd }]; + }), + [filteredThreads, resolveThreadGitCwd], + ); + const gitStatuses = useBoardVcsStatuses(vcsTargets); + + const getThreadGitContext = useCallback( + (thread: SidebarThreadSummary): BoardThreadGitContext => { + const project = + projectByKey.get( + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), + ) ?? null; + const cwd = resolveThreadGitCwd(thread); + const gitStatus = + cwd === null ? null : (gitStatuses.get(boardGitKey(thread.environmentId, cwd)) ?? null); + return { + project, + gitStatus, + gitStatusPending: cwd !== null && gitStatus === null, + }; + }, + [gitStatuses, projectByKey, resolveThreadGitCwd], + ); + + const nowMinute = useNowMinute(); + + const previousSettledThreadKeys = useRef>(new Set()); + const settledThreadKeys = useMemo(() => { + const now = `${nowMinute}:00.000Z`; + const keys = new Set(); + for (const thread of filteredThreads) { + const changeRequestState = + resolveThreadPr({ + threadBranch: thread.branch, + hasDedicatedWorktree: thread.worktreePath != null, + gitStatus: getThreadGitContext(thread).gitStatus, + })?.state ?? null; + if ( + isThreadSettledForDisplay(thread, { + serverConfigs, + now, + autoSettleAfterDays, + changeRequestState, + }) + ) { + keys.add(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))); + } + } + // Column building and the drag handlers key on this set; keep the previous + // identity when the contents did not change so the minute tick and + // git-status churn don't cascade a full board re-render. + const previous = previousSettledThreadKeys.current; + if (previous.size === keys.size && [...keys].every((key) => previous.has(key))) { + return previous; + } + previousSettledThreadKeys.current = keys; + return keys; + }, [autoSettleAfterDays, filteredThreads, getThreadGitContext, nowMinute, serverConfigs]); + // The context-menu handler reads these through refs: depending on the live + // identities would hand every BoardCard a fresh callback prop on each + // git-status or shell event and defeat the cards' memoization. + const settledThreadKeysRef = useRef(settledThreadKeys); + settledThreadKeysRef.current = settledThreadKeys; + const serverConfigsRef = useRef(serverConfigs); + serverConfigsRef.current = serverConfigs; + + const threadLastVisitedAtById = useUiStateStore((state) => state.threadLastVisitedAtById); + const threadStatusLabelByKey = useMemo( + () => + new Map( + threads.map((thread) => { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + const threadStatusLabel = resolveThreadStatusPill({ + thread: { + ...thread, + lastVisitedAt: threadLastVisitedAtById[threadKey], + }, + })?.label; + return [threadKey, threadStatusLabel ?? null] as const; + }), + ), + [threadLastVisitedAtById, threads], + ); + const workingWorktreeKeys = useMemo(() => { + const keys = new Set(); + for (const thread of threads) { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + const statusLabel = threadStatusLabelByKey.get(threadKey); + if (statusLabel !== "Working" && statusLabel !== "Connecting") { + continue; + } + const cwd = resolveThreadGitCwd(thread); + if (cwd !== null) { + keys.add(boardGitKey(thread.environmentId, cwd)); + } + } + return keys; + }, [resolveThreadGitCwd, threadStatusLabelByKey, threads]); + const columns = useMemo( + () => + buildBoardColumns( + filteredThreads, + (thread) => { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + const lastVisitedAt = threadLastVisitedAtById[threadKey]; + const cwd = resolveThreadGitCwd(thread); + + return deriveBoardColumn({ + threadStatusLabel: threadStatusLabelByKey.get(threadKey) ?? null, + interactionMode: thread.interactionMode, + isSettled: settledThreadKeys.has(threadKey), + latestTurnCompletedAt: thread.latestTurn?.completedAt ?? null, + readySessionUpdatedAt: + thread.latestTurn === null && thread.session?.status === "ready" + ? thread.session.updatedAt + : null, + lastVisitedAt: lastVisitedAt ?? null, + threadBranch: thread.branch, + hasDedicatedWorktree: thread.worktreePath != null, + hasWorkingThreadForWorktree: + cwd !== null && workingWorktreeKeys.has(boardGitKey(thread.environmentId, cwd)), + gitStatus: getThreadGitContext(thread).gitStatus, + }); + }, + (thread) => + thread.session?.status === "running" && + thread.latestTurn?.turnId === thread.session.activeTurnId + ? (thread.latestTurn.startedAt ?? thread.latestTurn.requestedAt) + : null, + boardWorktreeKey, + ), + [ + filteredThreads, + getThreadGitContext, + resolveThreadGitCwd, + settledThreadKeys, + threadLastVisitedAtById, + threadStatusLabelByKey, + workingWorktreeKeys, + ], + ); + + // Settled tail renders in pages, mirroring SidebarV2: expansion resets when + // the project filter changes so a scope flip never inherits a deep page. + const [settledVisibleCount, setSettledVisibleCount] = useState(SETTLED_TAIL_INITIAL_COUNT); + const settledResetKey = storedProjectFilter ?? "all"; + const lastSettledResetKeyRef = useRef(settledResetKey); + if (lastSettledResetKeyRef.current !== settledResetKey) { + lastSettledResetKeyRef.current = settledResetKey; + setSettledVisibleCount(SETTLED_TAIL_INITIAL_COUNT); + } + const settledTail = useMemo( + () => sliceBoardSettledItems(columns.settled, settledVisibleCount), + [columns, settledVisibleCount], + ); + const showMoreSettled = useCallback( + () => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT), + [], + ); + + const dragClickGuard = useMemo(() => createBoardDragClickGuard(), []); + useEffect(() => () => dragClickGuard.dispose(), [dragClickGuard]); + const [activeDragId, setActiveDragId] = useState(null); + const [dropIntent, setDropIntent] = useState(null); + const activeThread = useMemo( + () => + activeDragId === null || parseBoardWorktreeGroupDragId(activeDragId) !== null + ? null + : (filteredThreads.find( + (thread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeDragId, + ) ?? null), + [activeDragId, filteredThreads], + ); + const activeWorktreeGroup = useMemo(() => { + const worktreeKey = parseBoardWorktreeGroupDragId(activeDragId); + if (worktreeKey === null) { + return null; + } + for (const columnId of BOARD_COLUMN_IDS) { + for (const item of columns[columnId]) { + if (item.kind === "worktreeGroup" && item.worktreeKey === worktreeKey) { + return item; + } + } + } + return null; + }, [activeDragId, columns]); + const activeDragIncludesSettledThread = useMemo(() => { + if (activeDragId === null) { + return false; + } + if (activeWorktreeGroup !== null) { + return activeWorktreeGroup.threads.some((thread) => + settledThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))), + ); + } + return settledThreadKeys.has(activeDragId); + }, [activeDragId, activeWorktreeGroup, settledThreadKeys]); + + // Touch drags require a long-press so swipe gestures keep scrolling the + // board; a distance-only constraint would claim every swipe as a drag. + const dndSensors = useSensors( + useSensor(MouseSensor, { activationConstraint: { distance: 6 } }), + useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 8 } }), + ); + + const handleDragStart = useCallback( + (event: DragStartEvent) => { + dragClickGuard.startDrag(); + setActiveDragId(String(event.active.id)); + }, + [dragClickGuard], + ); + + const handleDragOver = useCallback((event: DragOverEvent) => { + setDropIntent(resolveBoardDropIntent(event.over?.id)); + }, []); + + const handleDragCancel = useCallback(() => { + dragClickGuard.finishDrag(); + setActiveDragId(null); + setDropIntent(null); + }, [dragClickGuard]); + + const handleDragEnd = useCallback( + (event: DragEndEvent) => { + dragClickGuard.finishDrag(); + setActiveDragId(null); + setDropIntent(null); + const dragData = event.active.data.current as + | { + threadRef?: ScopedThreadRef; + worktreeGroupThreadRefs?: readonly ScopedThreadRef[]; + } + | undefined; + const threadRefs = + dragData?.worktreeGroupThreadRefs ?? (dragData?.threadRef ? [dragData.threadRef] : []); + if (threadRefs.length === 0) { + return; + } + const intent = resolveBoardDropIntent(event.over?.id); + if (intent === null) { + return; + } + + if (intent === "settle" || intent === "unsettle") { + // Dropping onto a state a card is already in is a no-op: the restore + // zone only shows for settled drags, and a group can hold a mix. + const wantSettled = intent === "settle"; + const refs = threadRefs.filter( + (threadRef) => settledThreadKeys.has(scopedThreadKey(threadRef)) !== wantSettled, + ); + if (refs.length === 0) { + return; + } + const action = wantSettled ? settleThread : unsettleThread; + const failureTitle = `Failed to ${wantSettled ? "settle" : "restore"} ${ + refs.length === 1 ? "thread" : "threads" + }`; + // Success is silent: the card moves when the shell update streams in. + void Promise.all(refs.map((threadRef) => action(threadRef))).then((results) => { + const failure = results.find( + (result) => result._tag === "Failure" && !isAtomCommandInterrupted(result), + ); + if (failure) { + reportThreadActionFailure(failure, failureTitle); + } + }); + return; + } + + if (intent === "trash") { + void confirmAndDeleteThreads(threadRefs).then((result) => { + reportThreadActionFailure( + result, + threadRefs.length === 1 ? "Failed to delete thread" : "Failed to delete threads", + ); + }); + return; + } + + void archiveSelectedThreadEntries({ + entries: threadRefs.map((threadRef) => ({ + threadKey: scopedThreadKey(threadRef), + threadRef, + })), + archive: ({ threadRef }, onArchived) => archiveThread(threadRef, { onArchived }), + }).then((outcome) => { + for (const failure of outcome.followupFailures) { + reportThreadActionFailure(failure, "Thread archived, but navigation failed"); + } + if (outcome.mutationFailure) { + reportThreadActionFailure( + outcome.mutationFailure, + threadRefs.length === 1 ? "Failed to archive thread" : "Failed to archive threads", + ); + } + }); + }, + [ + archiveThread, + confirmAndDeleteThreads, + dragClickGuard, + settledThreadKeys, + settleThread, + unsettleThread, + ], + ); + + const handleOpenThread = useCallback( + (threadRef: ScopedThreadRef) => { + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(threadRef), + }); + }, + [navigate], + ); + + const closeThreadRenameDialog = useCallback(() => { + setThreadRenameTarget(null); + setThreadRenameTitle(""); + }, []); + + const submitThreadRename = useCallback(async () => { + if (threadRenameTarget === null) { + return; + } + const committed = await renameThread( + scopeThreadRef(threadRenameTarget.environmentId, threadRenameTarget.id), + threadRenameTitle, + threadRenameTarget.title, + ); + if (committed) { + closeThreadRenameDialog(); + } + }, [closeThreadRenameDialog, renameThread, threadRenameTarget, threadRenameTitle]); + + const handleThreadContextMenu = useCallback( + async (thread: SidebarThreadSummary, position: { x: number; y: number }) => { + const api = readLocalApi(); + if (!api) { + return; + } + + const threadRef = scopeThreadRef(thread.environmentId, thread.id); + const threadKey = scopedThreadKey(threadRef); + const supportsSettlement = + serverConfigsRef.current.get(thread.environmentId)?.environment.capabilities + .threadSettlement === true; + const supportsSnooze = + serverConfigsRef.current.get(thread.environmentId)?.environment.capabilities + .threadSnooze === true; + const isSettled = settledThreadKeysRef.current.has(threadKey); + // Snooze classification uses a real clock (wake times are + // second-precise) and presets resolve at menu-open time — both same + // as the sidebar. + const preciseNow = new Date().toISOString(); + const isSnoozed = supportsSnooze && effectiveSnoozed(thread, { now: preciseNow }); + const snoozePresets = resolveSnoozePresets(new Date()); + const clicked = await api.contextMenu.show( + buildSidebarV2ThreadContextMenuItems({ + branch: thread.branch, + supportsSettlement, + isSettled, + supportsSnooze, + isSnoozed, + canSnoozeNow: canSnooze(thread, { now: preciseNow }), + snoozePresets, + }), + position, + ); + + if (clicked?.startsWith("snooze:")) { + const preset = snoozePresets.find((candidate) => `snooze:${candidate.id}` === clicked); + if (!preset) { + return; + } + const result = await snoozeThread(threadRef, preset.snoozedUntil); + if (result._tag === "Failure") { + reportThreadActionFailure(result, "Failed to snooze thread"); + return; + } + // A snoozed card has no visible change on the board, so the toast is + // the only confirmation — and Undo the escape hatch for a mis-click. + toastManager.add( + stackedThreadToast({ + type: "success", + title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date())}`, + timeout: 5_000, + actionProps: { + children: "Undo", + onClick: () => { + void unsnoozeThread(threadRef).then((undoResult) => { + reportThreadActionFailure(undoResult, "Failed to wake thread"); + }); + }, + }, + }), + ); + return; + } + if (clicked === "unsnooze") { + reportThreadActionFailure(await unsnoozeThread(threadRef), "Failed to wake thread"); + return; + } + if (clicked === "new-thread-on-branch") { + // Explicit branch carry-over: reuse the thread's worktree when it + // has one, otherwise its branch on the local checkout. + await handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), { + branch: thread.branch, + worktreePath: thread.worktreePath, + envMode: thread.worktreePath ? "worktree" : "local", + startFromOrigin: false, + }); + return; + } + if (clicked === "settle" || clicked === "unsettle") { + const result = + clicked === "settle" ? await settleThread(threadRef) : await unsettleThread(threadRef); + reportThreadActionFailure( + result, + clicked === "settle" ? "Failed to settle thread" : "Failed to un-settle thread", + ); + return; + } + + if (clicked === "rename") { + setThreadRenameTarget(thread); + setThreadRenameTitle(thread.title); + return; + } + if (clicked === "mark-unread") { + markThreadUnread(threadKey, thread.latestTurn?.completedAt); + return; + } + if (clicked !== "delete") { + return; + } + + reportThreadActionFailure(await confirmAndDeleteThread(threadRef), "Failed to delete thread"); + }, + [ + confirmAndDeleteThread, + handleNewThread, + markThreadUnread, + settleThread, + snoozeThread, + unsettleThread, + unsnoozeThread, + ], + ); + + const showThreadContextMenu = useCallback( + (thread: SidebarThreadSummary, position: { x: number; y: number }) => { + void settlePromise(() => handleThreadContextMenu(thread, position)).then((result) => { + if (result._tag === "Success") { + return; + } + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Thread action failed", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + }); + }, + [handleThreadContextMenu], + ); + + const projectFilterItems = useMemo( + () => [ + { value: BOARD_PROJECT_FILTER_ALL, label: "All projects" }, + ...projectSnapshots.map((snapshot) => ({ + value: snapshot.projectKey, + label: snapshot.displayName, + })), + ], + [projectSnapshots], + ); + const selectedFilterValue = + storedProjectFilter !== null && + projectSnapshots.some((snapshot) => snapshot.projectKey === storedProjectFilter) + ? storedProjectFilter + : BOARD_PROJECT_FILTER_ALL; + const selectedFilterSnapshot = + selectedFilterValue === BOARD_PROJECT_FILTER_ALL + ? null + : (projectSnapshots.find((snapshot) => snapshot.projectKey === selectedFilterValue) ?? null); + + return ( + <> + {/* .workspace-topbar pins the header to --workspace-topbar-height so the + floating sidebar toggle (absolutely positioned in that same band) + stays vertically aligned with the title at every breakpoint. */} +
+ Board +
+ +
+
+ +
+
+
+ {BOARD_COLUMN_IDS.map((columnId) => { + const items = columnId === "settled" ? settledTail.visibleItems : columns[columnId]; + return ( + + {items.map((item) => { + const renderCard = (thread: SidebarThreadSummary) => { + const gitContext = getThreadGitContext(thread); + const threadKey = scopedThreadKey( + scopeThreadRef(thread.environmentId, thread.id), + ); + return ( + + ); + }; + if (item.kind === "thread") { + return renderCard(item.thread); + } + // buildBoardColumns only emits groups with >= 2 members. + const mostRecentThread = item.threads[0]!; + return ( + + scopeThreadRef(thread.environmentId, thread.id), + )} + worktreePath={mostRecentThread.worktreePath ?? ""} + branch={mostRecentThread.branch} + mostRecentCard={renderCard(mostRecentThread)} + dragClickGuard={dragClickGuard} + > + {item.threads.slice(1).map(renderCard)} + + ); + })} + {columnId === "settled" && settledTail.hiddenThreadCount > 0 ? ( + + ) : null} + + ); + })} +
+
+ {activeDragId !== null ? ( + + ) : null} +
+ + {activeWorktreeGroup !== null ? ( + + ) : activeThread !== null ? ( + + ) : null} + +
+ { + if (!open) { + closeThreadRenameDialog(); + } + }} + > + + + Rename thread + Update the title shown for this thread. + + +
+ Thread title + setThreadRenameTitle(event.target.value)} + onKeyDown={(event) => { + if (event.key === "Enter") { + event.preventDefault(); + void submitThreadRename(); + } + }} + /> +
+
+ + + + +
+
+ + ); +} diff --git a/apps/web/src/components/board/BoardWorktreeGroup.test.tsx b/apps/web/src/components/board/BoardWorktreeGroup.test.tsx new file mode 100644 index 00000000000..a1f5f1b67cf --- /dev/null +++ b/apps/web/src/components/board/BoardWorktreeGroup.test.tsx @@ -0,0 +1,100 @@ +import { DndContext } from "@dnd-kit/core"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vite-plus/test"; + +import type { BoardDragClickGuard } from "./BoardDragClickGuard"; +import { BoardWorktreeGroup, BoardWorktreeGroupDragOverlay } from "./BoardWorktreeGroup"; + +const environmentId = EnvironmentId.make("environment-local"); + +const noopDragClickGuard: BoardDragClickGuard = { + startDrag: () => {}, + finishDrag: () => {}, + consumeSuppressedClick: () => false, + dispose: () => {}, +}; + +function renderGroup({ + branch = "t3code/session-dashboard-board", + mostRecentCard =
, + children =
, +}: { + branch?: string | null; + mostRecentCard?: ReactNode; + children?: ReactNode; +} = {}): string { + return renderToStaticMarkup( + + + {children} + + , + ); +} + +describe("BoardWorktreeGroup", () => { + it("starts collapsed showing only the most recent card below the toggle", () => { + const markup = renderGroup(); + + expect(markup).toContain('aria-expanded="false"'); + expect(markup).toContain(' +
+ {mostRecentCard} + {expanded ? children : null} +
+ + ); +} + +/** Non-interactive header clone rendered inside the DragOverlay while dragging a group. */ +export function BoardWorktreeGroupDragOverlay({ + worktreePath, + branch, + threadCount, + dropIntent = null, +}: { + worktreePath: string; + branch: string | null; + threadCount: number; + dropIntent?: BoardDropIntent | null; +}) { + const displayLabel = resolveWorktreeGroupLabel(worktreePath, branch); + + return ( + + ); +} diff --git a/apps/web/src/components/board/useBoardVcsStatuses.ts b/apps/web/src/components/board/useBoardVcsStatuses.ts new file mode 100644 index 00000000000..b774880b651 --- /dev/null +++ b/apps/web/src/components/board/useBoardVcsStatuses.ts @@ -0,0 +1,78 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId, VcsStatusResult } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; +import { useMemo, useRef } from "react"; + +import { vcsEnvironment } from "../../state/vcs"; +import { boardGitKey } from "./Board.logic"; + +export interface BoardVcsTarget { + readonly environmentId: EnvironmentId; + readonly cwd: string; +} + +const EMPTY_STATUSES_ATOM = Atom.make( + (): ReadonlyMap => new Map(), +).pipe(Atom.withLabel("web:board-vcs-statuses:empty")); + +/** + * Aggregated VCS status subscription for the board: one derived atom over the + * per-cwd status subscription family, read with a single useAtomValue. The + * family dedupes identical (environmentId, cwd) keys into one WS subscription + * and keeps entries warm for 5 minutes after last use, so filter toggles + * don't churn subscriptions. Entries are `null` until the first snapshot + * streams in. + */ +export function useBoardVcsStatuses( + targets: ReadonlyArray, +): ReadonlyMap { + // Thread-shell churn hands this hook a fresh input array on every update; + // dedupe into a sorted, identity-stable list so the derived atom below is + // only rebuilt when the (environmentId, cwd) set actually changes. + const previousTargetsRef = useRef>([]); + const dedupedTargets = useMemo(() => { + const byKey = new Map(); + for (const target of targets) { + byKey.set(boardGitKey(target.environmentId, target.cwd), target); + } + const next = [...byKey.entries()].sort(([left], [right]) => + left < right ? -1 : left > right ? 1 : 0, + ); + const previous = previousTargetsRef.current; + if ( + previous.length === next.length && + previous.every(([key], index) => key === next[index]![0]) + ) { + return previous; + } + previousTargetsRef.current = next; + return next; + }, [targets]); + + const statusesAtom = useMemo(() => { + if (dedupedTargets.length === 0) { + return EMPTY_STATUSES_ATOM; + } + return Atom.make( + (get): ReadonlyMap => + new Map( + dedupedTargets.map(([key, target]) => [ + key, + Option.getOrNull( + AsyncResult.value( + get( + vcsEnvironment.status({ + environmentId: target.environmentId, + input: { cwd: target.cwd }, + }), + ), + ), + ), + ]), + ), + ).pipe(Atom.withLabel(`web:board-vcs-statuses:${dedupedTargets.length}`)); + }, [dedupedTargets]); + + return useAtomValue(statusesAtom); +} diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsx index d6f178a1f54..e36ddee1fff 100644 --- a/apps/web/src/components/ui/scroll-area.tsx +++ b/apps/web/src/components/ui/scroll-area.tsx @@ -11,12 +11,14 @@ function ScrollArea({ scrollbarGutter = false, hideScrollbars = false, chainVerticalScroll = false, + chainHorizontalScroll = false, ...props }: ScrollAreaPrimitive.Root.Props & { scrollFade?: boolean; scrollbarGutter?: boolean; hideScrollbars?: boolean; chainVerticalScroll?: boolean; + chainHorizontalScroll?: boolean; }) { return ( { it("keeps the blocked thread context with the fixed message", () => { const error = new ThreadArchiveBlockedError({ - environmentId: EnvironmentId.make("environment-1"), + environmentId, threadId: ThreadId.make("thread-1"), }); @@ -17,3 +20,45 @@ describe("ThreadArchiveBlockedError", () => { expect(error.message).toBe("Cannot archive a running thread."); }); }); + +describe("deleteThreadTargetsSequentially", () => { + const targets = [ + { environmentId, threadId: ThreadId.make("thread-1") }, + { environmentId, threadId: ThreadId.make("thread-2") }, + { environmentId, threadId: ThreadId.make("thread-3") }, + ] as const; + + it("makes shared-worktree cleanup eligible only for the final target", async () => { + const cleanupEligibleTargets: string[] = []; + + const result = await deleteThreadTargetsSequentially(targets, async (target, opts) => { + if (opts.deletedThreadKeys.size === targets.length - 1) { + cleanupEligibleTargets.push(scopedThreadKey(target)); + } + return { _tag: "Success" } as const; + }); + + expect(result).toBeNull(); + expect(cleanupEligibleTargets).toEqual([scopedThreadKey(targets[2])]); + }); + + it("does not discount a target whose deletion failed", async () => { + const deletedKeySnapshots: string[][] = []; + const failure = { _tag: "Failure", reason: "delete failed" } as const; + const deleteTarget = vi.fn( + async ( + target: (typeof targets)[number], + opts: { deletedThreadKeys: ReadonlySet }, + ) => { + deletedKeySnapshots.push([...opts.deletedThreadKeys]); + return target === targets[1] ? failure : ({ _tag: "Success" } as const); + }, + ); + + const result = await deleteThreadTargetsSequentially(targets, deleteTarget); + + expect(result).toBe(failure); + expect(deleteTarget).toHaveBeenCalledTimes(2); + expect(deletedKeySnapshots).toEqual([[], [scopedThreadKey(targets[0])]]); + }); +}); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 91a3779a057..6b7afedbb96 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -1,9 +1,14 @@ import { parseScopedThreadKey, + scopedThreadKey, scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; -import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + isAtomCommandInterrupted, + settlePromise, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { canSettle, canSnooze } from "@t3tools/client-runtime/state/thread-settled"; import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -94,6 +99,33 @@ export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass( + targets: readonly ScopedThreadRef[], + deleteTarget: ( + target: ScopedThreadRef, + opts: { deletedThreadKeys: ReadonlySet }, + ) => Promise, +): Promise | null> { + const deletedThreadKeys = new Set(); + for (const target of targets) { + const result = await deleteTarget(target, { deletedThreadKeys }); + if (result._tag === "Failure") { + return result as Extract; + } + deletedThreadKeys.add(scopedThreadKey(target)); + } + return null; +} + export function useThreadActions() { const closeTerminal = useAtomCommand(terminalEnvironment.close); const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, { @@ -117,6 +149,9 @@ export function useThreadActions() { const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false, }); + const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { + reportFailure: false, + }); const stopThreadSession = useAtomCommand(threadEnvironment.stopSession); const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, { reportFailure: false, @@ -527,6 +562,41 @@ export function useThreadActions() { [unsnoozeThreadMutation], ); + // Shared rename commit: trims, warns on an empty title, and reports + // failures. Returns true when the title is committed (or was unchanged) so + // dialog-style callers know they can close. + const renameThread = useCallback( + async (target: ScopedThreadRef, title: string, originalTitle: string): Promise => { + const trimmed = title.trim(); + if (trimmed.length === 0) { + toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); + return false; + } + if (trimmed === originalTitle) { + return true; + } + const result = await updateThreadMetadata({ + environmentId: target.environmentId, + input: { threadId: target.threadId, title: trimmed }, + }); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to rename thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return false; + } + return true; + }, + [updateThreadMetadata], + ); + const confirmAndDeleteThread = useCallback( async (target: ScopedThreadRef) => { const localApi = readLocalApi(); @@ -555,12 +625,51 @@ export function useThreadActions() { [confirmThreadDelete, deleteThread, resolveThreadTarget], ); + const confirmAndDeleteThreads = useCallback( + async (targets: readonly ScopedThreadRef[]) => { + const [firstTarget] = targets; + if (firstTarget === undefined) { + return AsyncResult.success(undefined); + } + if (targets.length === 1) { + return confirmAndDeleteThread(firstTarget); + } + + const localApi = readLocalApi(); + if (confirmThreadDelete && localApi) { + const confirmationResult = await settlePromise(() => + localApi.dialogs.confirm( + [ + `Delete ${targets.length} threads?`, + "This permanently clears conversation history for these threads.", + ].join("\n"), + ), + ); + if (confirmationResult._tag === "Failure") { + return confirmationResult; + } + if (!confirmationResult.value) { + return AsyncResult.success(undefined); + } + } + + const failure = await deleteThreadTargetsSequentially(targets, deleteThread); + if (failure) { + return failure; + } + return AsyncResult.success(undefined); + }, + [confirmAndDeleteThread, confirmThreadDelete, deleteThread], + ); + return useMemo( () => ({ archiveThread, unarchiveThread, deleteThread, confirmAndDeleteThread, + confirmAndDeleteThreads, + renameThread, settleThread, unsettleThread, snoozeThread, @@ -569,7 +678,9 @@ export function useThreadActions() { [ archiveThread, confirmAndDeleteThread, + confirmAndDeleteThreads, deleteThread, + renameThread, settleThread, snoozeThread, unarchiveThread, diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index c0d326edd55..d832cc19711 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -118,6 +118,7 @@ const DEFAULT_BINDINGS = compile([ command: "commandPalette.toggle", whenAst: whenNot(whenIdentifier("terminalFocus")), }, + { shortcut: modShortcut("t"), command: "board.open" }, { shortcut: modShortcut("m", { shiftKey: true }), command: "modelPicker.toggle", @@ -458,6 +459,15 @@ describe("model picker navigation helpers", () => { }); describe("chat/editor shortcuts", () => { + it("resolves the board shortcut", () => { + assert.strictEqual( + resolveShortcutCommand(event({ key: "t", metaKey: true }), DEFAULT_BINDINGS, { + platform: "MacIntel", + }), + "board.open", + ); + }); + it("matches chat.new shortcut", () => { assert.isTrue( isChatNewShortcut(event({ key: "o", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, { diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 563d1b43755..609c3b79641 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -23,6 +23,7 @@ import { Route as SettingsConnectionsRouteImport } from './routes/settings.conne import { Route as SettingsBetaRouteImport } from './routes/settings.beta' import { Route as SettingsArchivedRouteImport } from './routes/settings.archived' import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback' +import { Route as ChatBoardRouteImport } from './routes/_chat.board' import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId' import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId' @@ -95,6 +96,11 @@ const ConnectCallbackRoute = ConnectCallbackRouteImport.update({ path: '/connect/callback', getParentRoute: () => rootRouteImport, } as any) +const ChatBoardRoute = ChatBoardRouteImport.update({ + id: '/board', + path: '/board', + getParentRoute: () => ChatRoute, +} as any) const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({ id: '/draft/$draftId', path: '/draft/$draftId', @@ -112,6 +118,7 @@ export interface FileRoutesByFullPath { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren + '/board': typeof ChatBoardRoute '/connect/callback': typeof ConnectCallbackRoute '/settings/archived': typeof SettingsArchivedRoute '/settings/beta': typeof SettingsBetaRoute @@ -128,6 +135,7 @@ export interface FileRoutesByTo { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren + '/board': typeof ChatBoardRoute '/connect/callback': typeof ConnectCallbackRoute '/settings/archived': typeof SettingsArchivedRoute '/settings/beta': typeof SettingsBetaRoute @@ -147,6 +155,7 @@ export interface FileRoutesById { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren + '/_chat/board': typeof ChatBoardRoute '/connect_/callback': typeof ConnectCallbackRoute '/settings/archived': typeof SettingsArchivedRoute '/settings/beta': typeof SettingsBetaRoute @@ -167,6 +176,7 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' + | '/board' | '/connect/callback' | '/settings/archived' | '/settings/beta' @@ -183,6 +193,7 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' + | '/board' | '/connect/callback' | '/settings/archived' | '/settings/beta' @@ -201,6 +212,7 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' + | '/_chat/board' | '/connect_/callback' | '/settings/archived' | '/settings/beta' @@ -323,6 +335,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ConnectCallbackRouteImport parentRoute: typeof rootRouteImport } + '/_chat/board': { + id: '/_chat/board' + path: '/board' + fullPath: '/board' + preLoaderRoute: typeof ChatBoardRouteImport + parentRoute: typeof ChatRoute + } '/_chat/draft/$draftId': { id: '/_chat/draft/$draftId' path: '/draft/$draftId' @@ -341,12 +360,14 @@ declare module '@tanstack/react-router' { } interface ChatRouteChildren { + ChatBoardRoute: typeof ChatBoardRoute ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute } const ChatRouteChildren: ChatRouteChildren = { + ChatBoardRoute: ChatBoardRoute, ChatIndexRoute: ChatIndexRoute, ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute, ChatDraftDraftIdRoute: ChatDraftDraftIdRoute, diff --git a/apps/web/src/routes/_chat.board.tsx b/apps/web/src/routes/_chat.board.tsx new file mode 100644 index 00000000000..39824af9745 --- /dev/null +++ b/apps/web/src/routes/_chat.board.tsx @@ -0,0 +1,7 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { BoardView } from "../components/board/BoardView"; + +export const Route = createFileRoute("/_chat/board")({ + component: BoardView, +}); diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index c7cff9943cd..09dcf982904 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -63,6 +63,7 @@ const STATIC_KEYBINDING_COMMANDS = [ "preview.zoomOut", "preview.resetZoom", "commandPalette.toggle", + "board.open", "chat.new", "chat.newLocal", "editor.openFavorite", diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index b6bdd7b4783..4b1fea98160 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -35,6 +35,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+-", command: "preview.zoomOut", when: "previewFocus" }, { key: "mod+0", command: "preview.resetZoom", when: "previewFocus" }, { key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" }, + { key: "mod+t", command: "board.open" }, { key: "mod+n", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },