diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 016739aaf..3023485b4 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -92,7 +92,7 @@ Whether the thread's agent may bring in another model on its own is {place:threa id: "agent-threads", title: "Threads agents start", keywords: ["child thread", "subthread", "thread_start", "spawn", "parallel", "delegate"], - body: `An agent can start threads of its own to work in parallel, and message, read or stop them. Each started thread shows under its parent in the sidebar; its final reply comes back to the parent as a message, which wakes the parent's agent. + body: `An agent can start threads of its own to work in parallel, and message, read or stop them. Each started thread shows under its parent in the sidebar; its final reply comes back to the parent as a message, which wakes the parent's agent. The parent and the threads it started also show as a row of tabs under the chat header, on the parent and on each of its threads: a click opens that thread, with its own message box and draft. The row lists the threads the sidebar shows under the parent; one the user made its own, or whose parent is wrapped, has no row. {place:threads.agentThreads} decides this: Off, Ask me first (a card in the chat lists the threads and you decide), or Automatic. The same setting covers agents creating or changing scheduled tasks. An agent may start at most 5 threads and send 10 messages to them per message you send. @@ -128,9 +128,9 @@ When an agent asks to start several threads, the card has a checkbox per thread, Only one thread leads a project; making another the lead replaces it. "Stop using as lead chat" turns it back into an ordinary thread, and the threads it started stay with it. Archiving or deleting the lead ends it. A lead can't move to another computer, and each computer keeps its own lead for a project. -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 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, or, once it has started threads, the family tabs with the lead first. -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 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. 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.agents.browser.tsx b/apps/web/src/components/ChatView.agents.browser.tsx index 064561ff0..cbae7e513 100644 --- a/apps/web/src/components/ChatView.agents.browser.tsx +++ b/apps/web/src/components/ChatView.agents.browser.tsx @@ -68,10 +68,12 @@ import { findVisibleComposerFooter, mountChatView, registerChatViewSuiteHooks, + waitForURL, fixture, rpcHarness, } from "./ChatView.browser-harness"; import { readThemePreference } from "../hooks/useTheme"; +import { nextFrames, readAfterEachPaint } from "../lib/frameProbe.browser-harness"; vi.mock("../lib/gitStatusState", () => ({ // Read synchronously by the draft seeder to skip a checkout already known @@ -1242,6 +1244,104 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { } }); + it("shows a family as tabs on the parent and its threads, and keeps the row still across a switch", async () => { + const firstChild = "thread-family-first" as ThreadId; + const secondChild = "thread-family-second" as ThreadId; + const loner = "thread-family-loner" as ThreadId; + const withThreads = addThreadToSnapshot( + addThreadToSnapshot( + addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-family-tabs" as MessageId, + targetText: "family tabs target", + }), + firstChild, + ), + secondChild, + ), + loner, + ); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...withThreads, + threads: withThreads.threads.map((thread) => + thread.id === firstChild || thread.id === secondChild + ? { + ...thread, + title: thread.id === firstChild ? "Write the changelog" : "Fix the flaky test", + parentThreadId: THREAD_ID, + attachedToParent: true, + createdAt: thread.id === firstChild ? isoAt(10) : isoAt(20), + } + : thread, + ), + }, + }); + const keyOf = (threadId: ThreadId) => + scopedThreadKey(scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId)); + const row = () => document.querySelector('[data-testid="family-tabs"]'); + try { + await waitForElement(row, "The family row should show on the parent."); + const keys = () => + [...row()!.querySelectorAll('[role="tab"]')].map((tab) => tab.dataset.testid); + // A starved CI tab can take seconds to file every thread. + await vi.waitFor( + () => + expect(keys()).toEqual([ + `family-tab-${THREAD_KEY}`, + `family-tab-${keyOf(firstChild)}`, + `family-tab-${keyOf(secondChild)}`, + ]), + { timeout: 10_000 }, + ); + + // Switching to a child: the row stays mounted where it is, every frame. + const rowAtStart = row()!; + const top = rowAtStart.getBoundingClientRect().top; + const samples: { present: boolean; same: boolean; top: number | null }[] = []; + const stop = readAfterEachPaint(() => { + const current = row(); + samples.push({ + present: current !== null, + same: current === rowAtStart, + top: current?.getBoundingClientRect().top ?? null, + }); + }); + await page.getByTestId(`family-tab-${keyOf(secondChild)}`).click(); + await waitForURL( + mounted.router, + (pathname) => pathname.endsWith(`/${secondChild}`), + "A tab click should open its thread.", + ); + await vi.waitFor( + () => + expect( + row() + ?.querySelector(`[data-testid="family-tab-${keyOf(secondChild)}"]`) + ?.getAttribute("aria-selected"), + ).toBe("true"), + { timeout: 10_000 }, + ); + await nextFrames(3); + stop(); + expect(samples.length).toBeGreaterThan(0); + expect(samples.every((sample) => sample.present && sample.same)).toBe(true); + expect(samples.every((sample) => sample.top === top)).toBe(true); + // The row says who started this thread: the header's chip gives way. + expect(document.body.textContent).not.toContain("Started by"); + + // A thread with no family has no row. + await mounted.router.navigate({ + to: "/$environmentId/$threadId", + params: { environmentId: LOCAL_ENVIRONMENT_ID, threadId: loner }, + }); + await vi.waitFor(() => expect(row()).toBeNull(), { timeout: 10_000 }); + } finally { + await mounted.cleanup(); + } + }); + it("names the thread that started this one, in the header and on its request", async () => { const base = createSnapshotForTargetUser({ targetMessageId: "msg-user-started-by" as MessageId, @@ -1282,7 +1382,15 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { } : thread, ), - { ...thisThread, id: parentThreadId, title: "Ship the 0.6 release", messages: [] }, + // Its parent is wrapped: no family row stands in for the chip, so the + // header names it (docs/design/lead-chat.md, "Family tabs"). + { + ...thisThread, + id: parentThreadId, + title: "Ship the 0.6 release", + messages: [], + doneOverride: { state: "done" as const, at: isoAt(400) }, + }, ], }, }); diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index 582be3c2a..f622a6636 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -312,55 +312,6 @@ 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/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 3d1be6a73..b276c2071 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -161,6 +161,7 @@ import { useStore, } from "../store"; import { readLeadProjectName } from "../leadChat"; +import { FamilyTabs, useFamilyTabsShown } from "./chat/FamilyTabs"; import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { useUiStateStore } from "../uiStateStore"; import { @@ -2223,6 +2224,7 @@ export default function ChatView(props: ChatViewProps) { const parentEnvironmentId = remoteOrigin?.environmentId ?? environmentId; const parentThreadId = remoteOrigin?.threadId ?? activeThread?.parentThreadId ?? null; const knownParentTitle = useThreadTitle(parentEnvironmentId, parentThreadId); + const familyTabsShown = useFamilyTabsShown(activeThreadKey); const isLeadChat = useStore( (state) => activeThreadRef !== null && readLeadProjectName(state, activeThreadRef) !== null, ); @@ -8779,8 +8781,9 @@ export default function ChatView(props: ChatViewProps) { fileBrowserAvailable={!isGeneralChatThread} taskProgress={taskProgress} forkContext={forkHeaderContext} - parentContext={parentHeaderContext} - isLeadChat={isLeadChat} + // The family row under the header says both while it shows. + parentContext={familyTabsShown ? null : parentHeaderContext} + isLeadChat={isLeadChat && !familyTabsShown} outsideOrigin={activeThread.outsideOrigin ?? null} onOpenParentThread={headerHandlers.onOpenParentThread} backgroundRuns={headerBackgroundRuns} @@ -8896,6 +8899,10 @@ export default function ChatView(props: ChatViewProps) { > {chatHeader} + {/* The open thread's family: its parent and the threads it started. */} + {activeThreadRef !== null && routeKind === "server" ? ( + + ) : null} {threadErrorRateLimitResetCreditDialog} (children: readonly E[]): E[] { + return children.toSorted( + (left, right) => + (toSortableTimestamp(left.thread.createdAt) ?? 0) - + (toSortableTimestamp(right.thread.createdAt) ?? 0) || + left.thread.id.localeCompare(right.thread.id), + ); +} + +/** + * Whether a parent heads a live family: it is not wrapped, or a child on a + * computer this app can't see still works or needs the user (that child has + * no row of its own to stand on). + */ +export function headsLiveFamily( + parent: Pick, + remoteChildren: readonly InboxRemoteChild[], +): boolean { + return ( + !parent.isDone || + remoteChildren.some((child) => isChildThreadNeedingYou(child) || isChildThreadWorking(child)) + ); +} + +/** Whether a child of a live parent is still in its family (the open thread always is). */ +export function isLiveFamilyMember( + child: InboxFamilyExit & { readonly threadKey: string }, + parent: { readonly seenAt: string | undefined }, + input: { readonly activeThreadKey: string | null; readonly now: string }, +): boolean { + return child.threadKey === input.activeThreadKey || !hasLeftLiveFamily(child, parent, input.now); +} + +/** + * A parent's open family: the members the sidebar draws under its row and + * the family tabs show (docs/design/lead-chat.md, "Family tabs"). One rule + * for both, so they never disagree. Null when the parent heads no live + * family (wrapped, or no members left). + */ +export function liveFamilyOf(input: { + readonly parent: E; + /** Its attached children, in any order. */ + readonly children: readonly E[]; + /** Its children on computers this app can't see. */ + readonly remoteChildren: readonly InboxRemoteChild[]; + readonly activeThreadKey: string | null; + readonly now: string; +}): { readonly children: E[]; readonly remoteChildren: InboxRemoteChild[] } | null { + if (!headsLiveFamily(input.parent, input.remoteChildren)) return null; + const children = sortFamilyChildren(input.children).filter((child) => + isLiveFamilyMember(child, input.parent, input), + ); + const remoteChildren = input.remoteChildren.filter( + (child) => !hasLeftLiveFamily(child, input.parent, input.now), + ); + return children.length === 0 && remoteChildren.length === 0 ? null : { children, remoteChildren }; +} + export function buildInboxSections(input: { readonly entries: readonly E[]; readonly parentKeyOf: (entry: E) => string | null; @@ -1833,11 +1894,7 @@ export function buildInboxSections(input: { // A wrapped parent whose children on a computer this app can't see still // work or need the user stays live: those children have no row of their // own to stand on, unlike its children here. - const wrapped = (entry: E): boolean => - entry.isDone && - !remoteChildrenOf(entry).some( - (child) => isChildThreadNeedingYou(child) || isChildThreadWorking(child), - ); + const wrapped = (entry: E): boolean => !headsLiveFamily(entry, remoteChildrenOf(entry)); const childrenByParentKey = new Map(); for (const entry of input.entries) { const parent = parentOf(entry); @@ -1846,13 +1903,8 @@ export function buildInboxSections(input: { siblings.push(entry); childrenByParentKey.set(parent.threadKey, siblings); } - for (const siblings of childrenByParentKey.values()) { - siblings.sort( - (left, right) => - (toSortableTimestamp(left.thread.createdAt) ?? 0) - - (toSortableTimestamp(right.thread.createdAt) ?? 0) || - left.thread.id.localeCompare(right.thread.id), - ); + for (const [parentKey, siblings] of childrenByParentKey) { + childrenByParentKey.set(parentKey, sortFamilyChildren(siblings)); } const liveHeads: E[] = []; @@ -1877,10 +1929,7 @@ export function buildInboxSections(input: { } if (!wrapped(parent)) { // Finished with, it moves to Wrapped; otherwise it is in the family. - if ( - entry.threadKey !== input.activeThreadKey && - hasLeftLiveFamily(entry, parent, input.now) - ) { + if (!isLiveFamilyMember(entry, parent, input)) { doneHeads.push(entry); liveParentByKey.set(entry.threadKey, parent); } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index c7381263b..e810dd0b0 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,6 +1,5 @@ import { ChevronDownIcon, ChevronsUpIcon, CloudIcon, MonitorIcon, SearchIcon } from "lucide-react"; import React, { Suspense, useCallback, useEffect, memo, useMemo, useRef, useState } from "react"; -import { useShallow } from "zustand/react/shallow"; import { shallow } from "zustand/vanilla/shallow"; import { useKept, useStableHandlers } from "../hooks/useStableIdentity"; import type { ScopedThreadRef } from "@threadlines/contracts"; @@ -23,11 +22,7 @@ import { reopenThreadByKey, setRemoteChildDoneOverride, } from "../lib/threadInboxSync"; -import { - useComputerLinksStore, - type ComputerLinksEntry, -} from "../environments/links/computerLinks"; -import { selectBootstrapCompleteForActiveEnvironment, useStore, type AppState } from "../store"; +import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store"; import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { useUiStateStore } from "../uiStateStore"; import { @@ -93,7 +88,6 @@ import { inboxLiveRowHoldsOpenChild, inboxLiveRowThreadKeys, isNeedsUserStatus, - INBOX_AUTO_DONE_AFTER_DAYS, labelWrappedRowsByDay, mergeThreadDoneOverride, mergeWrappedShelfRows, @@ -114,7 +108,6 @@ import { trimInboxCustomOrder, seedInboxCustomOrder, summarizeChildThreads, - resolveRemoteFamilyChildren, toggleProjectScopeKey, windowInboxDoneRows, windowInboxThreads, @@ -181,6 +174,7 @@ import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill"; import { SidebarVersionTag } from "./sidebar/SidebarVersionTag"; import { readEnvironmentApi } from "../environmentApi"; import { useRoomsEnabled } from "~/hooks/useRoomsEnabled"; +import { NO_REMOTE_CHILDREN, useRemoteFamilyChildren } from "../hooks/useRemoteFamilyChildren"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; import { useServerKeybindings } from "../rpc/serverState"; @@ -282,23 +276,6 @@ interface InboxLiveSection { readonly rows: readonly InboxLiveRow[]; } -/** Every parent without children on other computers shares this. */ -const NO_REMOTE_CHILDREN: readonly InboxRemoteChild[] = []; - -/** - * Whether a computer still links to another, as its last links snapshot says. - * Unknown (no snapshot yet, or one no longer live) reads as linked: only a - * computer that says so has dropped the link. - */ -function stillLinked(entry: ComputerLinksEntry | undefined, environmentId: EnvironmentId) { - if (entry === undefined || !entry.live) return true; - return entry.snapshot.outbound.some( - (link) => - link.remoteEnvironmentId === environmentId && - (link.state === "active" || link.state === "failed"), - ); -} - /** Wraps up or reopens a child on a computer this app can't see, through its parent's computer. */ const setRemoteChildDone: RemoteChildSetDone = (child, state) => { if (child.parentRef === undefined || child.threadId === null) return; @@ -316,16 +293,6 @@ const setRemoteChildDone: RemoteChildSetDone = (child, state) => { }); }; -/** - * The computers whose thread lists this app has: their threads speak for - * themselves, so a parent's record of a child there stays out of its family. - */ -function selectEnvironmentIdsWithThreads(state: AppState): string[] { - return Object.entries(state.environmentStateById).flatMap(([environmentId, environment]) => - environment.bootstrapComplete ? [environmentId] : [], - ); -} - function buildThreadJumpLabelMap(input: { keybindings: ReturnType; platform: string; @@ -623,7 +590,6 @@ export default function Sidebar() { sidebarProjectByKey, resolveProjectKeyForRef, generalChatProjectKeys, - openPullRequests, pullRequestByThreadKey, linkedPullRequestsByThreadKey, entries, @@ -647,11 +613,8 @@ export default function Sidebar() { const inboxSort = useSettings((s) => s.inboxSort); const inboxCustomOrder = useSettings((s) => s.inboxCustomOrder); const inboxGroupOrder = useSettings((s) => s.inboxGroupOrder); - const wrapUpChildThreadsOnFinish = useSettings((s) => s.wrapUpChildThreadsOnFinish); - const wrapUpIdleThreads = useSettings((s) => s.wrapUpIdleThreads); - // Which computers each computer still links to: a child on one it no - // longer does has nothing more to say. - const computerLinksByEnvironmentId = useComputerLinksStore((state) => state.byEnvironmentId); + // A family's children on computers this app can't see, as the family tabs read them too. + const remoteFamilyChildren = useRemoteFamilyChildren(nowIso); const { updateSettings } = useUpdateSettings(); const roomsEnabled = useRoomsEnabled(); // The Rooms filter (in the scope menu) narrows what the inbox shows, never @@ -691,11 +654,6 @@ export default function Sidebar() { const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId); const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId); const computerLabel = useComputerLabel(); - const environmentIdsWithThreadsList = useStore(useShallow(selectEnvironmentIdsWithThreads)); - const environmentIdsWithThreads = useMemo( - () => new Set(environmentIdsWithThreadsList), - [environmentIdsWithThreadsList], - ); const pendingLinkRequests = usePendingLinkRequests(); const [renamingThreadKey, setRenamingThreadKey] = useState(null); const [renamingTitle, setRenamingTitle] = useState(""); @@ -910,8 +868,6 @@ export default function Sidebar() { entry.thread.environmentId === scopedEnvironmentIdValue) && (!roomsFilterActive || isRoom(entry.thread)) && (scopedProjectKeySet.size === 0 || scopedProjectKeySet.has(entry.projectKey)); - const canSeeComputer = (environmentId: EnvironmentId) => - environmentIdsWithThreads.has(environmentId); const { live, done, doneRemote } = buildInboxSections({ entries, parentKeyOf: (entry) => familyParentKeyOf(entry.thread), @@ -921,30 +877,11 @@ export default function Sidebar() { parent.thread.environmentId !== scopedEnvironmentIdValue && inScope(child), remoteChildrenOf: (parent) => - (parent.thread.remoteChildren?.length ?? 0) + - (parent.thread.remoteChildStarts?.length ?? 0) + - (parent.thread.localChildStarts?.length ?? 0) === - 0 - ? NO_REMOTE_CHILDREN - : resolveRemoteFamilyChildren({ - parent: parent.thread, - canSeeComputer, - computerLabel, - hasThread: (threadId) => - entryByThreadKey.has( - scopedThreadKey(scopeThreadRef(parent.thread.environmentId, threadId)), - ), - filing: { - now: nowIso, - wrapUpOnFinish: wrapUpChildThreadsOnFinish, - autoDoneAfterDays: wrapUpIdleThreads ? INBOX_AUTO_DONE_AFTER_DAYS : null, - linked: (environmentId) => - stillLinked( - computerLinksByEnvironmentId[parent.thread.environmentId], - environmentId, - ), - }, - }), + remoteFamilyChildren(parent.thread, (threadId) => + entryByThreadKey.has( + scopedThreadKey(scopeThreadRef(parent.thread.environmentId, threadId)), + ), + ), isFamilyOpen: (parentKey) => childThreadFamilyOpenById[parentKey] === true, activeThreadKey: routeThreadKey, now: nowIso, @@ -968,11 +905,8 @@ export default function Sidebar() { return { liveEntries: live, doneEntries: done, doneRemoteEntries: doneRemote }; }, [ childThreadFamilyOpenById, - computerLabel, - computerLinksByEnvironmentId, doneThreadOverlays, entries, - environmentIdsWithThreads, inboxCustomOrder, inboxSort, nowIso, @@ -980,8 +914,7 @@ export default function Sidebar() { routeThreadKey, scopedEnvironmentIdValue, scopedProjectKeys, - wrapUpChildThreadsOnFinish, - wrapUpIdleThreads, + remoteFamilyChildren, ]); // The Wrapped shelf: wrapped threads, and children on computers this app // can't see that left a live family, by when each wrapped. diff --git a/apps/web/src/components/chat/FamilyTabs.tsx b/apps/web/src/components/chat/FamilyTabs.tsx new file mode 100644 index 000000000..2e10dca45 --- /dev/null +++ b/apps/web/src/components/chat/FamilyTabs.tsx @@ -0,0 +1,329 @@ +/** + * Family tabs (docs/design/lead-chat.md, "Family tabs"): under the chat + * header, one row for the open thread's family, the parent first and then + * the threads it started. A tab is a thread open: the same chat with its own + * message box, scroll position and draft. + * + * The row belongs to the family, not to the open thread: it is keyed by the + * parent, so switching between members keeps it mounted and still. It reads + * a narrow model (`sameFamilyTabs`), so a reply streaming in one thread does + * not redraw it. + */ +import { parseScopedThreadKey, scopedThreadKey } from "@threadlines/client-runtime"; +import type { ScopedThreadRef } from "@threadlines/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { CheckIcon, FlagIcon } from "lucide-react"; +import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { create } from "zustand"; + +import { useInboxThreads } from "../../hooks/useInboxThreads"; +import { useIsMobile } from "../../hooks/useMediaQuery"; +import { useRemoteFamilyChildren } from "../../hooks/useRemoteFamilyChildren"; +import { useKept } from "../../hooks/useStableIdentity"; +import { useThreadMenu } from "../../hooks/useThreadMenu"; +import { useTouchHoldMenu } from "../../hooks/useTouchHoldMenu"; +import { requestIdleThreadDetailPrewarm } from "../../environments/runtime/service"; +import { cn } from "../../lib/utils"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; +import { + type FamilyTab, + type FamilyTabs as FamilyTabsModel, + familyTabsOf, + fitFamilyTabs, + sameFamilyTabs, +} from "./familyTabs.logic"; + +/** The members of the family whose row is on screen, newline-joined; "" for none. */ +const useFamilyTabsShownStore = create<{ readonly memberKeys: string }>()(() => ({ + memberKeys: "", +})); + +/** + * Whether the family row is showing for `threadKey`: the header then drops + * its "Lead chat" and "Started by" chips, since the row says both. + */ +export function useFamilyTabsShown(threadKey: string | null): boolean { + return useFamilyTabsShownStore( + (state) => threadKey !== null && state.memberKeys.split("\n").includes(threadKey), + ); +} + +/** What "+N" takes on the row, its own width. */ +const OVERFLOW_PX = 44; + +/** + * The row for `threadRef`'s family, or nothing when it has none. While it + * shows, the header's "Lead chat" and "Started by" chips give way to it + * (`useFamilyTabsShown`). + */ +export function FamilyTabs({ threadRef }: { threadRef: ScopedThreadRef }) { + const family = useFamilyTabs(threadRef); + const navigate = useNavigate(); + + const open = useCallback( + (target: ScopedThreadRef) => { + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(target) }); + }, + [navigate], + ); + + // The members are a click away: load them ahead, as the sidebar does its rows. + const memberKeys = + family === null + ? "" + : family.tabs.flatMap((tab) => (tab.threadRef === null ? [] : [tab.key])).join("\n"); + useEffect(() => { + if (memberKeys === "") return; + return requestIdleThreadDetailPrewarm( + memberKeys.split("\n").flatMap((key) => { + const ref = parseScopedThreadKey(key); + return ref === null ? [] : [ref]; + }), + ); + }, [memberKeys]); + + // The header's chips give way while the row shows; it reads this. + useLayoutEffect(() => { + useFamilyTabsShownStore.setState({ memberKeys }); + }, [memberKeys]); + useLayoutEffect(() => () => useFamilyTabsShownStore.setState({ memberKeys: "" }), []); + + if (family === null) return null; + return ; +} + +/** + * The open thread's family as the row draws it, kept while nothing it shows + * changes. Membership is the sidebar's own rule (`liveFamilyOf`, through + * `familyTabsOf`), fed by the same filing (`useInboxThreads`). + */ +export function useFamilyTabs(threadRef: ScopedThreadRef): FamilyTabsModel | null { + const openKey = scopedThreadKey(threadRef); + const { entries, nowIso } = useInboxThreads(); + const remoteFamilyChildren = useRemoteFamilyChildren(nowIso); + const family = useMemo(() => { + const keys = new Set(entries.map((entry) => entry.threadKey)); + return familyTabsOf({ + openKey, + entries, + remoteChildrenOf: (parent) => + remoteFamilyChildren(parent.thread, (threadId) => + keys.has(scopedThreadKey({ environmentId: parent.thread.environmentId, threadId })), + ), + now: nowIso, + }); + }, [entries, nowIso, openKey, remoteFamilyChildren]); + return useKept(family, sameFamilyTabs); +} + +const FamilyTabRow = memo(function FamilyTabRow({ + family, + onOpen, +}: { + family: FamilyTabsModel; + onOpen: (target: ScopedThreadRef) => void; +}) { + const isMobile = useIsMobile(); + const rowRef = useRef(null); + const [rowPx, setRowPx] = useState(null); + useLayoutEffect(() => { + const row = rowRef.current; + if (row === null || isMobile) return; + setRowPx(row.clientWidth); + const observer = new ResizeObserver(([entry]) => { + if (entry) setRowPx(Math.round(entry.contentRect.width)); + }); + observer.observe(row); + return () => observer.disconnect(); + }, [isMobile]); + + // On a phone the row scrolls sideways instead, with the open tab in view. + const openTabRef = useRef(null); + const openKey = family.openKey; + useLayoutEffect(() => { + if (isMobile && openKey !== "") { + openTabRef.current?.scrollIntoView({ block: "nearest", inline: "nearest" }); + } + }, [openKey, isMobile]); + + const { shown, hidden } = + isMobile || rowPx === null + ? { shown: family.tabs, hidden: [] as readonly FamilyTab[] } + : fitFamilyTabs({ + tabs: family.tabs, + openKey: family.openKey, + rowPx, + overflowPx: OVERFLOW_PX, + }); + + return ( +
+ {shown.map((tab) => ( + + ))} + {hidden.length > 0 ?
+ ); +}); + +const FamilyTabButton = memo(function FamilyTabButton({ + tab, + active, + fill, + onOpen, + buttonRef, +}: { + tab: FamilyTab; + active: boolean; + /** May shrink when the row is crowded (desktop); on a phone each keeps its width and the row scrolls. */ + fill: boolean; + onOpen: (target: ScopedThreadRef) => void; + buttonRef?: React.RefObject | undefined; +}) { + const threadMenu = useThreadMenu(); + const openMenu = useCallback( + (position: { readonly x: number; readonly y: number }) => { + if (tab.threadRef !== null) { + void threadMenu.open({ threadRef: tab.threadRef, inbox: tab.inbox }, position); + } + }, + [tab.inbox, tab.threadRef, threadMenu], + ); + const onContextMenu = useCallback( + (event: React.MouseEvent) => { + event.preventDefault(); + openMenu({ x: event.clientX, y: event.clientY }); + }, + [openMenu], + ); + const touchHold = useTouchHoldMenu({ open: openMenu, onContextMenu }); + const label = + tab.kind === "parent" && tab.lead + ? `Lead: ${tab.title}` + : tab.statusWord !== null + ? `${tab.title}, ${tab.statusWord}` + : tab.title; + return ( + + ); +}); + +/** "+N": the tabs that don't fit, with their status; amber while one needs the user. */ +function FamilyTabOverflow({ + hidden, + onOpen, +}: { + hidden: readonly FamilyTab[]; + onOpen: (target: ScopedThreadRef) => void; +}) { + // The colour of the first hidden thread that needs the user: no new colour. + const needsYouDot = hidden.find((tab) => tab.needsYou)?.dotClass ?? null; + return ( + + + +{hidden.length} + {needsYouDot !== null ? ( + + ) : null} + + + {hidden.map((tab) => ( + { + if (tab.threadRef !== null) onOpen(tab.threadRef); + }} + > + + {tab.done ? ( + + ))} + + + ); +} diff --git a/apps/web/src/components/chat/familyTabs.logic.test.ts b/apps/web/src/components/chat/familyTabs.logic.test.ts new file mode 100644 index 000000000..a3f42f165 --- /dev/null +++ b/apps/web/src/components/chat/familyTabs.logic.test.ts @@ -0,0 +1,142 @@ +import { scopedThreadKey, scopeThreadRef } from "@threadlines/client-runtime"; +import { EnvironmentId, ThreadId } from "@threadlines/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { ThreadStatusPill } from "../Sidebar.logic"; +import type { SidebarThreadSummary } from "../../types"; +import { + type FamilyTab, + type FamilyTabEntry, + familyTabsOf, + fitFamilyTabs, +} from "./familyTabs.logic"; + +const environmentId = EnvironmentId.make("environment-local"); +const keyOf = (id: string) => scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(id))); +const NOW = "2026-11-16T12:00:00.000Z"; +const working: ThreadStatusPill = { + label: "Working", + colorClass: "text-working", + dotClass: "dot-working", + pulse: true, +}; +const approval: ThreadStatusPill = { + label: "Pending Approval", + colorClass: "text-approval", + dotClass: "dot-approval", + pulse: false, +}; + +function entry( + id: string, + options: { + parent?: string; + attached?: boolean; + createdAt?: string; + status?: ThreadStatusPill | null; + done?: boolean; + seenAt?: string; + wrappedByUser?: boolean; + lead?: boolean; + } = {}, +): FamilyTabEntry { + const createdAt = options.createdAt ?? "2026-11-16T10:00:00.000Z"; + return { + threadKey: keyOf(id), + thread: { + id: ThreadId.make(id), + environmentId, + title: `Title ${id}`, + createdAt, + parentThreadId: options.parent === undefined ? null : ThreadId.make(options.parent), + attachedToParent: options.attached ?? options.parent !== undefined, + } as SidebarThreadSummary, + status: options.status ?? null, + isDone: options.done ?? false, + settledAt: createdAt, + seenAt: options.seenAt, + deliveredAt: null, + wrappedByUser: options.wrappedByUser ?? false, + isLead: options.lead ?? false, + }; +} + +const tabsFor = (open: string, entries: readonly FamilyTabEntry[]) => + familyTabsOf({ openKey: keyOf(open), entries, remoteChildrenOf: () => [], now: NOW }); + +describe("family tabs", () => { + const family = [ + entry("lead", { lead: true }), + entry("second", { parent: "lead", createdAt: "2026-11-16T10:02:00.000Z", status: approval }), + entry("first", { parent: "lead", createdAt: "2026-11-16T10:01:00.000Z", status: working }), + entry("alone"), + ]; + + it("shows the parent first, then its threads oldest first, the same row from any member", () => { + const onParent = tabsFor("lead", family); + const onChild = tabsFor("second", family); + expect(onParent?.tabs.map((tab) => tab.key)).toEqual([ + keyOf("lead"), + keyOf("first"), + keyOf("second"), + ]); + expect(onChild?.familyKey).toBe(keyOf("lead")); + expect(onChild?.tabs.map((tab) => tab.key)).toEqual(onParent?.tabs.map((tab) => tab.key)); + expect(onParent?.tabs[0]).toMatchObject({ kind: "parent", lead: true }); + expect(onParent?.tabs[2]).toMatchObject({ statusWord: "approval", needsYou: true }); + }); + + it("has no row on a thread with no family, a child the user made its own, or under a wrapped parent", () => { + expect(tabsFor("alone", family)).toBeNull(); + const separated = [entry("parent"), entry("own", { parent: "parent", attached: false })]; + expect(tabsFor("own", separated)).toBeNull(); + expect(tabsFor("parent", separated)).toBeNull(); + const wrappedParent = [entry("parent", { done: true }), entry("child", { parent: "parent" })]; + expect(tabsFor("child", wrappedParent)).toBeNull(); + }); + + it("drops a child the user wrapped, as the sidebar does, but never the open one", () => { + const wrapped = [ + entry("parent"), + entry("kept", { parent: "parent" }), + entry("gone", { parent: "parent", done: true, wrappedByUser: true }), + ]; + expect(tabsFor("parent", wrapped)?.tabs.map((tab) => tab.key)).toEqual([ + keyOf("parent"), + keyOf("kept"), + ]); + const openGone = tabsFor("gone", wrapped); + expect(openGone?.tabs.find((tab) => tab.key === keyOf("gone"))).toMatchObject({ done: true }); + }); +}); + +describe("fitting the row", () => { + const tab = (key: string, needsYou = false): FamilyTab => ({ + key, + threadRef: null, + kind: "child", + title: key, + lead: false, + dotClass: null, + statusWord: null, + done: false, + needsYou, + computerLabel: null, + inbox: null, + }); + const tabs = ["a", "b", "c", "d", "e", "f"].map((key) => tab(key, key === "f")); + + it("keeps every tab while they fit at the floor, else moves the last behind +N", () => { + expect(fitFamilyTabs({ tabs, openKey: "a", rowPx: 600, overflowPx: 40 }).hidden).toEqual([]); + const tight = fitFamilyTabs({ tabs, openKey: "a", rowPx: 340, overflowPx: 40 }); + expect(tight.shown.map((entry) => entry.key)).toEqual(["a", "b", "c"]); + expect(tight.hidden.map((entry) => entry.key)).toEqual(["d", "e", "f"]); + expect(tight.hidden.some((entry) => entry.needsYou)).toBe(true); + }); + + it("always keeps the open thread's tab on the row", () => { + const tight = fitFamilyTabs({ tabs, openKey: "e", rowPx: 340, overflowPx: 40 }); + expect(tight.shown.map((entry) => entry.key)).toEqual(["a", "b", "e"]); + expect(tight.hidden.map((entry) => entry.key)).toEqual(["c", "d", "f"]); + }); +}); diff --git a/apps/web/src/components/chat/familyTabs.logic.ts b/apps/web/src/components/chat/familyTabs.logic.ts new file mode 100644 index 000000000..04fbfc5db --- /dev/null +++ b/apps/web/src/components/chat/familyTabs.logic.ts @@ -0,0 +1,200 @@ +/** + * Family tabs (docs/design/lead-chat.md, "Family tabs"): a thread that + * started other threads, and each thread it started, show one row of tabs + * under the chat header. Which threads are on the row is the sidebar's own + * family rule (`liveFamilyOf`); how the row lays them out is decided here, + * as data, so the component only draws it. + */ +import { scopeThreadRef } from "@threadlines/client-runtime"; +import type { ScopedThreadRef } from "@threadlines/contracts"; + +import type { SidebarThreadSummary } from "../../types"; + +import { + familyParentKeyOf, + type InboxFamilyEntry, + type InboxRemoteChild, + inboxStatusWord, + isChildThreadNeedingYou, + isNeedsUserStatus, + liveFamilyOf, +} from "../Sidebar.logic"; + +/** One tab on the row. */ +export interface FamilyTab { + /** The thread's scoped key (or the remote child's key). */ + readonly key: string; + /** What a click opens; null for a child this app has no thread for. */ + readonly threadRef: ScopedThreadRef | null; + readonly kind: "parent" | "child"; + readonly title: string; + /** The parent is its project's lead chat: its tab is the flag and "Lead". */ + readonly lead: boolean; + /** A child's status dot class and word; null for the parent or a quiet child. */ + readonly dotClass: string | null; + readonly statusWord: string | null; + /** Wrapped and still in the family: a check instead of a dot. */ + readonly done: boolean; + /** Waiting on the user (what makes "+N" amber when it is hidden). */ + readonly needsYou: boolean; + /** The computer it runs on when the app can't see that computer. */ + readonly computerLabel: string | null; + /** Where the sidebar files it, for the menu's Wrap up or Reopen; null where it has none. */ + readonly inbox: { readonly isDone: boolean; readonly canMarkDone: boolean } | null; +} + +/** The row for the open thread's family, or null when it has none. */ +export interface FamilyTabs { + /** The parent's key: the row belongs to the family, never to the open thread. */ + readonly familyKey: string; + readonly tabs: readonly FamilyTab[]; + readonly openKey: string; +} + +/** What the row reads about each thread, filed the way the sidebar files it. */ +export interface FamilyTabEntry extends InboxFamilyEntry { + readonly thread: SidebarThreadSummary; + readonly isLead?: boolean | undefined; + /** Whether its row offers Wrap up (InboxEntry.canMarkDone). */ + readonly canMarkDone?: boolean | undefined; +} + +/** + * The open thread's family as tabs: on a parent with at least one member, and + * on each member while its parent is live. The parent first, then its + * threads in the order the sidebar draws them. Null for a thread with no + * family, a child the user made its own, or one whose parent is wrapped. + */ +export function familyTabsOf(input: { + readonly openKey: string; + readonly entries: readonly E[]; + readonly remoteChildrenOf: (parent: E) => readonly InboxRemoteChild[]; + readonly now: string; +}): FamilyTabs | null { + const byKey = new Map(input.entries.map((entry) => [entry.threadKey, entry] as const)); + const open = byKey.get(input.openKey); + if (open === undefined) return null; + const parentKey = familyParentKeyOf(open.thread) ?? open.threadKey; + const parent = byKey.get(parentKey); + if (parent === undefined) return null; + const family = liveFamilyOf({ + parent, + children: input.entries.filter( + (entry) => + entry.threadKey !== parent.threadKey && familyParentKeyOf(entry.thread) === parentKey, + ), + remoteChildren: input.remoteChildrenOf(parent), + activeThreadKey: input.openKey, + now: input.now, + }); + if (family === null) return null; + // The open child must be one of them (it always is while its parent is live). + if ( + parent.threadKey !== input.openKey && + !family.children.some((child) => child.threadKey === input.openKey) + ) { + return null; + } + const childTab = (child: E): FamilyTab => ({ + key: child.threadKey, + threadRef: scopeThreadRef(child.thread.environmentId, child.thread.id), + kind: "child", + title: child.thread.title, + lead: false, + dotClass: child.isDone ? null : (child.status?.dotClass ?? null), + statusWord: child.isDone ? null : inboxStatusWord(child.status), + done: child.isDone, + needsYou: !child.isDone && isNeedsUserStatus(child.status), + computerLabel: null, + inbox: { isDone: child.isDone, canMarkDone: child.canMarkDone === true }, + }); + const remoteTab = (child: InboxRemoteChild): FamilyTab => ({ + key: child.threadKey, + threadRef: null, + kind: "child", + title: child.title, + lead: false, + dotClass: child.isDone ? null : (child.status?.dotClass ?? null), + statusWord: child.isDone ? null : inboxStatusWord(child.status), + done: child.isDone, + needsYou: isChildThreadNeedingYou(child), + computerLabel: child.computerLabel, + inbox: null, + }); + return { + familyKey: parent.threadKey, + openKey: input.openKey, + tabs: [ + { + key: parent.threadKey, + threadRef: scopeThreadRef(parent.thread.environmentId, parent.thread.id), + kind: "parent", + title: parent.thread.title, + lead: parent.isLead === true, + dotClass: null, + statusWord: null, + done: false, + needsYou: !parent.isDone && isNeedsUserStatus(parent.status), + computerLabel: null, + inbox: { isDone: parent.isDone, canMarkDone: parent.canMarkDone === true }, + }, + ...family.children.map(childTab), + ...family.remoteChildren.map(remoteTab), + ], + }; +} + +/** Whether two rows draw the same: the row skips a redraw when nothing it shows changed. */ +export function sameFamilyTabs(left: FamilyTabs | null, right: FamilyTabs | null): boolean { + if (left === right) return true; + if (left === null || right === null) return false; + return ( + left.familyKey === right.familyKey && + left.openKey === right.openKey && + left.tabs.length === right.tabs.length && + left.tabs.every((tab, index) => { + const other = right.tabs[index]!; + return ( + tab.key === other.key && + tab.title === other.title && + tab.lead === other.lead && + tab.dotClass === other.dotClass && + tab.statusWord === other.statusWord && + tab.done === other.done && + tab.needsYou === other.needsYou && + tab.computerLabel === other.computerLabel && + tab.inbox?.isDone === other.inbox?.isDone && + tab.inbox?.canMarkDone === other.inbox?.canMarkDone + ); + }) + ); +} + +/** The narrowest a tab gets before the rest move behind "+N". */ +export const FAMILY_TAB_MIN_WIDTH_PX = 96; + +/** + * Which tabs fit the row, in order, and which go behind "+N". Tabs shrink to + * `minTabPx`; past that, the last ones move behind the menu, which takes + * `overflowPx` itself. The open thread's tab is always on the row: when it + * would be hidden it takes the last place that fits. + */ +export function fitFamilyTabs(input: { + readonly tabs: readonly FamilyTab[]; + readonly openKey: string; + readonly rowPx: number; + readonly minTabPx?: number; + readonly overflowPx: number; +}): { readonly shown: readonly FamilyTab[]; readonly hidden: readonly FamilyTab[] } { + const minTabPx = input.minTabPx ?? FAMILY_TAB_MIN_WIDTH_PX; + const all = input.tabs; + if (all.length * minTabPx <= input.rowPx) return { shown: all, hidden: [] }; + const fit = Math.max(1, Math.floor((input.rowPx - input.overflowPx) / minTabPx)); + let shown = all.slice(0, fit); + if (!shown.some((tab) => tab.key === input.openKey)) { + const open = all.find((tab) => tab.key === input.openKey); + if (open !== undefined) shown = [...shown.slice(0, Math.max(0, fit - 1)), open]; + } + const shownKeys = new Set(shown.map((tab) => tab.key)); + return { shown, hidden: all.filter((tab) => !shownKeys.has(tab.key)) }; +} diff --git a/apps/web/src/hooks/useRemoteFamilyChildren.ts b/apps/web/src/hooks/useRemoteFamilyChildren.ts new file mode 100644 index 000000000..b0e1db277 --- /dev/null +++ b/apps/web/src/hooks/useRemoteFamilyChildren.ts @@ -0,0 +1,94 @@ +import type { EnvironmentId, ThreadId } from "@threadlines/contracts"; +import { useCallback, useMemo } from "react"; +import { useShallow } from "zustand/react/shallow"; + +import { + INBOX_AUTO_DONE_AFTER_DAYS, + type InboxRemoteChild, + resolveRemoteFamilyChildren, +} from "../components/Sidebar.logic"; +import { useComputerLabel } from "../components/sidebar/linkedComputers"; +import { + type ComputerLinksEntry, + useComputerLinksStore, +} from "../environments/links/computerLinks"; +import { type AppState, useStore } from "../store"; +import type { SidebarThreadSummary } from "../types"; +import { useSettings } from "./useSettings"; + +/** Every parent without children on other computers shares this. */ +export const NO_REMOTE_CHILDREN: readonly InboxRemoteChild[] = []; + +/** + * Whether a computer still links to another, as its last links snapshot says. + * Unknown (no snapshot yet, or one no longer live) reads as linked: only a + * computer that says so has dropped the link. + */ +function stillLinked(entry: ComputerLinksEntry | undefined, environmentId: EnvironmentId) { + if (entry === undefined || !entry.live) return true; + return entry.snapshot.outbound.some( + (link) => + link.remoteEnvironmentId === environmentId && + (link.state === "active" || link.state === "failed"), + ); +} + +/** + * The computers whose thread lists this app has: their threads speak for + * themselves, so a parent's record of a child there stays out of its family. + */ +export function selectEnvironmentIdsWithThreads(state: AppState): string[] { + return Object.entries(state.environmentStateById).flatMap(([environmentId, environment]) => + environment.bootstrapComplete ? [environmentId] : [], + ); +} + +/** + * A parent's children the app has no thread for (on a computer it can't see, + * or a start with no thread yet), filed the way the sidebar files them. The + * sidebar's families and the family tabs both read them through this. + * `hasThread` says whether the app has a thread of the parent's computer. + */ +export function useRemoteFamilyChildren(nowIso: string) { + const computerLinksByEnvironmentId = useComputerLinksStore((state) => state.byEnvironmentId); + const computerLabel = useComputerLabel(); + const environmentIdsWithThreadsList = useStore(useShallow(selectEnvironmentIdsWithThreads)); + const environmentIdsWithThreads = useMemo( + () => new Set(environmentIdsWithThreadsList), + [environmentIdsWithThreadsList], + ); + const wrapUpChildThreadsOnFinish = useSettings((s) => s.wrapUpChildThreadsOnFinish); + const wrapUpIdleThreads = useSettings((s) => s.wrapUpIdleThreads); + return useCallback( + ( + parent: SidebarThreadSummary, + hasThread: (threadId: ThreadId) => boolean, + ): readonly InboxRemoteChild[] => + (parent.remoteChildren?.length ?? 0) + + (parent.remoteChildStarts?.length ?? 0) + + (parent.localChildStarts?.length ?? 0) === + 0 + ? NO_REMOTE_CHILDREN + : resolveRemoteFamilyChildren({ + parent, + canSeeComputer: (environmentId) => environmentIdsWithThreads.has(environmentId), + computerLabel, + hasThread, + filing: { + now: nowIso, + wrapUpOnFinish: wrapUpChildThreadsOnFinish, + autoDoneAfterDays: wrapUpIdleThreads ? INBOX_AUTO_DONE_AFTER_DAYS : null, + linked: (environmentId) => + stillLinked(computerLinksByEnvironmentId[parent.environmentId], environmentId), + }, + }), + [ + computerLabel, + computerLinksByEnvironmentId, + environmentIdsWithThreads, + nowIso, + wrapUpChildThreadsOnFinish, + wrapUpIdleThreads, + ], + ); +} diff --git a/apps/web/src/leadChat.ts b/apps/web/src/leadChat.ts index b317fccd3..3807b3307 100644 --- a/apps/web/src/leadChat.ts +++ b/apps/web/src/leadChat.ts @@ -17,15 +17,12 @@ import { } from "@threadlines/contracts"; import { leadSetRefusal, projectLeadThreadId } from "@threadlines/shared/projectLead"; import { agentThreadsMode } from "@threadlines/shared/serverSettings"; -import * as Schema from "effect/Schema"; import { addComputerNotConnectedNotice } from "./components/computerConnectionNotices"; import { failureNotice, toastManager } from "./components/ui/toast"; import { readEnvironmentApi } from "./environmentApi"; import { readEnvironmentDescriptor } from "./environments/runtime"; -import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage"; import { newCommandId, newThreadId } from "./lib/utils"; -import { queueRightPanelTab } from "./rightPanelTabs"; import { lastUsedSelection, readComputerConfig, @@ -159,20 +156,6 @@ export function leadMenuLabel(state: LeadMenuState): string { : `${base}: ${state.refusal.charAt(0).toLowerCase()}${state.refusal.slice(1).replace(/\.$/, "")}`; } -/** Set once a thread on this device has become a lead: see `showThreadsPanelOnFirstLead`. */ -const FIRST_LEAD_SHOWN_KEY = "threadlines:lead-chat:threads-panel-shown"; - -/** - * The first time a thread becomes the lead on this device, its Threads tab - * opens beside it, so the board that goes with a lead is found. Once per - * device: after that, opening it is the user's move. - */ -function showThreadsPanelOnFirstLead(threadRef: ScopedThreadRef): void { - if (getLocalStorageItem(FIRST_LEAD_SHOWN_KEY, Schema.Boolean) === true) return; - setLocalStorageItem(FIRST_LEAD_SHOWN_KEY, true, Schema.Boolean); - queueRightPanelTab(scopedThreadKey(threadRef), "threads"); -} - /** * Makes `threadId` the project's lead chat, or (null) stops having one, on * the project's own computer. Says so when that computer can't be reached @@ -209,9 +192,6 @@ export async function setProjectLead(input: { projectId: input.projectId, threadId: input.threadId, }); - if (input.threadId !== null) { - showThreadsPanelOnFirstLead(scopeThreadRef(input.environmentId, input.threadId)); - } return true; } catch (error) { toastManager.add(failureNotice({ title: failure, error })); diff --git a/apps/web/src/rightPanelTabs.ts b/apps/web/src/rightPanelTabs.ts index 86a26ef57..1192a49eb 100644 --- a/apps/web/src/rightPanelTabs.ts +++ b/apps/web/src/rightPanelTabs.ts @@ -653,38 +653,7 @@ export function hideRightPanel(threadKey: string | null): void { mutate(threadKey, hideRightPanelState); } -/** - * A tab something outside the route wants opened on a thread the next time - * its route can show it: code that has no navigation of its own (a command - * finishing) asks here, and the route opens it, URL and all, once the thread - * is on screen with that tab available. Session-scoped like the strips. - */ -const queuedTabByThreadKey = new Map(); - -export function queueRightPanelTab(threadKey: string, tab: RightPanelTab): void { - queuedTabByThreadKey.set(threadKey, tab); - notify(); -} - -/** The tab queued for this thread, if any. The route opens it, then clears it. */ -export function useQueuedRightPanelTab(threadKey: string | null): RightPanelTab | null { - return useSyncExternalStore( - subscribe, - useCallback( - () => (threadKey ? (queuedTabByThreadKey.get(threadKey) ?? null) : null), - [threadKey], - ), - ); -} - -export function clearQueuedRightPanelTab(threadKey: string): void { - if (queuedTabByThreadKey.delete(threadKey)) { - notify(); - } -} - export function resetRightPanelTabsForTests(): void { stateByThreadKey.clear(); - queuedTabByThreadKey.clear(); notify(); } diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx index c42dd0f94..b47ee97da 100644 --- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx +++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx @@ -88,12 +88,10 @@ import { autoOpenAgentsTab, availableRightPanelTabs, type AgentsAutoOpenEdge, - clearQueuedRightPanelTab, closeRightPanelTab, focusRightPanelTab, hideRightPanel, isRightPanelClosedInSearch, - useQueuedRightPanelTab, useReconciledRightPanelTabs, moveRightPanelTab, pullRequestTabSearchParams, @@ -668,19 +666,6 @@ function ChatThreadRouteView() { navigateToTab, shouldUseDiffSheet, ]); - // A tab queued for this thread from outside the route (the Threads tab, the - // first time a thread becomes a lead on this device): opened once the thread - // can show it, as the sheet on a phone. It is asked for once per device, so - // it is never dropped. - const queuedTab = useQueuedRightPanelTab(currentThreadKey); - useEffect(() => { - if (queuedTab === null || currentThreadKey === null || !availableTabs.includes(queuedTab)) { - return; - } - clearQueuedRightPanelTab(currentThreadKey); - focusRightPanelTab(currentThreadKey, queuedTab); - navigateToTab(queuedTab); - }, [availableTabs, currentThreadKey, navigateToTab, queuedTab]); // The thread's media, for the launcher's Media row: the same listing the // Media tab opens on, so the row and the tab agree. Read only while the // launcher is on screen; a turn landing changes the revision and so the key. diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md index 254489aac..49c505cd2 100644 --- a/docs/design/lead-chat.md +++ b/docs/design/lead-chat.md @@ -1,6 +1,7 @@ # Lead chat: one place to run a project -Status: plan rev 3 (Nov 16 2026), being built in four pieces (see Build order). GPT-6.1 Sol reviewed rev 1 (13 findings) +Status: plan rev 4 (Nov 16 2026), being built in five pieces (see Build order). Rev 4 adds +family tabs (piece 5), asked for by Will after seeing pieces 1 to 3; that section has not been reviewed. GPT-6.1 Sol reviewed rev 1 (13 findings) and the two redesigned parts of rev 2 (6 findings). Each was checked against the code and all hold; the answers are in "Changes from review" at the end. Rev 3's answers to the second pass were not reviewed again. Awaiting Will's go. @@ -89,8 +90,11 @@ Words below are the on-screen words. Copy follows the repo's copy rules (no em d project folder (no worktree), makes it the lead and opens it. - **Command palette:** "Go to lead chat" (one entry per project that has one), "New lead chat", "Make this thread the lead chat" / "Stop using as lead chat". -- **Keybinding command** `navigate.leadChat` (lead of the open thread's project, else of - the scoped project). No default key. +- **No keybinding command (built):** a new `navigate.leadChat` would extend + `KeybindingCommand`, a closed set an older client decodes strictly: one rule naming + it makes that client reject the whole keybinding list, and with it the computer's + config. "Go to lead chat" stays in the palette. Commands can come once clients drop + rules they don't know (a follow-up). - **Not allowed, with the reason shown on the disabled item:** General Chats; a thread another thread started and still owns; a thread from another computer or an outside agent; an archived thread; a thread with a move pending; an agent that cannot use the @@ -115,10 +119,54 @@ Words below are the on-screen words. Copy follows the repo's copy rules (no em d - Header chip "Lead chat", built like the "Started by" chip. - Empty composer placeholder: "Drop work for here". -- The first time a thread becomes the lead on this device, the Threads panel opens. +- The Threads panel does not open by itself (rev 4: the family tabs below are how the + lead's threads are reached; the panel is the whole-project view, opened on purpose). - A message the lead passed into another thread is authored "" there, as a parent's messages are in a child today. +### Family tabs (every family, not only a lead's) + +A thread that started other threads, and each thread it started, show one row of tabs +under the chat header: the parent first, then its threads. Clicking a tab opens that +thread, the same full chat as today with its own message box, scroll position and +draft. The point is that the user never loses their place: the lead (or any parent) is +always one click away, and so is every thread it started. + +- **Which threads.** Exactly the members the sidebar shows for that parent's open + family (attached children that have not left the live family, `hasLeftLiveFamily` + and the rules around it), in the same order (creation order, never re-sorted). One + function decides membership for both, so the tabs and the sidebar cannot disagree. + A child on a linked computer gets a tab when the sidebar gives it a row, and a click + does what that row's click does. +- **When the row shows.** On the parent while it has at least one member, and on each + member while its parent is live. A thread with no family has no row. A child the + user made its own, or whose parent is wrapped or archived, has no row and keeps + today's "Started by" chip. +- **A tab.** The parent's tab is its title; a lead's is the flag and "Lead". A child's + is its status dot (the family child rows' colours and words; a check once wrapped + and still in the family) and its title. The open one has a quiet fill. Hover is a + colour shift. Right-click or a long press opens the sidebar's thread menu. There is + no close button: a tab is not an open file, and wrapping up stays in the menu. +- **Too many to fit.** Tabs shrink to a floor (about 96px), then the rest move behind + a "+N" menu at the end of the row, which lists them with their status. The open + thread's tab is always on the row. "+N" carries an amber dot when a hidden thread + needs the user. On a phone the row scrolls sideways instead and the open tab is + scrolled into view. +- **What it replaces.** While the row shows, the header drops the "Started by" chip + and the "Lead chat" chip: the row says both. +- **The sidebar is unchanged.** The open child still shows under its parent's row as + it does today. (Hiding it, so only the parent's row is marked, would mean reworking + the sidebar's keyboard order for no gain the tabs do not already give.) +- **No flash.** The row belongs to the family, not to the open thread: switching + between members must not unmount or redraw it, and the chat below must not shift. + The row appearing when a parent starts its first thread shifts the chat once. +- **Speed.** A tab switch is a thread open. The threads on the row use the sidebar's + existing prewarm, so a switch paints as fast as a prewarmed sidebar row. The row + reads a narrow selection (id, title, status per member) with stable equality, so a + streaming reply in one thread does not re-render it. +- **Keys.** None for now, for the reason under "No keybinding command": the plan's + `thread.family.next` and `thread.family.previous` wait for that follow-up. + ### Starting several threads (approval card, every parent, not only the lead) The card " wants to start N threads" gets a checkbox per row, all checked. The @@ -441,9 +489,9 @@ turns too, since an event-fed lead is the main unattended case. ## Build order -Four pieces, each its own branch and pull request. 1, 2 and 4 touch the same decider +Five pieces, each its own branch and pull request. 1, 2 and 4 touch the same decider files and go in that order from one builder. 3 is web only and can run beside 2 once -piece 1's contracts are committed. +piece 1's contracts are committed. 5 is web only and can run beside 4. 1. **Lead role.** Project field, command, cascades, migration, capability; role text on every turn start; limits; menus, palette, keybinding command, sidebar row and @@ -475,6 +523,16 @@ piece 1's contracts are committed. failed; restart with a held request; a linked child and a `usageLimited` goal still fail as today. +5. **Family tabs.** Web only, no contract change. Membership comes from the sidebar's + own family rules (extract the function if it is buried in `buildInboxSections`); + the row's layout choices (order, which tabs fit, the open one always shown, "+N" + attention) are pure data in a `familyTabs.logic.ts`. The header chips give way + while the row shows; the Threads panel stops opening by itself. Guide: the threads + topic says a family shows as tabs. Tests: the logic as data; one browser test that + the row shows on a parent and on its child and not on a thread with no family, + that a click switches threads, and, read after every paint + (`readAfterEachPaint`), that the row does not vanish or move across the switch. + Live check before calling it done, on a throwaway stack (never `~/.threadlines/userdata`): a Claude lead starts a Codex thread and a Claude thread and hears back from both, passes a follow-up into a thread made by hand, the lead role moves to another thread