diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index db9a10acaedb1..24c0daccfa26e 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -1,4 +1,7 @@ import { ThreadInspectionContext } from "./chat/ThreadInspectionContext"; +import { ThreadPanelHostContext } from "./chat/ThreadPanelHostContext"; +import { BoardTaskContext } from "./delivery/BoardTaskContext"; +import { parseTask } from "~/lib/delivery"; import { createMemoryHistory } from "@tanstack/react-router"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { @@ -6,6 +9,7 @@ import { NodeId, IssueTrackerKind, ORCHESTRATION_V2_WS_METHODS, + ProjectId, ProviderDriverKind, ProviderInstanceId, RunId, @@ -35,10 +39,12 @@ import { __setClientSettingsForTests } from "~/hooks/useSettings"; import stylesheet from "~/index.css?inline"; import { environmentContextRecord } from "~/lib/composerContextRecords"; import { startWorkspaceFocus } from "~/lib/workspaceFocus"; +import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore"; import { usePromptStashStore } from "~/promptStashStore"; -import { useRightPanelStore } from "~/rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore"; import { getRouter } from "~/router"; import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { environmentShell } from "~/state/shell"; import { environmentThreadDetails } from "~/state/threads"; import { ENVIRONMENT_ID, @@ -930,6 +936,205 @@ it("opens a timeline parent through the containing workspace", async () => { expect(router.state.location.pathname).toBe(path); }); +/** The board task a task's view provides to what it hosts. */ +const boardTask = () => ({ + environmentId: null, + taskId: "t7", + task: parseTask({ + id: "t7", + number: 7, + title: "Fix the sync", + body: "Make the sync stop dropping rows.", + state: "ready", + lane: "ready", + card: { id: "t7", number: 7, title: "Fix the sync", lane: "ready" }, + }), + stale: false, + refresh: () => {}, + openTask: () => {}, + openThread: () => {}, + seats: { thread: () => null, current: null, open: () => {} }, +}); + +it("a thread a board task's view shows in its own thread's place keeps the task's panels", async () => { + await page.viewport(1400, 900); + const lead = threadWithHistory("task-lead", 1); + const seat = threadWithHistory("task-seat", 1); + using _environment = installFakeEnvironment([lead, seat]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const leadRef = scopeThreadRef(ENVIRONMENT_ID, lead.id); + // The task's tabs and its details are open on the task thread's panels; the seat's are empty. + useRightPanelStore.getState().open(leadRef, "task-evidence"); + useRightPanelStore.getState().setThreadPanelOpen(leadRef, "inline", true); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${seat.id}`] }), + ); + await router.load(); + await using screen = await render( + + + + + , + { + // AppRoot brings its own router. + router: false, + }, + ); + await expect + .element(screen.getByRole("textbox", { name: `Message ${seat.title}`, exact: true })) + .toBeVisible(); + // The right panel is the task thread's, with the task's evidence in it. + await expect + .element(screen.getByRole("button", { name: "Task evidence", exact: true })) + .toBeVisible(); + await expect.element(screen.getByText("Execution and checkpoints")).toBeVisible(); + // So are the details, whose Task item reads the board's task. + const taskItem = page.getByRole("region", { name: "Task", exact: true }); + await expect.element(taskItem.getByText("Make the sync stop dropping rows.")).toBeVisible(); +}); + +it("a board task's thread opened by its own route keeps the task's tabs saved for its task view, out of sight", async () => { + await page.viewport(1400, 900); + const lead = threadWithHistory("task-own-route", 1); + using _environment = installFakeEnvironment([lead]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const leadRef = scopeThreadRef(ENVIRONMENT_ID, lead.id); + useRightPanelStore.getState().open(leadRef, "task-evidence"); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${lead.id}`] }), + ); + await router.load(); + const app = (board: ReturnType | null) => ( + + + + ); + await using screen = await render(app(null), { + // AppRoot brings its own router. + router: false, + }); + await expect + .element(screen.getByRole("textbox", { name: `Message ${lead.title}`, exact: true })) + .toBeVisible(); + // With no board task around it, the panel is the thread's own: no task tab, and none offered. + await expect.element(screen.getByText("Open a surface")).toBeVisible(); + await expect.element(screen.getByText("Task evidence")).not.toBeInTheDocument(); + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, leadRef).surfaces, + ).toEqual([{ id: "task-evidence", kind: "task-evidence" }]); + await screen.rerender(app(boardTask())); + await expect + .element(screen.getByRole("button", { name: "Task evidence", exact: true })) + .toBeVisible(); +}); + +it("a thread without the task's project, shown in a board task's view, leaves the task's file tabs alone", async () => { + await page.viewport(1400, 900); + const lead = threadWithHistory("task-files-lead", 1); + // The conversation the task was filed from, in a project this environment does not have. + const source = { + ...threadWithHistory("task-files-source", 1), + projectId: ProjectId.make("project-elsewhere"), + }; + using _environment = installFakeEnvironment([lead, source]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const leadRef = scopeThreadRef(ENVIRONMENT_ID, lead.id); + useRightPanelStore.getState().open(leadRef, "files"); + useRightPanelStore.getState().open(leadRef, "task-evidence"); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${source.id}`] }), + ); + await router.load(); + const hosted = () => ( + + + + + + ); + await using screen = await render(hosted(), { + // AppRoot brings its own router. + router: false, + }); + await expect + .element(screen.getByRole("textbox", { name: `Message ${source.title}`, exact: true })) + .toBeVisible(); + // With the environment's snapshot in, the next render reconciles a panel's file tabs. + await expect + .poll(() => appAtomRegistry.get(environmentShell.hasSnapshotAtom(ENVIRONMENT_ID))) + .toBe(true); + await screen.rerender(hosted()); + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, leadRef).surfaces.map( + ({ kind }) => kind, + ), + ).toEqual(["files", "task-evidence"]); +}); + +it("a seat in a board task's view floats its own preview, which opens in the seat's own view", async () => { + await page.viewport(1400, 900); + const lead = threadWithHistory("task-preview-lead", 1); + const seat = threadWithHistory("task-preview-seat", 1); + using _environment = installFakeEnvironment([lead, seat]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const leadRef = scopeThreadRef(ENVIRONMENT_ID, lead.id); + const seatRef = scopeThreadRef(ENVIRONMENT_ID, seat.id); + usePreviewMiniPlayerStore.getState().open(seatRef, { + kind: "device", + hostId: "local", + deviceId: "phone", + platform: "ios", + name: "Phone", + }); + using _miniPlayer = { + [Symbol.dispose]: () => usePreviewMiniPlayerStore.getState().removeThread(seatRef), + }; + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${seat.id}`] }), + ); + await router.load(); + using navigate = vi.spyOn(router, "navigate"); + await using screen = await render( + + + + + , + { + // AppRoot brings its own router. + router: false, + }, + ); + await expect + .element(screen.getByRole("region", { name: "Floating device preview" })) + .toBeVisible(); + // The pill shows on hover; the click is what is under test. + screen + .getByRole("button", { name: "Open preview in right panel" }) + .element() + .dispatchEvent(new MouseEvent("click", { bubbles: true })); + const panel = (ref: typeof leadRef) => + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).surfaces; + expect(panel(seatRef)).toEqual([expect.objectContaining({ kind: "device" })]); + expect(panel(leadRef)).toEqual([]); + expect(navigate).toHaveBeenCalledWith( + expect.objectContaining({ to: "/$environmentId/$threadId" }), + ); +}); + it("a subagent tab shows its read-only bar under no header of its own", async () => { const parent = threadWithHistory("subagent-parent", 1); const subagent = { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 30a52ba753d35..9c345b8dc8ea7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,4 +1,6 @@ import { useThreadInspection } from "./chat/ThreadInspectionContext"; +import { useThreadPanelHost } from "./chat/ThreadPanelHostContext"; +import { useBoardTask } from "./delivery/BoardTaskContext"; import { deriveTeamChatPhase } from "@t3tools/client-runtime/state/thread-workflows"; import { m } from "../i18n/messages"; import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; @@ -223,10 +225,10 @@ import { FileMetadataThreadProvider } from "../hooks/FileMetadataThreadProvider" import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout"; import { PopoverCreateHandle } from "./ui/popover"; import { - selectActiveRightPanel, - selectActiveRightPanelSurface, + savedMoveIndex, selectThreadPanelOpen, selectThreadRightPanelState, + shownRightPanelState, useRightPanelStore, } from "../rightPanelStore"; import { isPreviewSupportedInRuntime, useThreadPreviewState } from "../previewStateStore"; @@ -469,6 +471,23 @@ const EMPTY_COMPOSER_BANNER_ITEMS: ReadonlyArray = []; const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet = new Set(); +/** What a view hosting this thread adds to it. An ordinary thread has none of these. */ +export interface ChatViewSlots { + /** The header's title in place of the thread's own. */ + readonly title?: string; + /** The header's parent breadcrumb in place of the thread's own: the way back to the host. */ + readonly parent?: { readonly title: string; readonly open: () => void }; + readonly headerActions?: ReactNode; + /** Under the header, above the timeline. */ + readonly banner?: ReactNode; + /** Above the composer, and shown with no composer too. */ + readonly composerLane?: ReactNode; + /** False when the thread takes no messages here: there is no composer. */ + readonly composer?: boolean; + /** The host's own tabs, which the right panel's + menu then offers. */ + readonly onAddTaskSurface?: (kind: "task-evidence" | "task-deployments") => void; +} + type ChatViewProps = | { environmentId: EnvironmentId; @@ -479,6 +498,7 @@ type ChatViewProps = /** A side chat in its parent's right panel; the parent keeps the keyboard and workspace UI. */ embedded?: SideChatParentPanel; unavailableContent?: ReactNode; + slots?: ChatViewSlots; routeKind: "server"; draftId?: never; } @@ -510,6 +530,7 @@ export default function ChatView(props: ChatViewProps) { embedded: parentPanel, } = props; const embedded = parentPanel !== undefined; + const slots = routeKind === "server" ? props.slots : undefined; const inspectThread = useThreadInspection(); const panelHostShell = useQuietThreadShell(parentPanel?.hostRef ?? null); const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); @@ -1133,6 +1154,18 @@ export default function ChatView(props: ChatViewProps) { })(); const activeThreadRef = useActiveThreadRef(activeThread); const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null; + // The right panel and the details panel are the host's when a workspace shows this thread in its + // own thread's place. An embedded thread has none of its own, so it takes no host. + const panelHost = useThreadPanelHost(); + const panelThreadRef = + useActiveThreadRef( + panelHost && !embedded + ? { environmentId: panelHost.environmentId, id: panelHost.threadId } + : null, + ) ?? activeThreadRef; + const panelThreadKey = panelThreadRef ? scopedThreadKey(panelThreadRef) : null; + // This thread stands in the host's place, as a seat in its task's view; its previews stay its own. + const shownInHostPlace = panelThreadKey !== activeThreadKey; const lastThreadSelectionRef = useRef<{ key: string; selection: ModelSelection } | null>(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the thread's selection is server state outside React; a switch from any surface must retire an explicit composer pick left on the old provider, which would otherwise pin the picker and revert the next send useEffect(() => { @@ -1193,21 +1226,22 @@ export default function ChatView(props: ChatViewProps) { if (anchorRunSettled) { setTimelineAnchor({ threadKey: activeThreadKey, messageId: null }); } - const activeRightPanelKind = useRightPanelStore((state) => - selectActiveRightPanel(state.byThreadKey, activeThreadRef), + const savedRightPanelState = useRightPanelStore((state) => + selectThreadRightPanelState(state.byThreadKey, panelThreadRef), ); + const boardTaskInView = useBoardTask() !== null; + const rightPanelState = shownRightPanelState(savedRightPanelState, boardTaskInView); + const activeRightPanelSurface = rightPanelState.isOpen + ? (rightPanelState.surfaces.find((surface) => surface.id === rightPanelState.activeSurfaceId) ?? + null) + : null; + const activeRightPanelKind = activeRightPanelSurface?.kind ?? null; const diffOpen = activeRightPanelKind === "diff"; - const rightPanelState = useRightPanelStore((state) => - selectThreadRightPanelState(state.byThreadKey, activeThreadRef), - ); const shouldUsePlanSidebarSheet = prefersPlanSidebarSheet && rightPanelState.maximized !== true; - const activeRightPanelSurface = useRightPanelStore((state) => - selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef), - ); - const activePreviewState = useThreadPreviewState(activeThreadRef); + const activePreviewState = useThreadPreviewState(panelThreadRef); const activePreviewServerEpoch = activePreviewState.serverEpoch; - const resolvePreviewRuntimeTabId = activeThreadRef - ? (tabId: string) => previewRuntimeTabId(activeThreadRef, activePreviewServerEpoch, tabId) + const resolvePreviewRuntimeTabId = panelThreadRef + ? (tabId: string) => previewRuntimeTabId(panelThreadRef, activePreviewServerEpoch, tabId) : undefined; const activePreviewMiniPlayer = usePreviewMiniPlayerStore((state) => selectThreadPreviewMiniPlayer(state.byThreadKey, activeThreadRef), @@ -1230,7 +1264,7 @@ export default function ChatView(props: ChatViewProps) { rightPanelOpen && activeThreadRef !== null, rightPanelPresenceValue, panelAnimationsActive, - activeThreadKey, + panelThreadKey, panelAnimationDurationMs, ); const rightPanelPresent = rightPanelPresence.present; @@ -1320,9 +1354,10 @@ export default function ChatView(props: ChatViewProps) { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops file surfaces from the right panel store once bootstrap shows the thread has no workspace useEffect(() => { - if (!activeThreadRef || !activeEnvironmentBootstrapComplete) return; - useRightPanelStore.getState().reconcileFileSurfaces(activeThreadRef, activeProject !== null); - }, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]); + // Another thread's project says nothing of the files in a panel that is the host's. + if (!panelThreadRef || !activeEnvironmentBootstrapComplete || shownInHostPlace) return; + useRightPanelStore.getState().reconcileFileSurfaces(panelThreadRef, activeProject !== null); + }, [activeEnvironmentBootstrapComplete, activeProject, panelThreadRef, shownInHostPlace]); const activeEnvironment = activeThread == null ? null : (environmentById.get(activeThread.environmentId) ?? null); @@ -1726,8 +1761,8 @@ export default function ChatView(props: ChatViewProps) { }; const downloadFileAttachmentStable = useStableCallback(downloadFileAttachment); const openFileAttachment = (attachment: ChatFileAttachment) => { - if (activeThreadRef) { - useRightPanelStore.getState().openAttachment(activeThreadRef, attachment); + if (panelThreadRef) { + useRightPanelStore.getState().openAttachment(panelThreadRef, attachment); return; } }; @@ -1950,7 +1985,7 @@ export default function ChatView(props: ChatViewProps) { turnDiffSummaries.some((summary) => summary.repositories !== undefined); // Provider-native subagents cannot take messages; approvals and questions go to the top-level parent. const showProviderSubagentBar = isProviderSubagent; - const composerMounted = !showProviderSubagentBar; + const composerMounted = !showProviderSubagentBar && slots?.composer !== false; const providerSubagentModels = selectedProviderEntry?.models ?? EMPTY_PROVIDER_MODELS; // Providers can report dated model ids or aliases. const providerSubagentModelSlug = selectedProviderEntry @@ -1979,7 +2014,7 @@ export default function ChatView(props: ChatViewProps) { shouldShowComposerContextStrip({ isDraftHeroState, persistInActiveThreads: settings.persistComposerContextStrip, - hasActiveProject: activeProject !== null && !showProviderSubagentBar, + hasActiveProject: activeProject !== null && composerMounted, isGitRepo, showEnvironmentIndicator: showComposerEnvironmentIndicator, }); @@ -2158,8 +2193,16 @@ export default function ChatView(props: ChatViewProps) { ? activePreviewMiniPlayer : null; const canvasPreview = useThreadPreviewCanvasSource(activeThreadRef, shownPreviewMiniPlayer); + // The preview opens in this thread's own panel, which only its own view shows. + const openInOwnView = () => { + if (!activeThreadRef) return; + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(activeThreadRef), + }); + }; const threadPanelInlineOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"), + selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, panelThreadRef, "inline"), ); // Selects only the mode, so canvas resizes rerender the chat view only when the // card switches presentation. @@ -2177,7 +2220,7 @@ export default function ChatView(props: ChatViewProps) { const threadPanelOpen = useRightPanelStore((state) => selectThreadPanelOpen( state.threadPanelVisibilityByThreadKey, - activeThreadRef, + panelThreadRef, threadPanelPresentation, ), ); @@ -2252,8 +2295,9 @@ export default function ChatView(props: ChatViewProps) { closeSurfacesToRight: closeRightPanelSurfacesToRightStable, closeAllSurfaces: closeAllRightPanelSurfacesStable, } = useRightPanelSurfaceClose({ - threadRef: activeThreadRef, + threadRef: panelThreadRef, terminalLabelsById: activeTerminalLabelsById, + surfaces: rightPanelState.surfaces, }); const closeRightPanelSurfaceStable = closeRightPanelSurface; const persistThreadSettingsForNextTurn = async (input: { @@ -2610,7 +2654,7 @@ export default function ChatView(props: ChatViewProps) { toggleThreadPanelStable, shortcuts: rightPanelShortcuts, } = useRightPanelActions({ - activeThreadRef, + activeThreadRef: panelThreadRef, activeProject, activeRightPanelSurface, activePreviewState, @@ -3202,7 +3246,7 @@ export default function ChatView(props: ChatViewProps) { embedded && (activeThread?.worktreePath ?? null) !== (panelHostShell?.worktreePath ?? null); // A maximized panel covers the terminal drawer the command runs in. const runSideChatShellCommandStable = useStableCallback((command: string) => { - if (activeThreadRef) useRightPanelStore.getState().setMaximized(activeThreadRef, false); + if (panelThreadRef) useRightPanelStore.getState().setMaximized(panelThreadRef, false); runShellCommandStable(command); }); // Main-thread surfaces show this reason; `/side` sent anyway gets it as a toast. @@ -3225,7 +3269,7 @@ export default function ChatView(props: ChatViewProps) { ? gt("Available once the thread's worktree is set up.") : null; const openSideChatStable = useStableCallback(() => void sideChat.open()); - const openSurfaceInMainView = useOpenSurfaceInMainView(activeThreadRef); + const openSurfaceInMainView = useOpenSurfaceInMainView(panelThreadRef); const sendSideChatStable = useStableCallback(sideChat.open); const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } = useTimelineRewind({ @@ -3701,11 +3745,11 @@ export default function ChatView(props: ChatViewProps) { ); } - const rightPanelContent = activeThreadRef ? ( + const rightPanelContent = panelThreadRef ? ( {embedded ? null : ( )} @@ -3845,11 +3889,16 @@ export default function ChatView(props: ChatViewProps) { activeThreadEnvironmentId={activeThread.environmentId} activeThreadId={activeThread.id} isServerThread={isServerThread} - activeThreadTitle={activeThread.title} + activeThreadTitle={slots?.title ?? activeThread.title} activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null} activeProject={activeProject ?? null} - parentThreadLink={headerParentThreadLink} - onOpenThread={onOpenRelatedThreadStable} + parentThreadLink={ + slots?.parent + ? { threadId: activeThread.id, title: slots.parent.title } + : headerParentThreadLink + } + onOpenThread={slots?.parent ? slots.parent.open : onOpenRelatedThreadStable} + actions={slots?.headerActions} rightPanelOpen={inlineRightPanelOwnsTitleBar} onNewThreadInProject={handleNewThreadInActiveProjectStable} {...(activeDraftLogicalProjectKey @@ -3859,6 +3908,7 @@ export default function ChatView(props: ChatViewProps) { /> )} + {slots?.banner}
+ {slots?.composerLane} -
+
) : null} + {/* The host's own preview tabs stay in its panel, so its sessions stay current too. */} + {canOperatePreview && + panelThreadRef && + shownInHostPlace && + activeEnvironmentServerBrowser && + !embedded ? ( + + ) : null} {activeThreadRef && shownPreviewMiniPlayer && !embedded ? ( ) : null} @@ -4500,7 +4560,7 @@ export default function ChatView(props: ChatViewProps) { { - if (activeThreadRef) - useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title); + if (panelThreadRef) + useRightPanelStore.getState().renameDevice(panelThreadRef, surfaceId, title); }} onCloseOtherSurfaces={closeOtherRightPanelSurfacesStable} onCloseSurfacesToRight={closeRightPanelSurfacesToRightStable} onCloseAllSurfaces={closeAllRightPanelSurfacesStable} - onMoveSurface={moveRightPanelSurfaceStable} + onMoveSurface={(surfaceId, toIndex) => + moveRightPanelSurfaceStable( + surfaceId, + savedMoveIndex(savedRightPanelState.surfaces, renderedRightPanelSurfaces, toIndex), + ) + } onCopyFilePath={copyRightPanelFilePathStable} onAddBrowser={() => createBrowserSurface()} onAddBrowserInProfile={createBrowserSurfaceStable} @@ -4557,6 +4622,7 @@ export default function ChatView(props: ChatViewProps) { deviceAvailable={activeThreadRef !== null} sideChatAvailable={sideChat.available} sideChatDisabledReason={sideChatDisabledReason} + onAddTaskSurface={slots?.onAddTaskSurface} > {rightPanelContent} diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index afb68b299a692..53798a2594673 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -8,6 +8,8 @@ import { buildNestedSearchItems, resolveCommandPaletteProject, buildThreadActionItems, + boardTaskSearchPath, + buildBoardTaskActionItems, buildLinkedThreadActionItems, filterPinnedBrowseEntries, filterCommandPaletteGroups, @@ -97,6 +99,78 @@ describe("linked pull request thread navigation", () => { }); }); +describe("board tasks", () => { + it("lists the board's tasks as the person types, by number or title, each opening its task", async () => { + const runTask = vi.fn(async () => {}); + const taskSearchItems = buildBoardTaskActionItems({ + tasks: [ + { id: "task-1", number: 1001, title: "Rework the board sync" }, + { id: "task-2", number: 1002, title: "Ship the onboarding copy" }, + ], + icon: null, + runTask, + }); + const search = (query: string, tasks = taskSearchItems) => + filterCommandPaletteGroups({ + activeGroups: [], + query, + isInSubmenu: false, + projectSearchItems: [], + threadSearchItems: [], + taskSearchItems: tasks, + }); + const titles = (query: string, tasks = taskSearchItems) => + search(query, tasks) + .filter((group) => group.value === "tasks-search") + .flatMap((group) => group.items.map((item) => item.title)); + expect(titles("sync")).toEqual(["#1001 Rework the board sync"]); + expect(titles("1002")).toEqual(["#1002 Ship the onboarding copy"]); + expect(titles("#1001")).toEqual(["#1001 Rework the board sync"]); + // Nothing before anything is typed, and nothing from a board that is not there. + expect(search("")).toEqual([]); + expect(titles("sync", [])).toEqual([]); + const [group] = search("onboarding"); + expect(group?.label).toBe("Tasks"); + const picked = group?.items[0]; + if (picked?.kind === "action") await picked.run(); + expect(runTask).toHaveBeenCalledExactlyOnceWith("task-2"); + }); + + it("asks the board's own search for what is typed, so a task older than the newest 200 is found", () => { + // 250 tasks, newest first as the engine lists them; the one asked for is the oldest. + const board = Array.from({ length: 250 }, (_, index) => { + const number = 250 - index; + return { id: `task-${number}`, number, title: number === 1 ? "Migrate the ledger" : "Chore" }; + }); + // The engine's list: `q` looks through every task, and `limit` cuts what comes back. + const engine = (path: string) => { + const params = new URL(path, "http://engine").searchParams; + const q = (params.get("q") ?? "").toLowerCase(); + return board + .filter((task) => `#${task.number} ${task.title}`.toLowerCase().includes(q)) + .slice(0, Number(params.get("limit"))); + }; + const path = boardTaskSearchPath(" ledger ", "work"); + expect(path).toBe("/api/tasks?q=ledger&limit=100&set=work"); + const groups = filterCommandPaletteGroups({ + activeGroups: [], + query: "ledger", + isInSubmenu: false, + projectSearchItems: [], + threadSearchItems: [], + taskSearchItems: buildBoardTaskActionItems({ + tasks: engine(path!), + icon: null, + runTask: async () => {}, + }), + }); + expect(groups.flatMap((group) => group.items.map((item) => item.title))).toEqual([ + "#1 Migrate the ledger", + ]); + expect(boardTaskSearchPath(" ", "work")).toBeNull(); + }); +}); + describe("reduceCommandPaletteUiState", () => { it("opens PR search from another overlay and replaces an earlier search", () => { const first = reduceCommandPaletteUiState( @@ -704,13 +778,25 @@ describe("buildThreadActionItems", () => { ]); }); - it("hides subagent threads and tasks shown under their parent but keeps forks", () => { + it("hides subagent threads, board tasks' conversations and tasks shown under their parent but keeps forks", () => { const parentId = ThreadId.make("parent"); const delegatedId = ThreadId.make("delegated"); + const boardTaskId = ThreadId.make("board-task"); const items = buildThreadActionItems({ threads: [ makeThread({ id: parentId, title: "Parent" }), makeThread({ id: delegatedId, title: "Delegated task" }), + // A board task's conversation opens in the task's view, which the board's rows list. + makeThread({ + id: boardTaskId, + title: "Board task conversation", + lineage: { + rootThreadId: boardTaskId, + parentThreadId: null, + relationshipToParent: null, + engineIntake: "board-task:board-1:task-7", + }, + }), makeThread({ id: ThreadId.make("subagent"), title: "Subagent", diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 2d6415ff22975..cb12f2946e398 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -28,6 +28,7 @@ import { type KeybindingCommand, type SourceControlDiscoveryResult, type SourceControlRepositoryInfo, + isServerOwnedThreadLineage, THREAD_JUMP_KEYBINDING_COMMANDS, } from "@t3tools/contracts"; import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem"; @@ -35,6 +36,7 @@ import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; import { type ReactNode } from "react"; import { msg } from "gt-react"; import { m, type MessageResolver } from "../i18n/messages"; +import { queryValue } from "../lib/deliveryBoard"; import { formatRelativeTimeLabel } from "../timestampFormat"; import { type Project, type SidebarThreadSummary, type Thread } from "../types"; @@ -93,6 +95,42 @@ export function buildLinkedThreadActionItems( ]; } +/** + * The board's own search for what is typed, as its task list makes it: the engine looks through + * every task on the board, not only the newest it lists. With nothing typed there is no read. + */ +export function boardTaskSearchPath(query: string, boardSet: string): string | null { + const q = query.trim(); + return q ? `/api/tasks?q=${queryValue(q)}&limit=100&set=${boardSet}` : null; +} + +/** The board's tasks as rows, found by number or title; each opens its task's view. */ +export function buildBoardTaskActionItems( + input: { + readonly tasks: ReadonlyArray<{ + readonly id: string; + readonly number: number; + readonly title: string; + }>; + readonly icon: ReactNode; + readonly runTask: (taskId: string) => Promise; + }, + resolve: MessageResolver = m, +): CommandPaletteActionItem[] { + return input.tasks.map((task) => { + const title = `#${task.number} ${task.title}`; + return { + kind: "action", + value: `open-task:${task.id}`, + title, + searchTerms: [title, String(task.number)], + description: resolve(msg("Opens the task on the board")), + icon: input.icon, + run: () => input.runTask(task.id), + }; + }); +} + export function browseInputEndPaddingClass(input: { readonly willCreateProjectPath: boolean; readonly hasHighlightedBrowseItem: boolean; @@ -487,6 +525,8 @@ export function buildThreadActionItems thread.archivedAt === null && + // A board task's conversation opens in its task, which the board's own rows list. + !isServerOwnedThreadLineage(thread.lineage) && !isShownUnderParent( { environmentId: thread.environmentId, threadId: thread.id }, thread.lineage, @@ -614,6 +654,8 @@ export function filterCommandPaletteGroups( projectSearchItems: ReadonlyArray; settingsSearchItems?: ReadonlyArray; threadSearchItems: ReadonlyArray; + /** The board's tasks, listed as threads are: only while searching. */ + taskSearchItems?: ReadonlyArray; /** Threads whose messages match, best first; threads already listed are skipped. */ threadMessageItems?: ReadonlyArray; now?: number; @@ -671,6 +713,13 @@ export function filterCommandPaletteGroups( items: input.threadSearchItems, }); } + if (input.taskSearchItems && input.taskSearchItems.length > 0) { + searchableGroups.push({ + value: "tasks-search", + label: resolve(msg("Tasks")), + items: input.taskSearchItems, + }); + } if (input.projectSearchItems.length > 0) { searchableGroups.push({ value: "projects-search", @@ -696,7 +745,7 @@ export function filterCommandPaletteGroups( const groups = ranked.map(({ group, ranked }): CommandPaletteGroup => { // Secondary items stay below the rest; the sort is stable, so score order holds. const limit = - group.value === "threads-search" + group.value === "threads-search" || group.value === "tasks-search" ? PALETTE_THREAD_LIMIT : group.value === "nested-search" || (searchesEverything && threadsMatch) ? PALETTE_SECONDARY_LIMIT diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 6e3fc7c646003..335ed88855d98 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -256,6 +256,7 @@ import { remoteProjectSourceIcon, sourceControlHostIcon, } from "./CommandPaletteAddProject"; +import { useCommandPaletteTaskItems } from "./CommandPaletteTaskItems"; import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems"; import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems"; import { @@ -970,6 +971,7 @@ function OpenCommandPaletteDialog(props: { isSearchPending: isThreadSearchPending, isSearchFailed: isThreadSearchFailed, } = useCommandPaletteThreadItems({ activeThread: activeThread ?? null, threadSearchQuery }); + const taskSearchItems = useCommandPaletteTaskItems(threadSearchQuery); // Recent means used recently: written in or opened, whichever is later. The // open thread would always lead that list, so it is left out. const activeThreadValue = activeThread @@ -1981,6 +1983,7 @@ function OpenCommandPaletteDialog(props: { messages, ) : allThreadItems, + taskSearchItems, threadMessageItems: isLinkedThreadSearch ? [] : threadMessageItems, now: searchNow, }, diff --git a/apps/web/src/components/CommandPaletteTaskItems.tsx b/apps/web/src/components/CommandPaletteTaskItems.tsx new file mode 100644 index 0000000000000..d54bb18abef42 --- /dev/null +++ b/apps/web/src/components/CommandPaletteTaskItems.tsx @@ -0,0 +1,44 @@ +import { useNavigate } from "@tanstack/react-router"; +import { useMessages } from "gt-react"; +import { SquareKanbanIcon } from "lucide-react"; + +import { parseCards } from "../lib/delivery"; +import { boardSetOf } from "../lib/deliveryBoard"; +import { + useBoardPreferences, + useDeliveryEnabled, + useDeliveryEnvironmentId, + useDeliveryRead, +} from "../state/delivery"; +import { + boardTaskSearchPath, + buildBoardTaskActionItems, + ITEM_ICON_CLASS, +} from "./CommandPalette.logic"; + +/** + * The board's tasks for a palette search, from the search the board's own list makes. It is read + * only while there is something to search for; with no board there is nothing to list. + */ +export function useCommandPaletteTaskItems(searchQuery: string) { + const navigate = useNavigate(); + const messages = useMessages(); + const environmentId = useDeliveryEnvironmentId(); + const enabled = useDeliveryEnabled(environmentId); + const { boardSet, shared } = useBoardPreferences(environmentId); + const path = boardTaskSearchPath(searchQuery, boardSetOf(boardSet)); + const read = useDeliveryRead(enabled && !shared && path ? environmentId : null, path); + return buildBoardTaskActionItems( + { + tasks: parseCards(read.body), + icon: , + runTask: async (taskId) => { + await navigate({ + to: "/board", + search: environmentId ? { environment: environmentId, task: taskId } : { task: taskId }, + }); + }, + }, + messages, + ); +} diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 515d5cdbfb32b..424da12f229e8 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -2,7 +2,7 @@ import "~/index.css"; import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group"; import type { RightPanelSurface } from "~/rightPanelStore"; @@ -255,6 +255,29 @@ describe("right panel thumb buttons", () => { }); }); +describe("board task tabs", () => { + it("are in the + menu only where a board task's view hosts the thread", async () => { + const onAddTaskSurface = vi.fn(); + const props = panel(DIFF_SURFACE).props as RightPanelTabsProps; + await using screen = await render({null}); + await screen.getByRole("button", { name: "Add panel surface" }).click(); + await expect.element(page.getByRole("menuitem", { name: /Files/ })).toBeVisible(); + await expect + .element(page.getByRole("menuitem", { name: /Task evidence/ })) + .not.toBeInTheDocument(); + await userEvent.keyboard("{Escape}"); + await screen.rerender( + + {null} + , + ); + await screen.getByRole("button", { name: "Add panel surface" }).click(); + await expect.element(page.getByRole("menuitem", { name: /Task evidence/ })).toBeVisible(); + await page.getByRole("menuitem", { name: /Deployments/ }).click(); + expect(onAddTaskSurface).toHaveBeenCalledExactlyOnceWith("task-deployments"); + }); +}); + const DEVICE_SURFACE: RightPanelSurface = { id: "device:host:phone", kind: "device", diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 51d66ae5fba94..5688509330070 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -171,6 +171,8 @@ export interface RightPanelTabsProps { sideChatAvailable?: boolean; /** Overrides the default reason while side chats are available but cannot start. */ sideChatDisabledReason?: string | null; + /** Absent where no board task's view hosts the thread. */ + onAddTaskSurface?: ((kind: TaskSurfaceKind) => void) | undefined; pullRequestStatusSeeds?: Readonly>; children: ReactNode; } @@ -225,6 +227,31 @@ const SURFACE_UNAVAILABLE_HINTS = { sideChat: msg("Available after the first message."), } as const; +type TaskSurfaceKind = "task-evidence" | "task-deployments"; + +/** A board task's own tabs, offered only where a board task's view hosts the thread. */ +function taskSurfaceActions(onAdd: ((kind: TaskSurfaceKind) => void) | undefined) { + if (!onAdd) return []; + return [ + { + label: msg("Task evidence"), + icon: ClipboardListIcon, + shortcut: "E", + available: true, + disabledReason: "", + onClick: () => onAdd("task-evidence"), + }, + { + label: msg("Deployments"), + icon: RocketIcon, + shortcut: "O", + available: true, + disabledReason: "", + onClick: () => onAdd("task-deployments"), + }, + ]; +} + type TabContextMenuAction = | "open-in-main-view" | "rename" @@ -356,6 +383,7 @@ function RightPanelEmptyState(props: { deviceAvailable: boolean; sideChatAvailable: boolean; sideChatDisabledReason: string | null; + onAddTaskSurface?: ((kind: TaskSurfaceKind) => void) | undefined; }) { const gt = useGT(); const messages = useMessages(); @@ -433,6 +461,7 @@ function RightPanelEmptyState(props: { }, ] : []), + ...taskSurfaceActions(props.onAddTaskSurface), ] as const; type SurfaceAction = (typeof actions)[number]; @@ -1282,6 +1311,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { }, ] : []), + ...taskSurfaceActions(props.onAddTaskSurface), ] as const; const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { @@ -1712,6 +1742,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { deviceAvailable={props.deviceAvailable} sideChatAvailable={props.sideChatAvailable === true} sideChatDisabledReason={props.sideChatDisabledReason ?? null} + onAddTaskSurface={props.onAddTaskSurface} /> ) : ( props.children diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 662836edf2b9a..28f7bbba69165 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,4 +1,5 @@ import { TeamBadge } from "../delivery/TeamBadge"; +import { useBoardTask } from "../delivery/BoardTaskContext"; import { TeamChatToggle } from "../delivery/TeamChatToggle"; import { TeamPicker } from "../delivery/TeamPicker"; import { OrchestratorChatSetup } from "../delivery/OrchestratorChatSetup"; @@ -517,6 +518,7 @@ const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) { const navigate = useNavigate(); + const boardTask = useBoardTask(); const gt = useGT(); const m = useMessages(); const { @@ -2681,7 +2683,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) /> ) : activeThreadId && !orchestratorMode ? ( - + {/* A board task's view shows its team in the header, once. */} + {boardTask ? null : ( + + )} ({ useThreadActionMenu: () => ({ openMenu, closeMenu: () => {} }), })); +import type { ReactNode } from "react"; + import { render, stubGlobal } from "../../../test/render"; import { ChatHeader } from "./ChatHeader"; -function header(title: string) { +function header(title: string, actions?: ReactNode) { return ( <> {}} rightPanelOpen={false} onNewThreadInProject={() => {}} + actions={actions} />
Outside rename
); } +it("shows what a hosting view adds to the header, and nothing of it on an ordinary thread", async () => { + await using screen = await render( + header("#12 Fix the sync", ), + ); + await expect + .element(screen.getByRole("button", { name: "What can be done with this task" })) + .toBeVisible(); + await screen.rerender(header("New thread")); + await expect + .element(screen.getByRole("button", { name: "What can be done with this task" })) + .not.toBeInTheDocument(); +}); + it.each(["blur", "Enter"] as const)( "preserves a concurrent title update when an untouched rename ends with %s", async (finish) => { diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 133c80f304d0a..6f0f862fdf3f1 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -19,6 +19,7 @@ import { useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, + type ReactNode, } from "react"; import { isTrailingDoubleClick } from "../Sidebar.logic"; import { Badge } from "../ui/badge"; @@ -58,6 +59,8 @@ interface ChatHeaderProps { onNewThreadInProject: () => void; onOpenProjectSettings?: (() => void) | undefined; onFindInThread?: ((threadRef: ScopedThreadRef) => void) | undefined; + /** Beside the share indicator: what a view hosting the thread adds to its header. */ + actions?: ReactNode; } function resolveRenameCommit(input: { @@ -83,6 +86,7 @@ export const ChatHeader = memo(function ChatHeader({ onNewThreadInProject, onOpenProjectSettings, onFindInThread, + actions, }: ChatHeaderProps) { const gt = useGT(); const activeProjectName = activeProject?.isScratch ? gt("No project") : activeProject?.title; @@ -412,6 +416,7 @@ export const ChatHeader = memo(function ChatHeader({ {isServerThread ? : null} + {actions}
); }); diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index b149e64f8d05f..bcbe29bc988c3 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -37,6 +37,9 @@ const DevicePanel = lazy(() => import("../device/DevicePanel").then((module) => ({ default: module.DevicePanel })), ); const FilePreviewPanel = lazy(() => import("../files/FilePreviewPanel")); +const BoardTaskTab = lazy(() => + import("../delivery/TaskPanelTab").then((module) => ({ default: module.TaskPanelTab })), +); type RightPanelTerminalProps = Omit< PersistentThreadTerminalPanelProps, @@ -287,9 +290,13 @@ export function RightPanelSurfaceContent(props: { ); } - // Board task surfaces belong to a task's own panel; a thread never hosts them. + // A board task's tabs show only where a board task's view hosts the thread; elsewhere nothing. case "task-evidence": case "task-deployments": - return null; + return ( + + + + ); } } diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx index 9959dbe2dc41c..a19e11b0d57f9 100644 --- a/apps/web/src/components/chat/ThreadDetailsCard.tsx +++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx @@ -13,6 +13,7 @@ import { cn } from "../../lib/utils"; import { Popover, PopoverPopup, PopoverCreateHandle } from "../ui/popover"; import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore"; import { useChatCanvas } from "./ChatCanvasContext"; +import { useThreadPanelHost } from "./ThreadPanelHostContext"; import { THREAD_DETAILS_CARD_GAP, resolveThreadDetailsCardDensity, @@ -43,11 +44,13 @@ export function ThreadDetailsCard({ const placement = canvas?.detailsCardPlacement ?? null; const mode = placement ? "inline" : "popover"; const topInset = canvas?.detailsCardTopInset ?? 0; + // Whether it shows is the host's, as ChatView reads it, when a workspace hosts this thread. + const panelThread = useThreadPanelHost() ?? threadRef; const inlineOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "inline"), + selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, panelThread, "inline"), ); const popoverOpen = useRightPanelStore((state) => - selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, threadRef, "popover"), + selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, panelThread, "popover"), ); const measurementKey = `${threadRef.environmentId}:${threadRef.threadId}:${preferredPlacement?.width ?? "popup"}:${contentKey}`; const [measurements, setMeasurements] = useState({ @@ -67,8 +70,8 @@ export function ThreadDetailsCard({ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the popover flag in the right panel store when the derived mode turns inline useLayoutEffect(() => { if (mode === "inline" && popoverOpen) - useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", false); - }, [mode, popoverOpen, threadRef]); + useRightPanelStore.getState().setThreadPanelOpen(panelThread, "popover", false); + }, [mode, popoverOpen, panelThread]); const [contentElement, setContentElement] = useState(null); const { environmentId, threadId } = threadRef; // Re-measures when the density or measurement key changes, so each density's @@ -80,10 +83,11 @@ export function ThreadDetailsCard({ const measure = () => { const frame = element.closest("[data-thread-details-card]"); const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0); - // PR lists, servers, lineage, side chats and automations scroll as they grow. Counting them - // toward density would hide the section and workspace controls when the user asks to see more. + // PR lists, servers, lineage, side chats, automations and a board task's details scroll as + // they grow. Counting them toward density would hide the section and workspace controls when + // the user asks to see more. const lists = element.querySelectorAll( - "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-automations-panel], [data-thread-details-server-overflow]", + "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-automations-panel], [data-thread-details-server-overflow], [data-thread-details-task]", ); const fittingHeight = next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0); @@ -145,7 +149,7 @@ export function ThreadDetailsCard({ details.cancel(); return; } - useRightPanelStore.getState().setThreadPanelOpen(threadRef, "popover", open); + useRightPanelStore.getState().setThreadPanelOpen(panelThread, "popover", open); }} > {placement && inlineOpen ? ( diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx index 52e5033d58d4d..0736176be56b6 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.browser.test.tsx @@ -82,7 +82,9 @@ vi.mock(import("~/state/vcs"), async (importOriginal) => { }); import { render } from "../../../test/render"; +import { parseTask } from "../../lib/delivery"; import { useRightPanelStore } from "../../rightPanelStore"; +import { BoardTaskContext } from "../delivery/BoardTaskContext"; import { PopoverCreateHandle } from "../ui/popover"; import { ChatCanvasContext } from "./ChatCanvasContext"; import { resolveChatCanvasLayout } from "./chatCanvasLayout"; @@ -203,6 +205,40 @@ it("shows a linked pull request in a folder that is not a git repository", async await expect.element(page.getByRole("button", { name: "Initialize Git" })).toBeVisible(); }); +it("shows the Task item only where a board task's view hosts the thread, with the item on", async () => { + using fixture = setup({ workspaceRoot: "/work/plain", folder: "/work/plain" }); + await using screen = await render(); + await expect.element(page.getByRole("region", { name: "Workspace" })).toBeVisible(); + expect(document.querySelector("[data-thread-details-task]")).toBeNull(); + const task = parseTask({ + id: "t1", + number: 12, + title: "Fix the sync", + body: "Make the sync stop dropping rows.", + state: "closed", + lane: "completed", + card: { id: "t1", number: 12, title: "Fix the sync", lane: "completed" }, + }); + await screen.rerender( + {}, + openTask: () => {}, + openThread: () => {}, + seats: { thread: () => null, current: null, open: () => {} }, + }} + > + + , + ); + await expect.element(page.getByRole("region", { name: "Task" })).toBeVisible(); + await expect.element(page.getByText("Make the sync stop dropping rows.")).toBeVisible(); +}); + it("offers no Initialize Git before the server config says where No project lives", async () => { using fixture = setup({ workspaceRoot: SCRATCH_ROOT, diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 085815bed02cf..a16da49f3066c 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -20,7 +20,9 @@ import ProjectScriptsControl, { type ProjectScriptActionResult, } from "../ProjectScriptsControl"; import { T, useGT } from "gt-react"; -import { useState, type ComponentProps } from "react"; +import { lazy, Suspense, useState, type ComponentProps } from "react"; +import { useBoardTask } from "../delivery/BoardTaskContext"; +import { taskHasRelatedWork } from "../delivery/relatedTaskGroups"; import { ThreadDetailsCard } from "./ThreadDetailsCard"; import { OpenInPicker } from "./OpenInPicker"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; @@ -49,6 +51,14 @@ import { } from "./threadDetailsPanelStyles"; import { Menu, MenuPopup } from "../ui/menu"; +// Board code loads only where a board task's view hosts the thread. +const TaskDetailsItem = lazy(() => + import("../delivery/TaskDetails").then((module) => ({ default: module.TaskDetailsItem })), +); +const TaskRelatedWork = lazy(() => + import("../delivery/TaskRelatedWork").then((module) => ({ default: module.TaskRelatedWork })), +); + interface ThreadDetailsPanelProps extends Pick< ComponentProps, "anchor" | "handle" @@ -98,6 +108,9 @@ interface ThreadDetailsPanelProps extends Pick< export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { const visible = useClientSettings(resolveThreadDetailsVisibility); const gt = useGT(); + // The Task item and the child tasks come from the board task whose view hosts this thread. + const boardTask = useBoardTask()?.task ?? null; + const taskShown = boardTask !== null && visible.task; const [menuPosition, setMenuPosition] = useState<{ x: number; y: number } | null>(null); const fileScripts = useT3ProjectFileScripts( props.environmentId, @@ -201,11 +214,17 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { return ( <>
+ {taskShown ? ( + + + + ) : null} + {show.environment || show.openIn || show.scripts ? (
@@ -319,6 +338,13 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { threadId={props.threadId} showLineage={visible.lineage} showSideChats={visible.sideChats} + extraGroup={ + boardTask && taskHasRelatedWork(boardTask) ? ( + + + + ) : undefined + } /> ) : null} diff --git a/apps/web/src/components/chat/ThreadPanelHostContext.ts b/apps/web/src/components/chat/ThreadPanelHostContext.ts new file mode 100644 index 0000000000000..d72eff10bb1d8 --- /dev/null +++ b/apps/web/src/components/chat/ThreadPanelHostContext.ts @@ -0,0 +1,9 @@ +import { createContext, useContext } from "react"; +import type { ScopedThreadRef } from "@t3tools/contracts"; + +/** + * A containing workspace whose own thread keeps the panels while it shows a related thread in its + * place: that thread's view shows the host thread's right panel and details panel, not its own. + */ +export const ThreadPanelHostContext = createContext(null); +export const useThreadPanelHost = () => useContext(ThreadPanelHostContext); diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 7f153ed048b4c..013a907ee73b3 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -2,6 +2,7 @@ import "~/index.css"; import { ThreadInspectionContext } from "./ThreadInspectionContext"; import * as DateTime from "effect/DateTime"; import { EnvironmentId, NodeId, ThreadId } from "@t3tools/contracts"; +import type { ReactNode } from "react"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; @@ -177,6 +178,36 @@ it.each([ } }); +it("shows a group its host adds after the lineage's own, even where the thread has no other", async () => { + setup(); + state.projection = { + ...(state.projection as object), + thread: { + id: threadId, + title: "Task conversation", + activeProviderThreadId: null, + lineage: { parentThreadId: null }, + forkedFrom: null, + }, + }; + const panel = (extraGroup?: ReactNode, showLineage = true) => ( + + ); + await using screen = await render(panel()); + expect(screen.container.querySelector("[data-thread-relationships-panel]")).toBeNull(); + await screen.rerender(panel(

Child tasks of the host

)); + await expect.element(screen.getByText("Child tasks of the host")).toBeVisible(); + // Lineage switched off hides the host's group with it. + await screen.rerender(panel(

Child tasks of the host

, false)); + await expect.element(screen.getByText("Child tasks of the host")).not.toBeInTheDocument(); +}); + it("opens an idle child beside the thread, and in its place with the modifier", async () => { setup(); const projection = makeThreadProjectionFixture(); diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index ae2ea727de208..eba91b3e8445a 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -487,6 +487,8 @@ export function ThreadRelationshipsPanel(props: { readonly threadId: ThreadId; readonly showLineage: boolean; readonly showSideChats: boolean; + /** A group the host adds after the lineage's own, such as a board task's child tasks. */ + readonly extraGroup?: ReactNode; }) { const gt = useGT(); const m = useMessages(); @@ -677,7 +679,8 @@ export function ThreadRelationshipsPanel(props: { const lineageVisible = props.showLineage && - (related.length > 0 || + (props.extraGroup !== undefined || + related.length > 0 || active.length > 0 || previous.length > 0 || runningCount > 0 || @@ -1144,6 +1147,7 @@ export function ThreadRelationshipsPanel(props: { } ))} + {props.extraGroup} ) : null} {sideChatsVisible ? ( diff --git a/apps/web/src/components/chat/threadDetailsItems.test.ts b/apps/web/src/components/chat/threadDetailsItems.test.ts index 6e3e746fd7648..6c90b31ed930c 100644 --- a/apps/web/src/components/chat/threadDetailsItems.test.ts +++ b/apps/web/src/components/chat/threadDetailsItems.test.ts @@ -1,13 +1,16 @@ import { describe, expect, it } from "vite-plus/test"; import { + isDefaultThreadDetailsVisibility, resolveThreadDetailsVisibility, + RESET_THREAD_DETAILS_ITEMS, setThreadDetailsItem, THREAD_DETAILS_ITEMS, } from "./threadDetailsItems"; const usage = THREAD_DETAILS_ITEMS.find((item) => item.id === "usage")!; const servers = THREAD_DETAILS_ITEMS.find((item) => item.id === "servers")!; +const task = THREAD_DETAILS_ITEMS.find((item) => item.id === "task")!; describe("thread details items", () => { it.each([ @@ -33,4 +36,21 @@ describe("thread details items", () => { const hidden = { threadDetailsItems: { servers: false }, threadDetailsUsageEnabled: false }; expect(setThreadDetailsItem(hidden, servers, true)).toEqual({}); }); + + it("shows the Task item by default, keeps it off once switched off, and resets it to on", () => { + const fresh = { threadDetailsItems: {}, threadDetailsUsageEnabled: false }; + expect(resolveThreadDetailsVisibility(fresh).task).toBe(true); + expect(isDefaultThreadDetailsVisibility(resolveThreadDetailsVisibility(fresh))).toBe(true); + + const off = setThreadDetailsItem(fresh, task, false); + expect(off).toEqual({ task: false }); + const switchedOff = { threadDetailsItems: off, threadDetailsUsageEnabled: false }; + expect(resolveThreadDetailsVisibility(switchedOff).task).toBe(false); + expect(isDefaultThreadDetailsVisibility(resolveThreadDetailsVisibility(switchedOff))).toBe( + false, + ); + expect(setThreadDetailsItem(switchedOff, task, true)).toEqual({}); + + expect(resolveThreadDetailsVisibility(RESET_THREAD_DETAILS_ITEMS).task).toBe(true); + }); }); diff --git a/apps/web/src/components/chat/threadDetailsItems.ts b/apps/web/src/components/chat/threadDetailsItems.ts index 9f8f05449c550..d1f0c3cd3c500 100644 --- a/apps/web/src/components/chat/threadDetailsItems.ts +++ b/apps/web/src/components/chat/threadDetailsItems.ts @@ -3,6 +3,12 @@ import { msg } from "gt-react"; // Ids are stored in client settings, so never rename one. export const THREAD_DETAILS_ITEMS = [ + // Shown only where a board task's view hosts the thread; any other thread has nothing for it. + { + id: "task", + label: msg("Task", { $context: "thread details item: the board task a thread belongs to" }), + defaultVisible: true, + }, { id: "environment", label: msg("Environment and worktree"), defaultVisible: true }, { id: "openIn", label: msg("Open in editor"), defaultVisible: true }, { id: "scripts", label: msg("Project scripts"), defaultVisible: true }, diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts index 2a8e2e9db26c5..b340216b8e82d 100644 --- a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts @@ -1,7 +1,11 @@ import { ProjectId, ThreadId } from "@t3tools/contracts"; import { expect, it } from "vite-plus/test"; -import { archivedThreadsOfBoard, archivedThreadTaskNote } from "./ArchivedBoardThreads.logic"; +import { + archivedThreadsOfBoard, + archivedThreadTarget, + archivedThreadTaskNote, +} from "./ArchivedBoardThreads.logic"; const thread = (board: string, taskId: string, archivedAt: string) => ({ threadId: ThreadId.make(`thread-${taskId}`), @@ -39,3 +43,20 @@ it("offers a restore only for a task that can take the thread back, and says why ); expect(archivedThreadTaskNote({ ...row, task: "held" })).toBe("The task is held elsewhere."); }); + +it("opens a restorable task's conversation in the task's view, and a deleted task's on its own", () => { + const row = thread("work", "task-a", "2026-11-20T10:00:00.000Z"); + // The task comes from what the server serves for the row, never from the thread itself. + expect(archivedThreadTarget(row)).toEqual({ kind: "task", taskId: "task-a" }); + expect(archivedThreadTarget({ ...row, task: "deleted" })).toEqual({ + kind: "thread", + threadId: row.threadId, + }); + // A task held elsewhere or not checked cannot take the thread back, so neither has a view here. + for (const task of ["held", "unknown"] as const) { + expect(archivedThreadTarget({ ...row, task })).toEqual({ + kind: "thread", + threadId: row.threadId, + }); + } +}); diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts index 97bb55c17389d..49d050d4b9f9b 100644 --- a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts @@ -15,6 +15,16 @@ export function archivedThreadsOfBoard( .toSorted((a, b) => b.archivedAt.localeCompare(a.archivedAt)); } +/** + * Where a row opens. A task that can take its conversation back has a view on the board, where + * the conversation opens with it; a row whose task cannot has no task view, so it opens alone. + */ +export function archivedThreadTarget(thread: ArchivedBoardThread) { + return thread.task === "open" + ? ({ kind: "task", taskId: thread.taskId } as const) + : ({ kind: "thread", threadId: thread.threadId } as const); +} + /** * What the archive says under a thread whose task cannot take it back, or null for one that can * and is offered a restore. A restored thread of any other task holds nothing and is archived diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.tsx b/apps/web/src/components/delivery/ArchivedBoardThreads.tsx index 1f19afd36d8f7..95d9bb77e4195 100644 --- a/apps/web/src/components/delivery/ArchivedBoardThreads.tsx +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.tsx @@ -14,6 +14,7 @@ import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popov import { toastManager } from "../ui/toast"; import { archivedThreadsOfBoard, + archivedThreadTarget, archivedThreadTaskNote, type ArchivedBoardThread, } from "./ArchivedBoardThreads.logic"; @@ -111,15 +112,22 @@ export function ArchivedBoardThreads(props: { diff --git a/apps/web/src/components/delivery/BoardSidebarPanel.logic.test.ts b/apps/web/src/components/delivery/BoardSidebarPanel.logic.test.ts new file mode 100644 index 0000000000000..1ff5bc39eda72 --- /dev/null +++ b/apps/web/src/components/delivery/BoardSidebarPanel.logic.test.ts @@ -0,0 +1,77 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { parseCard, type TaskBrief } from "../../lib/delivery"; +import { NO_FILTERS } from "../../lib/deliveryBoard"; +import { panelCards, switcherGroups, type SwitcherRow } from "./BoardSidebarPanel.logic"; + +const card = (id: string, number: number, extra: Record = {}) => + parseCard({ id, number, title: `Task ${number}`, lane: "ready", state: "ready", ...extra }); +const brief = (id: string, number: number): TaskBrief => ({ + id, + number, + title: `Task ${number}`, + state: "ready", + lane: "ready", +}); +const seatThread = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("seat") }; +const seat = { seat: "builder", activity: "active", thread: seatThread }; + +/** A row as its id and depth, the open task marked: what the column draws, in order. */ +const shape = (rows: ReadonlyArray) => + rows.map((row) => + row.kind === "seat" + ? `seat:${row.seat}@${row.depth}` + : `${row.brief.id}@${row.depth}${row.current ? "*" : ""}`, + ); + +describe("the board's column", () => { + it("lists by the board's filters on the board, and by its own search alone while a task is open", () => { + const cards = [card("a", 1, { tags: ["sync"] }), card("b", 2, { priority: "high" })]; + const filters = { ...NO_FILTERS, tags: ["sync"], lanes: ["queue"], priority: "low" as const }; + expect(panelCards(cards, filters, false)).toEqual([]); + expect(panelCards(cards, filters, true)).toEqual(cards); + }); + + it("nests the open task's current children and seat conversations under its row, each task once", () => { + const cards = [card("t1", 1), card("t2", 2), card("t3", 3)]; + const rows = switcherGroups(cards, { + open: cards[0]!, + parent: null, + children: [brief("t2", 2)], + seats: [seat], + }); + expect(shape(rows.open)).toEqual(["t1@0*", "t2@1", "seat:builder@1", "t3@0"]); + }); + + it("puts the parent's row above the open task, nested under it, and the task's own family one deeper", () => { + const cards = [card("t1", 1), card("t2", 2), card("t4", 4)]; + const rows = switcherGroups(cards, { + open: cards[1]!, + parent: brief("t1", 1), + children: [brief("t4", 4)], + seats: [seat], + }); + expect(shape(rows.open)).toEqual(["t1@0", "t2@1*", "t4@2", "seat:builder@2"]); + }); + + it("shows what the list did not read from the open task's own read, at the head of its group", () => { + // A part is off the board while its whole is on it, so the list may hold neither. + const waiting = { waitingOn: "person", waitsOnPerson: true }; + const open = card("t2", 2, waiting); + const rows = switcherGroups([card("t9", 9, waiting)], { + open, + parent: brief("t1", 1), + children: [{ ...brief("t3", 3), lane: "human-review" }], + seats: [], + }); + expect(shape(rows.waiting)).toEqual(["t1@0", "t2@1*", "t3@2", "t9@0"]); + // The open task waits by its own card; a task known only by its brief, by its lane. + expect(rows.waiting.map((row) => row.kind === "task" && row.waits)).toEqual([ + false, + true, + true, + true, + ]); + }); +}); diff --git a/apps/web/src/components/delivery/BoardSidebarPanel.logic.ts b/apps/web/src/components/delivery/BoardSidebarPanel.logic.ts new file mode 100644 index 0000000000000..85ba23c1f3f4c --- /dev/null +++ b/apps/web/src/components/delivery/BoardSidebarPanel.logic.ts @@ -0,0 +1,154 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; + +import { waitKindsOf } from "../../lib/boardLaneCards"; +import { BOARD_LANE, boardLaneOf } from "../../lib/boardLanes"; +import { seatsAtWork, type DeliveryCard, type TaskBrief } from "../../lib/delivery"; +import { matchesCard, type BoardFilters } from "../../lib/deliveryBoard"; + +/** The column's groups, in the order they show. */ +export const PANEL_GROUPS = ["waiting", "working", "chats", "drafts", "open", "done"] as const; +export type PanelGroup = (typeof PANEL_GROUPS)[number]; + +/** + * What the column lists. On the board, the board's filters narrow it. While a task is open the + * column is a switcher: its own search narrows it, and the board's filters neither show nor apply, + * so the board still has them when the person goes back. + */ +export function panelCards( + cards: ReadonlyArray, + filters: BoardFilters, + switching: boolean, +): ReadonlyArray { + return switching ? cards : cards.filter((card) => matchesCard(card, { ...filters, q: "" })); +} + +const groupOf = (card: DeliveryCard): PanelGroup => { + if (card.lane === "completed") return "done"; + if (card.lane === "draft") return "drafts"; + if (card.lane === "chat") return "chats"; + if (card.waitingOn === "person") return "waiting"; + // Being worked on: a seat is at work. A card whose seats are all held waits with the rest. + return seatsAtWork(card).length > 0 ? "working" : "open"; +}; + +/** The cards by group. Done keeps its last twenty. */ +export function panelGroups( + cards: ReadonlyArray, +): Readonly>> { + const groups: Record = { + waiting: [], + working: [], + chats: [], + drafts: [], + open: [], + done: [], + }; + for (const card of cards) groups[groupOf(card)].push(card); + return { ...groups, done: groups.done.slice(0, 20) }; +} + +/** The open task and what the switcher nests with it, all from the board's own read. */ +export interface SwitcherFamily { + readonly open: DeliveryCard; + readonly parent: TaskBrief | null; + /** Its current parts and QA follow-ups. */ + readonly children: ReadonlyArray; + /** The seats of its conversation that have one; a seat with none has no row. */ + readonly seats: ReadonlyArray<{ + readonly seat: string; + readonly activity: string; + readonly thread: ScopedThreadRef; + }>; +} + +export type SwitcherRow = + | { + readonly kind: "task"; + readonly brief: TaskBrief; + /** The board's card for the task, when it was read. */ + readonly card: DeliveryCard | null; + /** The needs-you dot. */ + readonly waits: boolean; + readonly depth: 0 | 1 | 2; + readonly current: boolean; + } + | { + readonly kind: "seat"; + readonly seat: string; + readonly activity: string; + readonly thread: ScopedThreadRef; + readonly depth: 1 | 2; + }; + +const briefOf = (card: DeliveryCard): TaskBrief => ({ + id: card.id, + number: card.number, + title: card.title, + state: card.state, + lane: card.lane, +}); + +/** + * A task's row. A task known only by its brief, such as a part, which is off the board while its + * whole is on it, waits on you when its lane is the board's one lane that does. + */ +export const taskRowOf = ( + brief: TaskBrief, + card: DeliveryCard | null, + depth: 0 | 1 | 2, + current: boolean, +): SwitcherRow => ({ + kind: "task", + brief, + card, + waits: card + ? waitKindsOf(card).length > 0 + : boardLaneOf(brief.lane ?? "") === BOARD_LANE.needsDecision, + depth, + current, +}); + +/** + * The switcher's rows by group, each task listed once. The open task's family sits in its + * root's group: under the root, its parent if it has one, then the open task, its current child + * tasks and its seat conversations, one level deeper each. A root the list did not read is shown + * from what the open task says of it, at the head of the open task's group. + */ +export function switcherGroups( + cards: ReadonlyArray, + family: SwitcherFamily | null, +): Readonly>> { + // The open task's own read has its card when the list does not, as for a part. + const byId = new Map([ + ...(family ? [[family.open.id, family.open] as const] : []), + ...cards.map((card) => [card.id, card] as const), + ]); + const taskRow = (brief: TaskBrief, depth: 0 | 1 | 2): SwitcherRow => + taskRowOf(brief, byId.get(brief.id) ?? null, depth, family?.open.id === brief.id); + const nested = new Set( + family ? [...(family.parent ? [family.open.id] : []), ...family.children.map((c) => c.id)] : [], + ); + const groups = panelGroups(cards.filter((card) => !nested.has(card.id))); + const rows = Object.fromEntries( + PANEL_GROUPS.map((group) => [group, groups[group].map((card) => taskRow(briefOf(card), 0))]), + ) as Record; + if (!family) return rows; + + const rootId = family.parent?.id ?? family.open.id; + const under: 1 | 2 = family.parent ? 2 : 1; + const familyRows: SwitcherRow[] = [ + ...(family.parent ? [taskRow(briefOf(family.open), 1)] : []), + ...family.children.map((child) => taskRow(child, under)), + ...family.seats.map((seat) => ({ kind: "seat" as const, ...seat, depth: under })), + ]; + for (const group of PANEL_GROUPS) { + const at = rows[group].findIndex((row) => row.kind === "task" && row.brief.id === rootId); + if (at >= 0) { + rows[group].splice(at + 1, 0, ...familyRows); + return rows; + } + } + const root = family.parent ?? briefOf(family.open); + rows[groupOf(family.open)].unshift(taskRow(root, 0), ...familyRows); + return rows; +} diff --git a/apps/web/src/components/delivery/BoardSidebarPanel.tsx b/apps/web/src/components/delivery/BoardSidebarPanel.tsx index 5abbbda495dcf..c3f313aab2656 100644 --- a/apps/web/src/components/delivery/BoardSidebarPanel.tsx +++ b/apps/web/src/components/delivery/BoardSidebarPanel.tsx @@ -1,22 +1,29 @@ import { useLocation, useNavigate, useSearch } from "@tanstack/react-router"; import type { EnvironmentId } from "@t3tools/contracts"; -import { ChevronRightIcon, PlusIcon, SearchIcon, UsersIcon, XIcon } from "lucide-react"; +import { useGT } from "gt-react"; +import { + ArrowLeftIcon, + ChevronRightIcon, + PlusIcon, + SearchIcon, + UsersIcon, + XIcon, +} from "lucide-react"; import { useMemo, useState, type ReactNode } from "react"; import { parseBoard, parseCards, + parseTask, TASK_PRIORITIES, type DeliveryCard, type TaskPriority, crewLine, - seatsAtWork, } from "../../lib/delivery"; import { activeFilters, hasFilters, LANE_TITLE, - matchesCard, PRIORITY_LABEL, queryValue, boardSetOf, @@ -41,10 +48,33 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ import { SidebarContent, SidebarGroup, useSidebar } from "../ui/sidebar"; import { APP_BUILD } from "../../branding"; import { ActiveFilterChips, LaneFilterMenu, TagFilterMenu } from "./BoardFilterControls"; +import { + PANEL_GROUPS, + panelCards, + panelGroups, + switcherGroups, + taskRowOf, + type PanelGroup, + type SwitcherFamily, + type SwitcherRow, +} from "./BoardSidebarPanel.logic"; +import { BoardSwitcherRows } from "./BoardSwitcher"; import { Age, CardSigns, laneTone, PriorityPill } from "./taskParts"; import { BoardIcon } from "./BoardIcon"; import { EnvironmentPicker } from "./EnvironmentPicker"; import { EngineDownNotice } from "./EnginePanel"; +import { relatedTaskGroups } from "./relatedTaskGroups"; +import { useTaskConversation } from "./useTaskConversation"; + +/** Each group's name, title and what it says when it is empty, in the order they show. */ +const GROUP_TITLES: Readonly> = { + waiting: "Waiting on you", + working: "Being worked on", + chats: "Team chats", + drafts: "Drafts", + open: "With the team", + done: "Done", +}; const ANY = "__any__"; @@ -168,6 +198,34 @@ function Section(props: { ); } +/** A group of the switcher: its tasks as rows, with the open task's family nested under its root. */ +function SwitcherSection(props: { + readonly environmentId: EnvironmentId | null; + readonly name: string; + readonly title: string; + readonly rows: ReadonlyArray; + readonly empty?: string; + readonly defaultFolded?: boolean; + readonly list: (rows: ReadonlyArray) => ReactNode; +}) { + if (props.rows.length === 0 && !props.empty) return null; + return ( + row.kind === "task").length} + {...(props.defaultFolded ? { defaultFolded: true } : {})} + > + {props.rows.length === 0 ? ( +

{props.empty}

+ ) : ( + props.list(props.rows) + )} +
+ ); +} + /** * The sidebar while the Board is open: tasks in place of * threads. A task is started, found and opened from here, and what waits for @@ -209,8 +267,20 @@ function EnvironmentBoardSidebar({ const { setFilters, clearFilters } = useBoardControls(environmentId); const boardSet = boardSetOf(preferences.boardSet); const now = useMinuteClock(); + const gt = useGT(); + // With a task open the column is a switcher: its search is its own, and the board's filters + // stay as they were for the board. + const openTaskId = location.pathname === "/board" ? (location.search.task ?? null) : null; + const switching = openTaskId !== null; + const [switcherQuery, setSwitcherQuery] = useState(""); + // The switcher's search lasts from task to task; the next time a task opens it starts empty. + const [wasSwitching, setWasSwitching] = useState(switching); + if (wasSwitching !== switching) { + setWasSwitching(switching); + if (!switching) setSwitcherQuery(""); + } - const q = filters.q.trim(); + const q = (switching ? switcherQuery : filters.q).trim(); // The engine looks in what is asked too, which a card does not carry. const read = useDeliveryRead( enabled && !shared ? environmentId : null, @@ -246,10 +316,29 @@ function EnvironmentBoardSidebar({ () => sidebarCandidates(taskCards, boardCards, q), [taskCards, boardCards, q], ); - const kept = useMemo( - () => cards.filter((card) => matchesCard(card, { ...filters, q: "" })), - [cards, filters], + const kept = panelCards(cards, filters, switching); + // The open task as the board reads it, for its family. The task view polls this same read. + const taskRead = useDeliveryRead( + enabled && openTaskId ? environmentId : null, + openTaskId ? `/api/tasks/${openTaskId}` : null, ); + const readTask = parseTask(taskRead.body); + const openTask = readTask?.id === openTaskId ? readTask : null; + const conversation = useTaskConversation(environmentId, openTask); + const family: SwitcherFamily | null = openTask + ? { + open: openTask.card, + parent: openTask.parent, + children: [ + ...relatedTaskGroups(openTask.card.parts).current, + ...relatedTaskGroups(openTask.followUps).current, + ], + seats: (openTask.council?.seats ?? []).flatMap((item) => { + const thread = conversation.seats.thread(item.seat); + return thread ? [{ seat: item.seat, activity: item.activity, thread }] : []; + }), + } + : null; const teams = useMemo(() => [...new Set(cards.map((card) => card.team))].sort(), [cards]); // From every card that was read, never from the ones a filter kept. const tags = useMemo( @@ -260,13 +349,14 @@ function EnvironmentBoardSidebar({ const close = () => { if (isMobile) setOpenMobile(false); }; - const open = (card: DeliveryCard) => { + const goToTask = (taskId: string) => { close(); void navigate({ to: "/board", - search: { task: card.id, ...(environmentId ? { environment: environmentId } : {}) }, + search: { task: taskId, ...(environmentId ? { environment: environmentId } : {}) }, }); }; + const open = (card: DeliveryCard) => goToTask(card.id); const chooseEnvironment = (environment: string) => { setDeliveryEnvironment(environment); void navigate({ to: "/board", search: { environment } }); @@ -278,16 +368,26 @@ function EnvironmentBoardSidebar({ ? "The engine did not answer." : "Reading the board..." : null; - const searching = hasFilters(filters); + const searching = switching ? q !== "" : hasFilters(filters); const filterCount = activeFilters(filters, laneTitle).filter((item) => item.key !== "q").length; - const live = kept.filter((card) => !["completed", "draft", "chat"].includes(card.lane)); - const chats = kept.filter((card) => card.lane === "chat"); - const waiting = live.filter((card) => card.waitingOn === "person"); - // Being worked on: a seat is at work. A card whose seats are all held waits with the rest. - const working = live.filter( - (card) => card.waitingOn !== "person" && seatsAtWork(card).length > 0, + const groups = panelGroups(kept); + const switcherRows = switching && !searching ? switcherGroups(kept, family) : null; + const found = kept.map((card) => taskRowOf(card, card, 0, card.id === openTaskId)); + const backToBoard = () => { + close(); + void navigate({ to: "/board", search: environmentId ? { environment: environmentId } : {} }); + }; + const switcherList = (rows: ReadonlyArray) => ( + { + close(); + conversation.seats.open(thread); + }} + /> ); - const rest = live.filter((card) => card.waitingOn !== "person" && seatsAtWork(card).length === 0); if (shared) return ( @@ -305,6 +405,14 @@ function EnvironmentBoardSidebar({
+ {switching ? ( +
+ +
+ ) : null}
+ {switching ? null : ( + + )} - - setFilters({ lanes: chosen })} - /> - - {teams.length > 1 ? ( - - ) : null} - {tags.length > 0 ? ( - setFilters({ tags: chosen })} - /> - ) : null} -
- - {/* What is on is shown whether the filters are folded or not. */} - setFilters(patch)} - onReset={clearFilters} - /> + Waiting on you + + setFilters({ lanes: chosen })} + /> + + {teams.length > 1 ? ( + + ) : null} + {tags.length > 0 ? ( + setFilters({ tags: chosen })} + /> + ) : null} +
+ + {/* What is on is shown whether the filters are folded or not. */} + setFilters(patch)} + onReset={clearFilters} + /> + + )}
@@ -510,6 +627,30 @@ function EnvironmentBoardSidebar({ environmentId={environmentId} message={`Delivery engine not reachable. ${read.error}`} /> + ) : switching ? ( + searching ? ( + + ) : ( + PANEL_GROUPS.map((group) => ( + + )) + ) ) : searching ? (
card.lane === "draft")} + cards={groups.drafts} now={now} selected={selected} onOpen={open} @@ -564,7 +705,7 @@ function EnvironmentBoardSidebar({ environmentId={environmentId} name="open" title="With the team" - cards={rest} + cards={groups.open} now={now} selected={selected} onOpen={open} @@ -573,7 +714,7 @@ function EnvironmentBoardSidebar({ environmentId={environmentId} name="done" title="Done" - cards={kept.filter((card) => card.lane === "completed").slice(0, 20)} + cards={groups.done} now={now} selected={selected} onOpen={open} diff --git a/apps/web/src/components/delivery/BoardSwitcher.browser.test.tsx b/apps/web/src/components/delivery/BoardSwitcher.browser.test.tsx new file mode 100644 index 0000000000000..eaabe6f8aa84b --- /dev/null +++ b/apps/web/src/components/delivery/BoardSwitcher.browser.test.tsx @@ -0,0 +1,62 @@ +import "~/index.css"; + +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { parseCard } from "../../lib/delivery"; +import { switcherGroups } from "./BoardSidebarPanel.logic"; +import { BoardSwitcherRows } from "./BoardSwitcher"; + +const card = (id: string, number: number, title: string) => + parseCard({ id, number, title, lane: "ready", state: "ready" }); +const seatThread = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("seat") }; + +it("draws the board's tasks on the row shell: the open task as the page, its family nested under its parent", async () => { + const onOpenTask = vi.fn(); + const onOpenSeat = vi.fn(); + const parent = card("t1", 1, "Rework the sync"); + const open = card("t2", 2, "Fix the cursor"); + const rows = switcherGroups([parent, open, card("t3", 3, "Another task")], { + open, + parent: { id: "t1", number: 1, title: "Rework the sync", state: "ready", lane: "ready" }, + children: [], + seats: [{ seat: "builder", activity: "active", thread: seatThread }], + }).open; + await using screen = await render( +
+ +
, + ); + const current = screen.getByRole("button", { name: /Fix the cursor/ }); + await expect.element(current).toHaveAttribute("aria-current", "page"); + await expect + .element(screen.getByRole("button", { name: /Rework the sync/ })) + .not.toHaveAttribute("aria-current"); + // Each level sits further in than the one it is nested under. + const start = (name: RegExp) => + Number.parseFloat(getComputedStyle(screen.getByRole("button", { name }).element()).paddingLeft); + expect(start(/Fix the cursor/)).toBeGreaterThan(start(/Rework the sync/)); + expect(start(/Seat builder/)).toBeGreaterThan(start(/Fix the cursor/)); + expect(start(/Another task/)).toBe(start(/Rework the sync/)); + + await screen.getByRole("button", { name: /Rework the sync/ }).click(); + expect(onOpenTask).toHaveBeenCalledWith("t1"); + // A seat opens its conversation in the centre; the open task stays the page. + await screen.getByRole("button", { name: /Seat builder/ }).click(); + expect(onOpenSeat).toHaveBeenCalledWith(seatThread); + await expect.element(current).toHaveAttribute("aria-current", "page"); + // Reachable by keyboard, as a thread row is. + screen + .getByRole("button", { name: /Another task/ }) + .element() + .focus(); + await userEvent.keyboard("{Enter}"); + expect(onOpenTask).toHaveBeenLastCalledWith("t3"); +}); diff --git a/apps/web/src/components/delivery/BoardSwitcher.tsx b/apps/web/src/components/delivery/BoardSwitcher.tsx new file mode 100644 index 0000000000000..8e3e40b946766 --- /dev/null +++ b/apps/web/src/components/delivery/BoardSwitcher.tsx @@ -0,0 +1,118 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { useGT, useMessages } from "gt-react"; +import { CornerDownRightIcon } from "lucide-react"; +import type { KeyboardEvent } from "react"; + +import { BOARD_LANE, boardLaneOf, boardLaneTitle } from "../../lib/boardLanes"; +import { WORK_STAGE_TITLE, workStageOf } from "../../lib/boardLaneCards"; +import { LANE_TITLE } from "../../lib/deliveryBoard"; +import { sameThread } from "../../lib/taskConversation"; +import { SidebarRowShell } from "../sidebar/SidebarThreadRow"; +import type { SwitcherRow } from "./BoardSidebarPanel.logic"; + +// A row is a button the way a thread row is: Enter or Space opens it, as a click does. +const pressed = (open: () => void) => (event: KeyboardEvent) => { + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + open(); +}; + +function TaskRow(props: { + readonly row: Extract; + readonly onOpen: (taskId: string) => void; +}) { + const m = useMessages(); + const { brief, card } = props.row; + const lane = boardLaneOf(brief.lane ?? ""); + const stage = + lane === BOARD_LANE.inWork && card + ? `${boardLaneTitle(lane, m, LANE_TITLE[lane] ?? brief.state)}, ${m(WORK_STAGE_TITLE[workStageOf(card)])}` + : boardLaneTitle(lane, m, LANE_TITLE[lane] ?? brief.state); + const open = () => props.onOpen(brief.id); + return ( +
  • + + + #{brief.number} + + {brief.title} + + {stage} + + +
  • + ); +} + +function SeatRow(props: { + readonly row: Extract; + readonly open: boolean; + readonly onOpen: (thread: ScopedThreadRef) => void; +}) { + const gt = useGT(); + const open = () => props.onOpen(props.row.thread); + return ( +
  • + + + + {gt("Seat {seat}", { seat: props.row.seat })} + + + {props.row.activity} + + +
  • + ); +} + +/** + * The board's tasks as rows on the thread row's shell, while a task is open: the open one is the + * page, and its family is nested under its root. A task row opens its task; a seat row opens its + * conversation in the centre, and the task stays the page. + */ +export function BoardSwitcherRows(props: { + readonly rows: ReadonlyArray; + readonly openSeat: ScopedThreadRef | null; + readonly onOpenTask: (taskId: string) => void; + readonly onOpenSeat: (thread: ScopedThreadRef) => void; +}) { + return ( +
      + {props.rows.map((row) => + row.kind === "task" ? ( + + ) : ( + + ), + )} +
    + ); +} diff --git a/apps/web/src/components/delivery/BoardTaskContext.ts b/apps/web/src/components/delivery/BoardTaskContext.ts new file mode 100644 index 0000000000000..41daba025e867 --- /dev/null +++ b/apps/web/src/components/delivery/BoardTaskContext.ts @@ -0,0 +1,31 @@ +import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; +import { createContext, useContext } from "react"; + +import type { TaskView } from "../../lib/delivery"; +import type { SeatConversations } from "./TaskTeamActivity"; + +/** The board task a view belongs to: its id and the board's own read of it. */ +export interface BoardTask { + readonly environmentId: EnvironmentId | null; + readonly taskId: string; + /** Null while the first read is out, or when there is no such task. */ + readonly task: TaskView | null; + /** What is shown is the last reading, not a live one: it is old, or the engine did not answer. */ + readonly stale: boolean; + /** Reads the task again, after something here changed it. */ + readonly refresh: () => void; + /** Opens another board task in place of this one. */ + readonly openTask: (taskId: string) => void; + /** Opens a conversation in the centre, the way a seat's opens. */ + readonly openThread: (thread: ScopedThreadRef) => void; + /** The seats' own conversations, which the team's rows open. */ + readonly seats: SeatConversations; +} + +/** + * Provided where the board's task view mounts, so what it hosts reads the task from here and never + * from the thread on screen, which is a seat's while one is open in the centre. + */ +export const BoardTaskContext = createContext(null); + +export const useBoardTask = () => useContext(BoardTaskContext); diff --git a/apps/web/src/components/delivery/DecisionBar.tsx b/apps/web/src/components/delivery/DecisionBar.tsx new file mode 100644 index 0000000000000..0c207a5667ce1 --- /dev/null +++ b/apps/web/src/components/delivery/DecisionBar.tsx @@ -0,0 +1,69 @@ +import type { TaskView } from "../../lib/delivery"; +import { Button } from "../ui/button"; +import { actionHelp, actionLabel } from "./taskActions"; +import { MobileHelp } from "./taskParts"; + +/** + * The decisions a person makes on the task: approve what was tested, send it back with a + * reason, start or submit it. A lane of its own above the composer, so that what is written + * is never taken for a decision and the buttons are in reach on a phone. + */ +export function DecisionBar(props: { + readonly task: TaskView; + readonly actions: ReadonlyArray; + readonly busy: boolean; + readonly onAction: (action: string) => void; +}) { + if (props.actions.length === 0) return null; + const deciding = props.actions.some((action) => action === "approve" || action === "reject"); + return ( +
    +
    +

    + {deciding ? "Your decision" : "What you can do next"} + {deciding ? ( + + {" "} + Messages never count as a decision. + + ) : null} +

    +
    + {props.actions.map((action) => ( +
    + + + {actionHelp(action, props.task.card)} + +
    + ))} + + {deciding ?

    Messages never count as a decision.

    : null} + {props.actions.map((item) => ( +

    + {actionLabel(item, props.task.card)}: + {actionHelp(item, props.task.card)} +

    + ))} +
    +
    +
    +
    + ); +} diff --git a/apps/web/src/components/delivery/MergePermissionControls.tsx b/apps/web/src/components/delivery/MergePermissionControls.tsx index e339f1ea7a9ba..9ac18e97c096d 100644 --- a/apps/web/src/components/delivery/MergePermissionControls.tsx +++ b/apps/web/src/components/delivery/MergePermissionControls.tsx @@ -53,6 +53,8 @@ export function MergePermissionControls(props: { onDone: () => void; readOnly?: boolean; stale?: boolean; + /** Where the section around the controls already carries their title. */ + untitled?: boolean; }) { const allowed = useAtomValue(deliveryEnvironment.act.permissionAtom(props.environmentId)); const [setting, setSetting] = useState<"on" | "off" | "inherit" | null>(null); @@ -60,7 +62,7 @@ export function MergePermissionControls(props: { const selected = setting ?? props.policy?.setting ?? "inherit"; return (
    -

    Automatic merge permission

    + {props.untitled ? null :

    Automatic merge permission

    }

    Permission alone never merges. Full-auto mode and the engine's independent merge checks diff --git a/apps/web/src/components/delivery/RunPanel.tsx b/apps/web/src/components/delivery/RunPanel.tsx new file mode 100644 index 0000000000000..cc7875e1b66f9 --- /dev/null +++ b/apps/web/src/components/delivery/RunPanel.tsx @@ -0,0 +1,217 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { useState } from "react"; + +import { repeatKeys, type TaskView } from "../../lib/delivery"; +import { harnessLabel } from "../../lib/deliverySeats"; +import { useDeliveryAct, useDeliveryRead, usePersonName } from "../../state/delivery"; +import ChatMarkdown from "../ChatMarkdown"; +import { Dialog, DialogHeader, DialogPanel, DialogPopup, DialogTitle } from "../ui/dialog"; +import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Textarea } from "../ui/textarea"; + +const DOCUMENT_LABEL: Record = { + "PLAN.md": "Plan", + "REVIEW.md": "Review", + "PACK.md": "Evidence pack", +}; + +/** + * The run under way, for a person following it: the documents it wrote, to read here or have + * summarised, the instructions given to it, and a way to give one. An instruction reaches the + * seat at work it is for, which starts its step again with it; what is asked is changed by a + * change, which goes through triage, not here. + */ +export function RunPanel(props: { + readonly environmentId: EnvironmentId | null; + readonly task: TaskView; + readonly onChanged: () => void; +}) { + const { task } = props; + const council = task.council; + const person = usePersonName(); + const act = useDeliveryAct(props.environmentId, "run"); + const [reading, setReading] = useState(null); + const [text, setText] = useState(""); + const [seat, setSeat] = useState(""); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState(null); + if (!council) return null; + const steerable = ["running", "paused", "needs-decision"].includes(council.state); + const steerKeys = repeatKeys(council.steers.map((steer) => `${steer.at}:${steer.text}`)); + const give = async () => { + if (!text.trim() || busy) return; + setBusy(true); + const result = await act(`/api/tasks/${task.id}/steer`, { + text: text.trim(), + seat: seat || null, + by: person, + }); + setBusy(false); + if (result.ok) { + setText(""); + setSaid( + "Given. It is in the history; the step starts again with it once its seats have stopped.", + ); + } else setSaid(result.why); + props.onChanged(); + }; + const summarise = async (name: string) => { + setBusy(true); + const result = await act(`/api/tasks/${task.id}/messages`, { + kind: "message", + text: `Summarise the ${DOCUMENT_LABEL[name] ?? name} (${name}) of run ${council.run} for me in a few lines: what it says will be done, how it will be checked, and anything I should look at.`, + by: person, + }); + setBusy(false); + setSaid(result.ok ? "Asked the coordinator. The answer comes in the history." : result.why); + props.onChanged(); + }; + return ( +

    +

    Run {council.run}

    + {council.documents.length > 0 ? ( +
    + {council.documents.map((name) => ( +
    + + +
    + ))} +
    + ) : ( +

    + No plan, review or evidence written yet. Each shows here once the run writes it. +

    + )} + {council.steers.length > 0 ? ( +
      + {council.steers.map((steer, index) => ( +
    • + + {steer.by} to {steer.seat ?? "every seat"}:{" "} + + {steer.text} +
    • + ))} +
    + ) : null} + {steerable ? ( +
    + +