diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 489fcc721..997cb26a1 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -107,7 +107,17 @@ A project's lead chat is a thread set up to coordinate the project; see the lead { id: "lead-chat", title: "Lead chat", - keywords: ["lead chat", "lead", "coordinator", "project lead", "orchestrator", "drop work"], + keywords: [ + "lead chat", + "lead", + "coordinator", + "project lead", + "orchestrator", + "drop work", + "threads panel", + "project threads", + "board", + ], body: `Each project can have one lead chat: a thread you drop work into (a bug, a stack trace, a list of tasks). Its agent answers small questions itself and starts threads for new work. Those threads show under the lead in the sidebar and report back to it, and it tells you what finished and what needs you. Any thread can be the lead. Use "Make this the lead chat" in a thread's menu (right-click its row, or click the title above the chat), or the command palette. The project's menu in the project picker has Open lead chat, or New lead chat, which starts a thread in the project folder and makes it the lead. "Go to lead chat" in the command palette opens it. @@ -120,6 +130,8 @@ Only one thread leads a project; making another the lead replaces it. "Stop usin The lead's row sits at the top of the sidebar with a flag, says Lead where the project name goes, and never wraps up on its own. The chat shows a Lead chat label beside the title. +The Threads tab in the right sidebar shows the project's threads on every computer you can see, grouped as Needs you, Ready for review, Working, Landing, Idle and Done. Open it from the sidebar's list of panels or its + menu, on any thread of the project; it opens by itself the first time a thread becomes the lead on this device. A thread you wrapped up goes under Done (for 7 days, closed until you open it) unless its pull request is still open, which keeps it under Ready for review or Landing. Ready for review says what the pull request waits on, as the Pull requests page does. Click a row to open the thread, or right-click it for the thread's menu. The top line counts what needs you and what's working, with a Lead chat link when you're on another thread. + The lead's agent is told its role at the start of every turn. It may start 10 threads and send 20 messages to them per message you send, instead of 5 and 10. It needs {place:threads.agentThreads} to be on, and an agent that can't use the thread tools says so. General chats, a thread another thread still owns, and threads from another computer or an outside agent can't be the lead.`, }, { diff --git a/apps/web/src/components/ChatView.panels.browser.tsx b/apps/web/src/components/ChatView.panels.browser.tsx index 1ad441667..e259162c8 100644 --- a/apps/web/src/components/ChatView.panels.browser.tsx +++ b/apps/web/src/components/ChatView.panels.browser.tsx @@ -40,6 +40,9 @@ import { waitForLayout, waitForElement, waitForServerConfigToApply, + addThreadToSnapshot, + markThreadDoneInTest, + setSidebarThreadWork, mountChatView, openProjectMenu, registerChatViewSuiteHooks, @@ -207,6 +210,101 @@ describe("ChatView (full app): right panel and header actions", () => { tile.click(); } + it("groups the project's threads in the Threads tab and opens one from its row", async () => { + const approvalId = "thread-board-approval" as ThreadId; + const workingId = "thread-board-working" as ThreadId; + const wrappedId = "thread-board-wrapped" as ThreadId; + const titles: Record = { + [approvalId]: "Needs an approval", + [workingId]: "Busy fixing", + [wrappedId]: "Finished last night", + }; + const base = createSnapshotForTargetUser({ + targetMessageId: "msg-user-board" as MessageId, + targetText: "board", + }); + const snapshot = [approvalId, workingId, wrappedId].reduce( + (current, threadId) => addThreadToSnapshot(current, threadId), + base, + ); + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: { + ...snapshot, + threads: snapshot.threads.map((thread) => + titles[thread.id] ? { ...thread, title: titles[thread.id]! } : thread, + ), + }, + }); + + try { + setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, approvalId, "needs-you"); + setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, workingId, "working"); + markThreadDoneInTest(`${LOCAL_ENVIRONMENT_ID}:${wrappedId}`, NOW_ISO); + + const railToggle = await waitForElement( + () => + document.querySelector('button[aria-label="Toggle panel"]') as HTMLButtonElement | null, + "Unable to find the rail toggle.", + ); + railToggle.click(); + await openRightPanelSurfaceFromLauncher("threads"); + + const rowsIn = (group: string) => + [ + ...document.querySelectorAll( + `[data-project-board-group='${group}'] [data-testid^='project-board-row-']`, + ), + ].map((row) => row.getAttribute("data-testid")!.replace("project-board-row-", "")); + await vi.waitFor( + () => { + expect(mounted.router.state.location.search).toMatchObject({ threads: "1" }); + expect( + [...document.querySelectorAll("[data-project-board-group]")].map((group) => + group.getAttribute("data-project-board-group"), + ), + ).toEqual(["needsYou", "working", "idle", "done"]); + expect(rowsIn("needsYou")).toEqual([approvalId]); + expect(rowsIn("working")).toEqual([workingId]); + expect(rowsIn("idle")).toEqual([THREAD_ID]); + // Done starts closed, like the sidebar's Wrapped shelf. + expect(rowsIn("done")).toEqual([]); + expect(document.querySelector("[data-testid='project-board-counts']")?.textContent).toBe( + "1 needs you · 1 working", + ); + }, + { timeout: 8_000, interval: 16 }, + ); + + (document.querySelector("[data-testid='project-board-toggle-done']") as HTMLElement).click(); + await vi.waitFor(() => expect(rowsIn("done")).toEqual([wrappedId]), { + timeout: 8_000, + interval: 16, + }); + + ( + document.querySelector(`[data-testid='project-board-row-${approvalId}']`) as HTMLElement + ).click(); + await vi.waitFor( + () => { + expect(mounted.router.state.location.pathname).toBe( + `/${LOCAL_ENVIRONMENT_ID}/${approvalId}`, + ); + // The board comes along, so the next row is one click away. + expect(mounted.router.state.location.search).toMatchObject({ threads: "1" }); + expect( + document + .querySelector(`[data-testid='project-board-row-${approvalId}']`) + ?.getAttribute("data-active"), + ).toBe("true"); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("builds a tab strip from the launcher and switches between its tabs", async () => { const mounted = await mountChatView({ viewport: WIDE_FOOTER_VIEWPORT, diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index f622a6636..582be3c2a 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -312,6 +312,55 @@ describe("ChatView (full app): sidebar", () => { } }); + it("opens the Threads tab the first time a thread becomes the lead on this device, as the sheet on a narrow window", async () => { + const capabilities = { repositoryIdentity: true, projectLead: true }; + const mounted = await mountChatView({ + // Below the inline panel's breakpoint, so the panel is the sheet. + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-first-lead" as MessageId, + targetText: "first lead", + }), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + environment: { ...nextFixture.serverConfig.environment, capabilities }, + }; + nextFixture.welcome = { + ...nextFixture.welcome, + environment: { ...nextFixture.welcome.environment, capabilities }, + }; + }, + }); + + try { + const row = await waitForElement( + () => document.querySelector(`[data-testid="thread-row-${THREAD_ID}"]`), + "The thread's sidebar row should be on screen.", + ); + const rect = row.getBoundingClientRect(); + row.dispatchEvent( + new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: rect.left + 20, + clientY: rect.top + 8, + }), + ); + await page.getByRole("button", { name: "Make this the lead chat", exact: true }).click(); + + await vi.waitFor( + () => { + expect(mounted.router.state.location.search).toMatchObject({ threads: "1" }); + expect(document.querySelector("[data-project-board='true']")).not.toBeNull(); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("narrows the live list to rooms from the View button and marks it while it does", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 10d8a8db9..c7381263b 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -45,6 +45,7 @@ import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; import { preserveRightPanelSearchParamsForDraftNavigation } from "../diffRouteSearch"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { type InboxEntry, useInboxThreads } from "../hooks/useInboxThreads"; +import { useOpenThreadPullRequest } from "../hooks/useOpenThreadPullRequest"; import { useThreadMenu } from "../hooks/useThreadMenu"; import { useTouchHoldMenu } from "../hooks/useTouchHoldMenu"; import { useIsMobile } from "../hooks/useMediaQuery"; @@ -1619,48 +1620,7 @@ export default function Sidebar() { ], ); - /** - * The pull request badge. A plain click opens the thread's Pull request tab, - * which is where the app can actually show it; a modifier or the middle - * button is the browser's "open it somewhere else" gesture, and the host is - * that somewhere else. - */ - const openPrLink = useCallback( - ( - event: React.MouseEvent, - pullRequest: Pick, - threadRef: ScopedThreadRef, - ) => { - event.preventDefault(); - event.stopPropagation(); - - if (!(event.metaKey || event.ctrlKey || event.button === 1)) { - closeSheet(); - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - search: { pullRequest: "1", pullRequestNumber: pullRequest.number }, - }); - return; - } - - const api = readLocalApi(); - if (!api) { - toastManager.add({ type: "error", title: "Can't open links here" }); - return; - } - - void api.shell.openExternal(pullRequest.url).catch((error) => { - toastManager.add( - failureNotice({ - title: "Couldn't open the pull request", - error, - }), - ); - }); - }, - [closeSheet, navigate], - ); + const openPrLink = useOpenThreadPullRequest(closeSheet); const attemptArchiveThread = useCallback( async (threadRef: ScopedThreadRef) => { diff --git a/apps/web/src/components/chat/ProjectBoardPanel.tsx b/apps/web/src/components/chat/ProjectBoardPanel.tsx new file mode 100644 index 000000000..7d8807077 --- /dev/null +++ b/apps/web/src/components/chat/ProjectBoardPanel.tsx @@ -0,0 +1,400 @@ +/** + * The Threads tab: a project's threads on every computer in view, grouped by + * what needs the user (docs/design/lead-chat.md, "Threads panel"). The + * grouping is projectBoard.logic's; the filing, statuses and pull requests are + * the sidebar's own (useInboxThreads), so a thread reads the same here as in + * its sidebar row. + */ +import { scopedThreadKey, scopeProjectRef, scopeThreadRef } from "@threadlines/client-runtime"; +import type { EnvironmentId, ProjectId, ScopedThreadRef, ThreadId } from "@threadlines/contracts"; +import { CheckIcon, ChevronDownIcon, FlagIcon } from "lucide-react"; +import React, { memo, useCallback, useMemo, useState } from "react"; + +import { type InboxEntry, useInboxThreads } from "../../hooks/useInboxThreads"; +import { useOpenThreadPullRequest } from "../../hooks/useOpenThreadPullRequest"; +import { useThreadMenu } from "../../hooks/useThreadMenu"; +import { useTouchHoldMenu } from "../../hooks/useTouchHoldMenu"; +import { projectLeadRef } from "../../leadChat"; +import { cn } from "../../lib/utils"; +import { selectProjectByRef, useStore } from "../../store"; +import { + findThreadOpenPullRequestEntry, + resolveNeedsYouReason, + type ThreadPullRequest, +} from "../pull-requests/pullRequests.logic"; +import { RelativeTimeLabel } from "../RelativeTimeLabel"; +import { + ThreadEnvironmentBadge, + ThreadProviderGlyph, + ThreadPullRequestBadge, + ThreadStatusText, + threadPullRequestList, +} from "../sidebar/InboxRows"; +import { + deriveProjectBoard, + foldProjectBoardGroup, + formatProjectBoardCounts, + type ProjectBoardGroup, + type ProjectBoardGroupId, + type ProjectBoardRow, + type ProjectBoardThreadInput, +} from "./projectBoard.logic"; + +interface BoardThread extends ProjectBoardThreadInput { + readonly entry: InboxEntry; + /** Every pull request it has, for the row's badge. */ + readonly threadPullRequests: readonly ThreadPullRequest[]; +} + +const NO_PULL_REQUESTS: readonly ThreadPullRequest[] = []; + +/** The board's threads: the project's inbox entries, with what their pull requests wait on. */ +function useProjectBoard(environmentId: EnvironmentId, projectId: ProjectId) { + const inbox = useInboxThreads(); + const { + entries, + linkedPullRequestsByThreadKey, + nowIso, + openPullRequests, + projects, + pullRequestByThreadKey, + resolveProjectKeyForRef, + } = inbox; + return useMemo(() => { + // The logical project, so copies of it on other computers are on the board too. + const projectKey = resolveProjectKeyForRef(scopeProjectRef(environmentId, projectId)); + const threads = entries.flatMap((entry): BoardThread[] => { + if (entry.projectKey !== projectKey) return []; + const { thread } = entry; + const pullRequests = threadPullRequestList( + pullRequestByThreadKey.get(entry.threadKey) ?? null, + linkedPullRequestsByThreadKey.get(entry.threadKey) ?? NO_PULL_REQUESTS, + ); + return [ + { + key: entry.threadKey, + entry, + threadPullRequests: pullRequests, + statusLabel: entry.status?.label ?? null, + isDone: entry.isDone, + doneAt: entry.doneAt, + activityAt: thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt, + pullRequests: pullRequests.map((pullRequest) => { + // Review and checks live on the open listing's row, not the thread's reading. + const listed = + pullRequest.state === "open" + ? findThreadOpenPullRequestEntry({ + thread, + number: pullRequest.number, + projects, + openEntries: openPullRequests.entries, + }) + : undefined; + return { + state: pullRequest.state, + isDraft: pullRequest.isDraft, + autoMergeEnabled: pullRequest.autoMergeEnabled, + reviewReason: listed === undefined ? null : resolveNeedsYouReason(listed), + }; + }), + }, + ]; + }); + return deriveProjectBoard(threads, Date.parse(nowIso)); + }, [ + entries, + environmentId, + linkedPullRequestsByThreadKey, + nowIso, + openPullRequests.entries, + projectId, + projects, + pullRequestByThreadKey, + resolveProjectKeyForRef, + ]); +} + +export const ProjectBoardPanel = memo(function ProjectBoardPanel({ + environmentId, + threadId, + projectId, + onOpenThread, +}: { + environmentId: EnvironmentId; + /** The thread open in the chat beside the panel. */ + threadId: ThreadId; + projectId: ProjectId; + onOpenThread: (threadRef: ScopedThreadRef) => void; +}) { + const { groups, counts } = useProjectBoard(environmentId, projectId); + const leadThreadId = useStore((state) => { + const project = selectProjectByRef(state, scopeProjectRef(environmentId, projectId)); + return project === undefined ? null : (projectLeadRef(state, project)?.threadId ?? null); + }); + const activeThreadKey = scopedThreadKey(scopeThreadRef(environmentId, threadId)); + const [doneOpen, setDoneOpen] = useState(false); + const [expandedGroups, setExpandedGroups] = useState>( + () => new Set(), + ); + const threadMenu = useThreadMenu(); + const openPrLink = useOpenThreadPullRequest(); + const openRowMenu = useCallback( + (entry: InboxEntry, position: { readonly x: number; readonly y: number }) => { + void threadMenu.open( + { + threadRef: scopeThreadRef(entry.thread.environmentId, entry.thread.id), + inbox: { isDone: entry.isDone, canMarkDone: entry.canMarkDone }, + }, + position, + ); + }, + [threadMenu], + ); + + return ( +
+
+ + {formatProjectBoardCounts(counts)} + + {leadThreadId !== null && leadThreadId !== threadId ? ( + + ) : null} +
+
+ {groups.length === 0 ? ( +

+ No threads in this project yet. +

+ ) : ( + groups.map((group) => ( + setDoneOpen((open) => !open) : null} + onExpand={() => setExpandedGroups((previous) => new Set(previous).add(group.id))} + onOpenThread={onOpenThread} + onOpenMenu={openRowMenu} + openPrLink={openPrLink} + /> + )) + )} +
+
+ ); +}); + +/** + * One group: its name and count over a hairline, then its rows. Done is the + * one that folds shut, like the sidebar's Wrapped shelf, so its whole header + * is the control. + */ +function BoardGroup({ + group, + open, + expanded, + activeThreadKey, + onToggle, + onExpand, + onOpenThread, + onOpenMenu, + openPrLink, +}: { + group: ProjectBoardGroup; + open: boolean; + expanded: boolean; + activeThreadKey: string; + onToggle: (() => void) | null; + onExpand: () => void; + onOpenThread: (threadRef: ScopedThreadRef) => void; + onOpenMenu: (entry: InboxEntry, position: { readonly x: number; readonly y: number }) => void; + openPrLink: ReturnType; +}) { + const { shown, hiddenCount } = foldProjectBoardGroup(group.rows, expanded); + const headerText = ( + <> + + {group.label} ({group.rows.length}) + +