diff --git a/apps/app/src/components/commands/CommandPalette.tsx b/apps/app/src/components/commands/CommandPalette.tsx index 63f9027492a..2f766b5cbd8 100644 --- a/apps/app/src/components/commands/CommandPalette.tsx +++ b/apps/app/src/components/commands/CommandPalette.tsx @@ -25,10 +25,9 @@ import { } from "@/lib/command-palette/palette-recents"; import { buildPluginComposerCommandActions, - buildPluginPaletteActions, + buildFocusedSurfacePaletteActions, } from "@/lib/command-palette/palette-plugin-actions"; import { usePluginSlotKind } from "@/lib/plugin-slots"; -import { getFocusedAppPanelController } from "@/lib/app-fixed-tab-navigation"; import { pluginListQueryOptions } from "@/hooks/queries/plugin-settings-queries"; import type { PluginSettingsCandidate } from "@/components/settings/plugin-settings-entries"; import { appQueryClient } from "@/lib/app-query-client"; @@ -112,11 +111,10 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { useIndexedAppCommandHandlers(appPluginCommandIds, (index) => { const slot = appPluginCommands[index]; if (!slot) return false; - const action = buildPluginPaletteActions({ + const action = buildFocusedSurfacePaletteActions({ slots: [slot], threadId, projectId, - panel: getFocusedAppPanelController(), })[0]; if (!action) return false; action.run(); @@ -134,11 +132,10 @@ export function CommandPalette({ threadId, projectId }: CommandPaletteProps) { shortcuts, }), ...[ - ...buildPluginPaletteActions({ + ...buildFocusedSurfacePaletteActions({ slots: appPluginCommands, threadId, projectId, - panel: getFocusedAppPanelController(), }), ...buildPluginComposerCommandActions({ slots: composerPluginCommands, diff --git a/apps/app/src/components/plugin/PluginMarkdown.tsx b/apps/app/src/components/plugin/PluginMarkdown.tsx index 519f69b10cc..7173c3f52fb 100644 --- a/apps/app/src/components/plugin/PluginMarkdown.tsx +++ b/apps/app/src/components/plugin/PluginMarkdown.tsx @@ -6,8 +6,8 @@ import type { import { getEnvironmentFilePreviewSourceAtRef } from "@bb/client-core"; import { normalizeAbsoluteFilePath } from "@bb/shared-ui/lib/absolute-file-path"; import { + AUTHORED_MARKDOWN_THREAD_MENTIONS, MarkdownPreview, - type MarkdownThreadMentions, } from "@/components/ui/markdown-preview"; import { buildMarkdownFileRouting } from "@/components/ui/markdown-file-routing"; import { WithoutCodeFenceRenderers } from "@/components/ui/markdown-code-fence-renderers"; @@ -30,11 +30,6 @@ import { normalizeExperimentalLiveFileTarget } from "@/lib/live-file-navigation" import { useLocalFileLinkOpener } from "@/hooks/useLocalFileLinkOpener"; import { useResolvedLiveFileRoot } from "@/hooks/useResolvedLiveFileTarget"; -const PLUGIN_MARKDOWN_THREAD_MENTIONS: MarkdownThreadMentions = { - mentions: [], - preserveSoftBreaks: false, -}; - function parsePluginMarkdownDocument( document: NonNullable, ) { @@ -124,7 +119,7 @@ function PluginDocumentMarkdown({ className={className} linkRouting={linkRouting} messageDirectives={messageDirectives} - threadMentions={PLUGIN_MARKDOWN_THREAD_MENTIONS} + threadMentions={AUTHORED_MARKDOWN_THREAD_MENTIONS} /> ); } @@ -162,7 +157,7 @@ function PluginMarkdownBody({ className={className} linkRouting={document === null ? {} : messageRouting} messageDirectives={messageDirectives} - threadMentions={PLUGIN_MARKDOWN_THREAD_MENTIONS} + threadMentions={AUTHORED_MARKDOWN_THREAD_MENTIONS} /> ); } diff --git a/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx b/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx index f7660d18d18..5b5cf7129bb 100644 --- a/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx +++ b/apps/app/src/components/plugin/PluginNewThreadComposer.test.tsx @@ -2,6 +2,7 @@ import { useEffect, + useLayoutEffect, useState, useSyncExternalStore, type ReactNode, @@ -53,7 +54,10 @@ import { setPluginSlotRegistrations, } from "@/lib/plugin-slots"; import { encodeReuseValue } from "@/components/pickers/environment-picker-value"; -import { useRootComposeReuseEnvironment } from "@/lib/root-compose-selection"; +import { + useRootComposeReuseEnvironment, + useSetRootComposeProjectId, +} from "@/lib/root-compose-selection"; import { getPromptDraftAccessor } from "@/hooks/usePromptDraftStorage"; import { makeThreadListEntry } from "@bb/test-helpers/domain-fixtures"; import { createDeferredPromise } from "@bb/test-helpers"; @@ -71,7 +75,7 @@ import { serializeFixedPanelTabsState, } from "@/lib/fixed-panel-tabs-state"; import { buildPluginPaletteActions } from "@/lib/command-palette/palette-plugin-actions"; -import { getFocusedAppPanelController } from "@/lib/app-fixed-tab-navigation"; +import { getFocusedAppPanelController } from "@/lib/app-navigation-host"; import { useFixedPanelTabsState } from "@/lib/fixed-panel-tabs"; import { openPluginDetailsInWorkspace } from "./plugin-detail-opener"; import { PluginNewThreadComposer } from "./PluginNewThreadComposer"; @@ -1542,6 +1546,48 @@ describe("PluginNewThreadComposer seeding", () => { }); }); + it("starts an unseeded composer on the remembered New thread project, as bb's New thread does", async () => { + function PickInNewThread() { + const setRootComposeProjectId = useSetRootComposeProjectId(); + useLayoutEffect(() => setRootComposeProjectId("proj_1")); + return null; + } + const submitted: NewThreadRequest[] = []; + const composer = ( + { + submitted.push(request); + }} + /> + ); + const view = render( + + + + + , + ); + view.rerender( + + + + {composer} + + , + ); + + await waitFor(() => { + expect(latestPromptBoxProps().project.value).toBe("proj_1"); + expect(latestPromptBoxProps().disabled).toBe(false); + }); + await submit(); + + expect(submitted).toHaveLength(1); + expect(submitted[0]?.projectId).toBe("proj_1"); + }); + it("keeps project defaults when no seed props are passed", async () => { const submitted: NewThreadRequest[] = []; render( diff --git a/apps/app/src/components/plugin/PluginNewThreadComposer.tsx b/apps/app/src/components/plugin/PluginNewThreadComposer.tsx index 195373a1b44..8bfcff9359f 100644 --- a/apps/app/src/components/plugin/PluginNewThreadComposer.tsx +++ b/apps/app/src/components/plugin/PluginNewThreadComposer.tsx @@ -10,6 +10,7 @@ import { } from "@/components/promptbox/NewThreadComposer"; import { PluginContext } from "@/components/plugin/plugin-context"; import { useQuickCreateProjectController } from "@/hooks/useQuickCreateProject"; +import { useRootComposeProjectId } from "@/lib/root-compose-selection"; export function PluginNewThreadComposer({ defaultProjectId, @@ -29,14 +30,15 @@ export function PluginNewThreadComposer({ }: PluginComposerProps) { const pluginId = useContext(PluginContext); const quickCreateProject = useQuickCreateProjectController(); - const [pickedProjectId, setPickedProjectId] = useState( - defaultProjectId ?? null, + const [rememberedProjectId] = useRootComposeProjectId(); + const [pickedProjectId, setPickedProjectId] = useState( + defaultProjectId ?? rememberedProjectId, ); const [seededDefaultProjectId, setSeededDefaultProjectId] = useState(defaultProjectId); if (seededDefaultProjectId !== defaultProjectId) { setSeededDefaultProjectId(defaultProjectId); - setPickedProjectId(defaultProjectId ?? null); + setPickedProjectId(defaultProjectId ?? rememberedProjectId); } const seed: NewThreadComposerSeed = { diff --git a/apps/app/src/components/plugin/PluginPanelRightPanelHost.contract.test.tsx b/apps/app/src/components/plugin/PluginPanelRightPanelHost.contract.test.tsx index eb4608dc05f..6eda58fce62 100644 --- a/apps/app/src/components/plugin/PluginPanelRightPanelHost.contract.test.tsx +++ b/apps/app/src/components/plugin/PluginPanelRightPanelHost.contract.test.tsx @@ -18,7 +18,7 @@ import { collectPluginAppRegistrations, definePluginApp, } from "@/lib/plugin-app-definition"; -import { resetFocusedAppPanelControllersForTest } from "@/lib/app-fixed-tab-navigation"; +import { resetFocusedAppNavigationSurfacesForTest } from "@/lib/app-navigation-host"; import { RouteNavigationProvider } from "@/components/ui/app-route-anchor"; import { CONTRACT_PLUGIN_ID, @@ -29,12 +29,14 @@ import { contractActionPanelTabId, contractTarget, describePanelControllerContract, + readContractNavigate, readContractPanel, readContractTabs, snapshotFromState, type ContractPanelRef, type ContractStateSink, } from "@/test/panel-controller-contract"; +import { makeTerminalSession } from "@/test/fixtures/terminal-sessions"; import { PluginContext } from "./plugin-context"; import { getPluginPagePanelStateId } from "./plugin-page-panel-state"; import { PluginPanelRightPanelHost } from "./PluginPanelRightPanelHost"; @@ -64,9 +66,10 @@ vi.mock("@/hooks/queries/host-queries", () => ({ vi.mock("@/hooks/queries/system-queries", () => ({ useSystemConfig: () => ({ data: { primaryHostId: null } }), })); -vi.mock("@/lib/bb-desktop", () => ({ +vi.mock("@/lib/bb-desktop", async (importOriginal) => ({ + ...(await importOriginal()), getDesktopBrowserApi: () => null, - isDesktopBrowserAvailable: () => false, + isDesktopBrowserAvailable: () => true, })); vi.mock("react-resizable-panels", async (importOriginal) => ({ ...(await importOriginal()), @@ -169,12 +172,12 @@ beforeEach(() => { afterEach(() => { cleanup(); removePluginSlotRegistrations(CONTRACT_PLUGIN_ID); - resetFocusedAppPanelControllersForTest(); + resetFocusedAppNavigationSurfacesForTest(); }); describePanelControllerContract( "plugin nav-panel page", - { fixedTabs: true }, + { fixedTabs: true, actionTabs: true, navigation: true }, async () => { const probe: ContractPanelRef = { current: null }; const sink: ContractStateSink = { current: null }; @@ -217,6 +220,22 @@ describePanelControllerContract( ); return { panel: () => readContractPanel(probe), + navigation: { + navigate: () => readContractNavigate(probe), + open: { + terminal: makeTerminalSession({ + id: "term_contract", + threadId: null, + environmentId: null, + hostId: "host_contract", + }), + file: { + target: { kind: "host", hostId: "host_contract", path: "/a.md" }, + location: null, + }, + url: "https://example.com/contract", + }, + }, snapshot: () => snapshotFromState(sink), tabs: () => readContractTabs(probe), renderedTabVisible: () => diff --git a/apps/app/src/components/plugin/PluginPanelRightPanelHost.tsx b/apps/app/src/components/plugin/PluginPanelRightPanelHost.tsx index 839edc53119..9c5d01b8311 100644 --- a/apps/app/src/components/plugin/PluginPanelRightPanelHost.tsx +++ b/apps/app/src/components/plugin/PluginPanelRightPanelHost.tsx @@ -77,8 +77,9 @@ import { } from "@/lib/bb-desktop"; import { useIsSidebarFramed } from "@/components/ui/sidebar.js"; import { UrlOpenRoutingProvider } from "@/lib/url-open-routing"; +import type { MarkdownPreviewLinkHandler } from "@/components/ui/markdown-link"; import { usePluginSlotKind } from "@/lib/plugin-slots"; -import { AppNavigationHostProvider } from "@/lib/app-navigation-host"; +import { AppNavigationSurfaceProvider } from "@/lib/app-navigation-host"; import { FixedTabTargetScope, getPluginFixedTabOwnerId, @@ -471,7 +472,6 @@ export function PluginPanelRightPanelHost({ activeTabId: isOpen ? (activeTab?.id ?? null) : null, close: hidePanel, destinations: panelDestinations, - isFocused: isFocused && panel !== null, }); const pluginActions = useMemo( () => @@ -574,6 +574,11 @@ export function PluginPanelRightPanelHost({ reveal: revealPanel, }); const openBrowser = panelBrowser.open; + const openBrowserUrl = panelBrowser.openUrl; + const handleOpenPanelLink = useCallback( + ({ href }) => openBrowserUrl(href), + [openBrowserUrl], + ); const fixedTabs = useMemo( () => @@ -649,7 +654,9 @@ export function PluginPanelRightPanelHost({ isPanelPersistedOpen={panelState.secondary.isOpen} onAutoFocusHandled={terminals.handleAutoFocusHandled} onCloseStart={() => terminals.close(tab.terminalId)} + onOpenLink={handleOpenPanelLink} onRetryStart={() => terminals.retryStart(tab.terminalId)} + onSelectionAddToChat={null} target={tab.target} terminalId={tab.terminalId} /> @@ -724,6 +731,7 @@ export function PluginPanelRightPanelHost({ }, [ activateTab, + handleOpenPanelLink, pluginActions, panel, panelPath, @@ -948,7 +956,10 @@ export function PluginPanelRightPanelHost({ return ( - + - + ); } diff --git a/apps/app/src/components/plugin/PluginThreadChat.test.tsx b/apps/app/src/components/plugin/PluginThreadChat.test.tsx index 5d21d63623b..0f0aad69b99 100644 --- a/apps/app/src/components/plugin/PluginThreadChat.test.tsx +++ b/apps/app/src/components/plugin/PluginThreadChat.test.tsx @@ -349,7 +349,6 @@ describe("PluginThreadChat", () => { unknown >; expect(timelineHost.leadingContent).toBeTruthy(); - expect(timelineHost.includePluginMessageActions).toBe(false); const actions = timelineHost.consumerMessageActions as Array< Record >; diff --git a/apps/app/src/components/plugin/PluginThreadChat.tsx b/apps/app/src/components/plugin/PluginThreadChat.tsx index 690770724d5..541fc5f8c64 100644 --- a/apps/app/src/components/plugin/PluginThreadChat.tsx +++ b/apps/app/src/components/plugin/PluginThreadChat.tsx @@ -50,11 +50,20 @@ import { type ThreadRoutePathArgs, } from "@/lib/route-paths"; import { useOptionalPaneContext } from "@/views/thread-detail/PaneContext"; +import { + resolveThreadEnvironmentAccess, + useThreadTimelineTitleActions, +} from "@/views/thread-detail/thread-screen-hosts"; +import { useThreadUnreadDividerState } from "@/views/thread-detail/useThreadUnreadDividerState"; +import { useCreateThreadInEnvironment } from "@/hooks/useCreateThreadInEnvironment"; import { ThreadScreen, type ThreadScreenPresentation, } from "@/views/thread-detail/ThreadScreen"; +const NO_CONSUMER_MESSAGE_ACTIONS: readonly ThreadTimelineConsumerMessageAction[] = + []; + export function PluginThreadChat({ threadId, variant = "full", @@ -108,9 +117,17 @@ function PluginThreadChatBody({ const hasComposer = variant !== "timeline"; useThreadTimelineSubscription(threadId, { enabled: threadId.length > 0 }); const markThreadRead = useMarkThreadRead(); + const unreadDividerState = useThreadUnreadDividerState({ + hasFreshThread: + thread !== undefined && + !threadQuery.isPlaceholderData && + !threadQuery.isFetching, + routeThreadId: threadId, + thread, + }); useThreadReadTracking({ markThreadRead, - thread: hasComposer ? thread : undefined, + thread: hasComposer && unreadDividerState.ready ? thread : undefined, }); const threadProviderInfo = useSystemProviderInfo( thread?.environmentId @@ -163,6 +180,17 @@ function PluginThreadChatBody({ const { isLocalDaemonHost } = useHostDaemon(); const environmentQuery = useEnvironment(thread?.environmentId ?? null); const environment = environmentQuery.data ?? null; + const environmentAccess = resolveThreadEnvironmentAccess({ + thread: thread ?? null, + environment, + environmentLoadFailed: environmentQuery.isError, + }); + const createThreadInEnvironment = useCreateThreadInEnvironment({ + projectId: thread?.projectId ?? "", + environmentId: thread?.environmentId ?? "", + sectionId: thread?.sectionId ?? null, + pinned: thread?.pinnedAt != null, + }); const hostsQuery = useHosts({ enabled: environment !== null }); const environmentHost = environment ? (hostsQuery.data?.find((host) => host.id === environment.hostId) ?? null) @@ -180,6 +208,15 @@ function PluginThreadChatBody({ openFilePreview: navigation.openFilePreview, threadId: thread?.id, }).openLink; + const handleTimelineTitleAction = useThreadTimelineTitleActions({ + threadId, + projectId: thread?.projectId ?? "", + openThread: navigateToThread, + environmentId: thread?.environmentId ?? null, + panel: navigation.panel, + openFilePreview: navigation.openFilePreview, + openLocalFileLink: onOpenLocalFileLink, + }); const resolveHostMentionLink = canUseHostFileNavigation ? timelineNavigation.resolveMentionLink : undefined; @@ -190,11 +227,11 @@ function PluginThreadChatBody({ : undefined); const pluginId = useContext(PluginContext); const consumerMessageActions = useMemo< - readonly ThreadTimelineConsumerMessageAction[] | undefined + readonly ThreadTimelineConsumerMessageAction[] >( () => messageActions === undefined || messageActions.length === 0 - ? undefined + ? NO_CONSUMER_MESSAGE_ACTIONS : messageActions.map((action) => ({ id: action.id, pluginId: action.icon !== undefined ? null : pluginId, @@ -316,8 +353,13 @@ function PluginThreadChatBody({ ? { environmentCheckout, environmentChrome, - focusRequest, + focusRequest: focusRequest ?? null, contextEnvironmentId: null, + onCreateNewThreadInEnvironment: + environmentAccess.reusesEnvironment + ? createThreadInEnvironment + : null, + onOpenThreadInfo: null, permissionPolicy: permissionPolicy === "editable" ? "editable" : "snapshot", } @@ -336,11 +378,12 @@ function PluginThreadChatBody({ isHostAmbiguous(hasMultipleMachines, environmentHost.type) ? environmentHost.name : null, - includePluginMessageActions: false, - leadingContent, - onForkMessage: isForkAvailable ? handleForkMessage : undefined, - unreadDividerAutoScroll: false, - unreadDividerPlacement: null, + leadingContent: leadingContent ?? null, + messageActionSurface: "embedded-chat", + onForkMessage: isForkAvailable ? handleForkMessage : null, + onTitleAction: handleTimelineTitleAction, + unreadDividerAutoScroll: unreadDividerState.autoScroll, + unreadDividerPlacement: unreadDividerState.placement, }} /> diff --git a/apps/app/src/components/thread/ThreadActionsMenu.test.tsx b/apps/app/src/components/thread/ThreadActionsMenu.test.tsx index bb2715486ab..fcbd2da915f 100644 --- a/apps/app/src/components/thread/ThreadActionsMenu.test.tsx +++ b/apps/app/src/components/thread/ThreadActionsMenu.test.tsx @@ -46,6 +46,7 @@ import { useAppPanelController, type AppFixedTabDestination, } from "@/lib/app-fixed-tab-navigation"; +import { AppNavigationSurfaceProvider } from "@/lib/app-navigation-host"; import { ThreadActionsContextMenu, ThreadActionsMenu, @@ -914,13 +915,16 @@ describe("thread actions outside bb's own surfaces", () => { }, ]; function FocusedThreadView() { - useAppPanelController({ + const panel = useAppPanelController({ activeTabId: null, close, destinations, - isFocused: true, }); - return null; + return ( + + {null} + + ); } type RetiredNavigate = { openThreadPanel(options: { actionId: string }): boolean; diff --git a/apps/app/src/components/thread/terminal/ThreadTerminalPanel.tsx b/apps/app/src/components/thread/terminal/ThreadTerminalPanel.tsx index 2f63891c7f4..d2c20c2dfbe 100644 --- a/apps/app/src/components/thread/terminal/ThreadTerminalPanel.tsx +++ b/apps/app/src/components/thread/terminal/ThreadTerminalPanel.tsx @@ -9,9 +9,9 @@ interface ThreadTerminalPanelProps { isPanelPersistedOpen: boolean; onAutoFocusHandled?: () => void; onCloseStart: () => void; - onOpenLink?: MarkdownPreviewLinkHandler; + onOpenLink: MarkdownPreviewLinkHandler; onRetryStart: () => void; - onSelectionAddToChat?: (text: string) => void; + onSelectionAddToChat: ((text: string) => void) | null; terminalId: string; target: TerminalCreateTarget; } @@ -49,7 +49,7 @@ export function ThreadTerminalPanel({ onCloseStart={onCloseStart} onOpenLink={onOpenLink} onRetryStart={onRetryStart} - onSelectionAddToChat={onSelectionAddToChat} + onSelectionAddToChat={onSelectionAddToChat ?? undefined} /> diff --git a/apps/app/src/components/thread/timeline/ConversationMessageContent.tsx b/apps/app/src/components/thread/timeline/ConversationMessageContent.tsx index 5e24b207f89..52ecff25760 100644 --- a/apps/app/src/components/thread/timeline/ConversationMessageContent.tsx +++ b/apps/app/src/components/thread/timeline/ConversationMessageContent.tsx @@ -15,6 +15,7 @@ import type { PromptTextMention } from "@bb/domain"; import { fileNameFromPath } from "@bb/thread-view"; import { cn } from "@bb/shared-ui/lib/utils"; import { + AUTHORED_MARKDOWN_THREAD_MENTIONS, MarkdownPreview, type MarkdownThreadMentions, } from "../../ui/markdown-preview.js"; @@ -122,11 +123,6 @@ const COLLAPSED_MESSAGE_FADE_STYLE: CSSProperties = { "linear-gradient(to bottom, black calc(100% - 2.5rem), transparent)", }; -const ASSISTANT_THREAD_MENTIONS: MarkdownThreadMentions = { - mentions: [], - preserveSoftBreaks: false, -}; - const STREAMING_SETTLED_MARKDOWN_CLASS_NAME = "[&>p:last-child]:mb-2"; const STREAMING_TAIL_MARKDOWN_CLASS_NAME = "[&>h1:first-child]:mt-4 [&>h2:first-child]:mt-4 [&>h3:first-child]:mt-3 [&>h4:first-child]:mt-3 [&>h5:first-child]:mt-2 [&>h6:first-child]:mt-2"; @@ -562,7 +558,7 @@ function AssistantConversationMessage({ incrementalBlocks linkRouting={linkRouting} messageDirectives={messageDirectives} - threadMentions={ASSISTANT_THREAD_MENTIONS} + threadMentions={AUTHORED_MARKDOWN_THREAD_MENTIONS} /> {streamingSplit === null ? null : ( )} diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx index 142816b9ace..e745c8eef0d 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.actions.test.tsx @@ -35,7 +35,13 @@ function messageActionRegistrationSet( messageActions: readonly PluginMessageActionRegistration[], ): PluginRegistrationSet { return makePluginRegistrationSet({ - messageActions, + messageActions: messageActions.map((action) => ({ + ...action, + experimental_surfaces: action.experimental_surfaces ?? [ + "thread-view", + "embedded-chat", + ], + })), }); } @@ -1552,82 +1558,6 @@ describe("ThreadTimelineRows actions", () => { ); }); - it.each([ - { isCompactViewport: false, isPointerCoarse: false }, - { isCompactViewport: true, isPointerCoarse: false }, - { isCompactViewport: true, isPointerCoarse: true }, - ])( - "suppresses slot actions on embedded surfaces with media %j", - async (media) => { - mockSelectionMenuMedia(media); - const run = vi.fn(); - const sendToMain = vi.fn(); - const addToChat = vi.fn(); - setPluginSlotRegistrations( - "demo", - messageActionRegistrationSet([ - { id: "summarize", title: "Summarize selection", run }, - ]), - ); - vi.spyOn(window, "requestAnimationFrame").mockImplementation( - (callback) => { - callback(performance.now()); - return 1; - }, - ); - vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {}); - const view = renderWithRouter( - , - ); - expect( - screen.queryByRole("button", { name: "Summarize selection" }), - ).toBeNull(); - fireEvent.click( - screen.getByRole("button", { name: "Send to main thread" }), - ); - expect(sendToMain).toHaveBeenCalledTimes(1); - const textNode = screen.getByText( - "Select this embedded answer.", - ).firstChild; - mockWindowSelection({ node: textNode!, text: "embedded answer" }); - fireEvent(document, new Event("selectionchange")); - const add = await screen.findByRole("button", { name: "Add to chat" }); - expect( - screen.queryByRole("button", { name: "Summarize selection" }), - ).toBeNull(); - expect( - screen.getAllByRole("button", { name: "Send to main thread" }), - ).toHaveLength(1); - fireEvent.click(add); - expect(addToChat).toHaveBeenCalledWith("embedded answer"); - expect(run).not.toHaveBeenCalled(); - view.unmount(); - }, - ); - it("passes the recorded steer sequence to slot and consumer actions", () => { const slotRun = vi.fn(); const consumerRun = vi.fn(); diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx index 551f5da8d2e..37d51429c41 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.tsx @@ -138,6 +138,7 @@ import { } from "./MessageMetadata.js"; import { runPluginMessageAction } from "@/lib/plugin-message-actions.js"; import { useAppNavigationHost } from "@/lib/app-navigation-host"; +import { useSurfaceMessageActionSlots } from "@/lib/message-action-surface"; import type { AppPanelController } from "@/lib/app-fixed-tab-navigation"; import { usePluginComposerHost, @@ -161,7 +162,6 @@ export interface ThreadTimelineRowsProps { onMessageAddToChat?: ThreadTimelineAddToChatHandler; onSelectionAddToChat?: ThreadTimelineAddToChatHandler; consumerMessageActions?: readonly ThreadTimelineConsumerMessageAction[]; - includePluginMessageActions?: boolean; onTitleAction?: TimelineTitleActionResolver; projectId?: string; resolveMentionLink?: PromptMentionLinkResolver; @@ -2335,14 +2335,12 @@ function ThreadTimelineRowsForTimelineView(props: ThreadTimelineRowsProps) { props.initialExpanded ?? EMPTY_ROW_ID_SET, ); const projectId = props.projectId; - const messageActionSlots = usePluginSlotKind("messageActions"); + const messageActionSlots = useSurfaceMessageActionSlots(); const messageMetadataSlots = usePluginSlotKind("messageMetadata"); const onSelectionAddToChat = props.onSelectionAddToChat; const timelineThreadId = props.threadId; const hasPluginSelectionActions = - timelineThreadId !== undefined && - props.includePluginMessageActions !== false && - messageActionSlots.length > 0; + timelineThreadId !== undefined && messageActionSlots.length > 0; const hasSelectionActions = onSelectionAddToChat !== undefined || hasPluginSelectionActions; const [activeSelection, setActiveSelection] = useState<{ @@ -2402,10 +2400,7 @@ function ThreadTimelineRowsForTimelineView(props: ThreadTimelineRowsProps) { } return ( buildRowPluginMessageActions({ - slots: - props.includePluginMessageActions === false - ? EMPTY_PLUGIN_SLOT_SNAPSHOT.messageActions - : messageActionSlots, + slots: messageActionSlots, timelineThreadId, message: activeSelection.message, selectedText: activeSelection.selection.text, @@ -2417,7 +2412,6 @@ function ThreadTimelineRowsForTimelineView(props: ThreadTimelineRowsProps) { activeSelection, composerHost, messageActionSlots, - props.includePluginMessageActions, panel, timelineThreadId, ]); @@ -2431,8 +2425,7 @@ function ThreadTimelineRowsForTimelineView(props: ThreadTimelineRowsProps) { onMessageAddToChat: props.onMessageAddToChat, onSelectionAddToChat: selectionAddToChatHandler, pluginMessageActions: - timelineThreadId === undefined || - props.includePluginMessageActions === false + timelineThreadId === undefined ? EMPTY_PLUGIN_SLOT_SNAPSHOT.messageActions : messageActionSlots, messageMetadata: messageMetadataSlots, @@ -2457,7 +2450,6 @@ function ThreadTimelineRowsForTimelineView(props: ThreadTimelineRowsProps) { selectionAddToChatHandler, messageActionSlots, messageMetadataSlots, - props.includePluginMessageActions, props.consumerMessageActions, reportProseSelection, timelineThreadId, diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineSurface.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineSurface.tsx index 607dc2fbcf6..a63547f5c43 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineSurface.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineSurface.tsx @@ -50,7 +50,6 @@ export interface ThreadTimelineSurfaceProps { onMessageAddToChat?: ThreadTimelineAddToChatHandler; onSelectionAddToChat?: ThreadTimelineAddToChatHandler; consumerMessageActions?: readonly ThreadTimelineConsumerMessageAction[]; - includePluginMessageActions?: boolean; onLoadOlderRows?: () => Promise | void; onTitleAction?: TimelineTitleActionResolver; projectId?: string; @@ -147,7 +146,6 @@ export function ThreadTimelineSurface({ onMessageAddToChat, onSelectionAddToChat, consumerMessageActions, - includePluginMessageActions, onLoadOlderRows, onTitleAction, projectId, @@ -227,7 +225,6 @@ export function ThreadTimelineSurface({ onMessageAddToChat={onMessageAddToChat} onSelectionAddToChat={onSelectionAddToChat} consumerMessageActions={consumerMessageActions} - includePluginMessageActions={includePluginMessageActions} onTitleAction={onTitleAction} projectId={projectId} resolveMentionLink={resolveMentionLink} diff --git a/apps/app/src/components/ui/markdown-preview.tsx b/apps/app/src/components/ui/markdown-preview.tsx index 27331c792dd..b883b7e2d7b 100644 --- a/apps/app/src/components/ui/markdown-preview.tsx +++ b/apps/app/src/components/ui/markdown-preview.tsx @@ -168,6 +168,11 @@ export interface MarkdownThreadMentions { preserveSoftBreaks: boolean; } +export const AUTHORED_MARKDOWN_THREAD_MENTIONS: MarkdownThreadMentions = { + mentions: [], + preserveSoftBreaks: false, +}; + interface MarkdownAnchorProps extends ComponentPropsWithoutRef<"a">, ExtraProps { linkRouting?: MarkdownLinkRouting; diff --git a/apps/app/src/components/ui/markdown-surface-contract.test.tsx b/apps/app/src/components/ui/markdown-surface-contract.test.tsx new file mode 100644 index 00000000000..9bedab0c79c --- /dev/null +++ b/apps/app/src/components/ui/markdown-surface-contract.test.tsx @@ -0,0 +1,149 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { ReactNode } from "react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { LazyPluginMarkdown } from "@/components/plugin/lazy-plugin-renderers"; +import { ThreadTitleMentionResourcesProvider } from "@/components/thread/ThreadTitleMentions"; +import { ConversationMessageContent } from "@/components/thread/timeline/ConversationMessageContent"; +import { ThreadTimelineNavigationProvider } from "@/components/thread/timeline/ThreadTimelineNavigationContext"; +import { RouteNavigationProvider } from "@/components/ui/app-route-anchor"; +import { LazyMarkdownHtml } from "@/components/ui/lazy-markdown-html"; +import { AppNavigationHostProvider } from "@/lib/app-navigation-host"; +import { pluginSdkAppImplementation } from "@/lib/plugin-sdk-app-impl"; + +await Promise.all([LazyMarkdownHtml.preload(), LazyPluginMarkdown.preload()]); + +const THREAD_ID = "thr_markdown"; +const MENTIONED_THREAD = { + id: "thr_1234567890", + projectId: "proj_demo", + title: "Rendering regression", + titleFallback: "Rendering regression", +}; +const CONTENT = + 'Continue in @thread:thr_1234567890 or read [the docs](https://example.com/docs).\n\n'; + +interface MarkdownSurface { + name: string; + render: (content: string) => ReactNode; +} + +const SURFACES: readonly MarkdownSurface[] = [ + { + name: "assistant message", + render: (content) => ( + + ), + }, + { + name: "plugin Markdown", + render: (content) => ( + + ), + }, + { + name: "plugin document Markdown", + render: (content) => ( + + ), + }, +]; + +const queryClient = new QueryClient(); + +function SurfaceHost({ + children, + openUrl, +}: { + children: ReactNode; + openUrl: (intent: { url: string }) => boolean; +}) { + return ( + + + + + + true} + resolveMentionLink={() => null} + threadId={THREAD_ID} + workspaceRootPath="/workspace" + > + {children} + + + + + + + ); +} + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe.each(SURFACES)("Markdown surface contract: $name", (surface) => { + it("renders a thread token as the titled thread mention", async () => { + render( + true}>{surface.render(CONTENT)}, + ); + const link = await screen.findByRole("link", { + name: /Rendering regression/, + }); + expect(link.getAttribute("href")).toBe( + "/projects/proj_demo/threads/thr_1234567890", + ); + }); + + it("opens web links through the surface's navigation host", async () => { + const openUrl = vi.fn(() => true); + render( + {surface.render(CONTENT)}, + ); + fireEvent.click(await screen.findByRole("link", { name: "the docs" })); + expect(openUrl).toHaveBeenCalledWith({ url: "https://example.com/docs" }); + }); + + it("keeps media elements mounted when the navigation host changes", async () => { + const view = render( + true}>{surface.render(CONTENT)}, + ); + const video = await screen.findByLabelText("Clip"); + view.rerender( + false}> + {surface.render(CONTENT)} + , + ); + expect(screen.getByLabelText("Clip")).toBe(video); + }); +}); diff --git a/apps/app/src/lib/app-fixed-tab-navigation.tsx b/apps/app/src/lib/app-fixed-tab-navigation.tsx index 62036062144..00702e6618c 100644 --- a/apps/app/src/lib/app-fixed-tab-navigation.tsx +++ b/apps/app/src/lib/app-fixed-tab-navigation.tsx @@ -1,7 +1,6 @@ import { createContext, useContext, - useEffect, useLayoutEffect, useMemo, useRef, @@ -198,12 +197,9 @@ export function createAppPanelController( }; } -const focusedControllers = new Map(); - -export function useAppPanelController({ - isFocused, - ...surface -}: AppPanelSurface & { isFocused: boolean }): AppPanelController { +export function useAppPanelController( + surface: AppPanelSurface, +): AppPanelController { const surfaceRef = useRef(surface); useLayoutEffect(() => { surfaceRef.current = surface; @@ -214,27 +210,9 @@ export function useAppPanelController({ close: () => closeSurface(surfaceRef.current), ...createAppPanelTabsStore(), })); - useEffect(() => { - if (!isFocused) return; - const token = Symbol("app-panel-controller"); - focusedControllers.set(token, controller); - return () => { - focusedControllers.delete(token); - }; - }, [controller, isFocused]); return controller; } -export function getFocusedAppPanelController(): AppPanelController | null { - let focused: AppPanelController | null = null; - for (const controller of focusedControllers.values()) focused = controller; - return focused; -} - -export function resetFocusedAppPanelControllersForTest(): void { - focusedControllers.clear(); -} - interface AppFixedTabTargetSnapshot { ownerId: string; sequence: number; diff --git a/apps/app/src/lib/app-navigation-host.tsx b/apps/app/src/lib/app-navigation-host.tsx index cc56b2c20d4..1c6de33ec5c 100644 --- a/apps/app/src/lib/app-navigation-host.tsx +++ b/apps/app/src/lib/app-navigation-host.tsx @@ -1,4 +1,13 @@ -import { createContext, useContext, useMemo, type ReactNode } from "react"; +import { + createContext, + useContext, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from "react"; import type { ExperimentalFileOpenOptions, JsonValue, @@ -101,3 +110,84 @@ export function AppNavigationHostProvider({ export function useAppNavigationHost() { return useContext(AppNavigationHostContext); } + +const focusedSurfaces = new Map< + symbol, + { current: ResolvedAppNavigationHostCapabilities } +>(); + +function FocusedSurfaceRegistration({ isFocused }: { isFocused: boolean }) { + const host = useAppNavigationHost(); + const latest = useRef(host); + useLayoutEffect(() => { + latest.current = host; + }); + useEffect(() => { + if (!isFocused) return; + const token = Symbol("app-navigation-surface"); + focusedSurfaces.set(token, latest); + return () => { + focusedSurfaces.delete(token); + }; + }, [isFocused]); + return null; +} + +export function AppNavigationSurfaceProvider({ + capabilities, + isFocused, + children, +}: { + capabilities: AppNavigationHostCapabilities; + isFocused: boolean; + children: ReactNode; +}) { + return ( + + + {children} + + ); +} + +function getFocusedAppNavigationSurface(): ResolvedAppNavigationHostCapabilities | null { + let focused: ResolvedAppNavigationHostCapabilities | null = null; + for (const surface of focusedSurfaces.values()) focused = surface.current; + return focused; +} + +export function getFocusedAppPanelController(): AppPanelController | null { + return getFocusedAppNavigationSurface()?.panel ?? null; +} + +export function resetFocusedAppNavigationSurfacesForTest(): void { + focusedSurfaces.clear(); +} + +export function FocusedAppNavigationSurfaceProvider({ + children, +}: { + children: ReactNode; +}) { + const parent = useAppNavigationHost(); + const latestParent = useRef(parent); + useLayoutEffect(() => { + latestParent.current = parent; + }); + const [capabilities] = useState(() => { + const host = () => getFocusedAppNavigationSurface() ?? latestParent.current; + return { + openFileExternally: (intent: ExperimentalFileOpenOptions) => + host().openFileExternally(intent), + openFilePreview: (intent: AppFilePreviewIntent) => + host().openFilePreview(intent), + openTerminal: (session: TerminalSession) => host().openTerminal(session), + openUrl: (intent: AppUrlOpenIntent) => host().openUrl(intent), + }; + }); + return ( + + {children} + + ); +} diff --git a/apps/app/src/lib/command-palette/palette-plugin-actions.ts b/apps/app/src/lib/command-palette/palette-plugin-actions.ts index daa73e18ed4..4703d0864d4 100644 --- a/apps/app/src/lib/command-palette/palette-plugin-actions.ts +++ b/apps/app/src/lib/command-palette/palette-plugin-actions.ts @@ -1,6 +1,7 @@ import { pluginCommandId, type PluginCommandId } from "@bb/domain"; import type { PluginCommandContext } from "@get-bb/plugin-sdk"; import type { AppPanelController } from "@/lib/app-fixed-tab-navigation"; +import { getFocusedAppPanelController } from "@/lib/app-navigation-host"; import { createPluginPanelController, createRetiredOpenPanel, @@ -100,6 +101,15 @@ export interface BuildPluginComposerCommandActionsArgs { dispatch: (command: PluginCommandId, target: EventTarget | null) => void; } +export function buildFocusedSurfacePaletteActions( + args: Omit, +): PaletteAction[] { + return buildPluginPaletteActions({ + ...args, + panel: getFocusedAppPanelController(), + }); +} + export function buildPluginComposerCommandActions( args: BuildPluginComposerCommandActionsArgs, ): PaletteAction[] { diff --git a/apps/app/src/lib/message-action-surface.tsx b/apps/app/src/lib/message-action-surface.tsx new file mode 100644 index 00000000000..6a8756d91fa --- /dev/null +++ b/apps/app/src/lib/message-action-surface.tsx @@ -0,0 +1,24 @@ +import { createContext, useContext, useMemo } from "react"; +import type { ExperimentalMessageActionSurface } from "@get-bb/plugin-sdk"; +import { + usePluginSlotKind, + type PluginMessageActionSlot, +} from "./plugin-slots"; + +const MessageActionSurfaceContext = + createContext("thread-view"); + +export const MessageActionSurfaceProvider = + MessageActionSurfaceContext.Provider; + +export function useSurfaceMessageActionSlots(): readonly PluginMessageActionSlot[] { + const surface = useContext(MessageActionSurfaceContext); + const slots = usePluginSlotKind("messageActions"); + return useMemo( + () => + slots.every((slot) => slot.experimental_surfaces.includes(surface)) + ? slots + : slots.filter((slot) => slot.experimental_surfaces.includes(surface)), + [slots, surface], + ); +} diff --git a/apps/app/src/lib/plugin-app-definition.test.ts b/apps/app/src/lib/plugin-app-definition.test.ts index 237c56262bd..2d8570c1772 100644 --- a/apps/app/src/lib/plugin-app-definition.test.ts +++ b/apps/app/src/lib/plugin-app-definition.test.ts @@ -805,7 +805,13 @@ describe("collectPluginAppRegistrations", () => { { id: "inline-vis", component: Component }, ]); expect(registrations.messageActions).toEqual([ - { id: "summarize", title: "Summarize", icon: "Zap", run }, + { + id: "summarize", + title: "Summarize", + icon: "Zap", + experimental_surfaces: ["thread-view", "embedded-chat"], + run, + }, ]); expect(registrations.composerCustomizations).toEqual([ { diff --git a/apps/app/src/lib/plugin-slots.test.ts b/apps/app/src/lib/plugin-slots.test.ts index 2ea2a367d25..8b61ed1e1e2 100644 --- a/apps/app/src/lib/plugin-slots.test.ts +++ b/apps/app/src/lib/plugin-slots.test.ts @@ -154,7 +154,14 @@ describe("plugin slot store structural sharing", () => { setPluginSlotRegistrations( "actions", registrationSet({ - messageActions: [{ id: "copy", title: "copy", run: () => {} }], + messageActions: [ + { + id: "copy", + title: "copy", + experimental_surfaces: ["thread-view", "embedded-chat"], + run: () => {}, + }, + ], }), ); const before = getPluginSlotSnapshot(); @@ -197,7 +204,14 @@ describe("plugin slot store structural sharing", () => { setPluginSlotRegistrations( "a", registrationSet({ - messageActions: [{ id: "a-copy", title: "a-copy", run: () => {} }], + messageActions: [ + { + id: "a-copy", + title: "a-copy", + experimental_surfaces: ["thread-view", "embedded-chat"], + run: () => {}, + }, + ], }), ); setPluginSlotRegistrations( @@ -228,13 +242,27 @@ describe("plugin slot batches", () => { setPluginSlotRegistrations( "a", registrationSet({ - messageActions: [{ id: "a", title: "a", run: () => {} }], + messageActions: [ + { + id: "a", + title: "a", + experimental_surfaces: ["thread-view", "embedded-chat"], + run: () => {}, + }, + ], }), ); setPluginSlotRegistrations( "b", registrationSet({ - messageActions: [{ id: "b", title: "b", run: () => {} }], + messageActions: [ + { + id: "b", + title: "b", + experimental_surfaces: ["thread-view", "embedded-chat"], + run: () => {}, + }, + ], }), ); expect(listener).not.toHaveBeenCalled(); @@ -258,7 +286,14 @@ describe("plugin slot batches", () => { setPluginSlotRegistrations( "fast", registrationSet({ - messageActions: [{ id: "fast", title: "fast", run: () => {} }], + messageActions: [ + { + id: "fast", + title: "fast", + experimental_surfaces: ["thread-view", "embedded-chat"], + run: () => {}, + }, + ], }), ); vi.advanceTimersByTime(99); diff --git a/apps/app/src/lib/plugin-slots.ts b/apps/app/src/lib/plugin-slots.ts index 16f6852ceaf..daa649b4924 100644 --- a/apps/app/src/lib/plugin-slots.ts +++ b/apps/app/src/lib/plugin-slots.ts @@ -15,7 +15,6 @@ import type { PluginPendingInteractionRegistration, PluginFileOpenerRegistration, PluginHomepageSectionRegistration, - PluginMessageActionRegistration, ExperimentalMessageMetadataRegistration, PluginMessageDirectiveRegistration, PluginNavPanelRegistration, @@ -39,6 +38,7 @@ import type { } from "@get-bb/plugin-sdk"; import { type CollectedPluginCommandRegistration, + type CollectedPluginMessageActionRegistration, type LegacyThreadPanelActionRegistration, type LegacyThreadHeaderActionRegistration, type LegacyNavPanelRegistration, @@ -83,7 +83,7 @@ export interface PluginRegistrationSet { composers?: readonly ExperimentalComposerRegistration[]; messageDirectives: readonly PluginMessageDirectiveRegistration[]; codeFenceRenderers?: readonly ExperimentalCodeFenceRendererRegistration[]; - messageActions?: readonly PluginMessageActionRegistration[]; + messageActions?: readonly CollectedPluginMessageActionRegistration[]; messageMetadata?: readonly ExperimentalMessageMetadataRegistration[]; commandPaletteActions?: readonly CollectedPluginCommandRegistration[]; providerIcons?: readonly CollectedPluginProviderIconRegistration[]; @@ -176,8 +176,8 @@ export interface PluginMessageDirectiveSlot extends PluginMessageDirectiveRegistration, PluginSlotBase {} export interface PluginCodeFenceRendererSlot extends ExperimentalCodeFenceRendererRegistration, PluginSlotBase {} -export interface PluginMessageActionSlot - extends PluginMessageActionRegistration, PluginSlotBase {} +export type PluginMessageActionSlot = CollectedPluginMessageActionRegistration & + PluginSlotBase; export interface PluginMessageMetadataSlot extends ExperimentalMessageMetadataRegistration, PluginSlotBase {} export type PluginCommandPaletteActionSlot = diff --git a/apps/app/src/lib/thread-actions/thread-action-registry.tsx b/apps/app/src/lib/thread-actions/thread-action-registry.tsx index 87c1480368e..56b27095953 100644 --- a/apps/app/src/lib/thread-actions/thread-action-registry.tsx +++ b/apps/app/src/lib/thread-actions/thread-action-registry.tsx @@ -23,7 +23,10 @@ import type { PluginThreadActionsOptions, } from "@get-bb/plugin-sdk"; import { PluginContext } from "@/components/plugin/plugin-context"; -import { getFocusedAppPanelController } from "@/lib/app-fixed-tab-navigation"; +import { + FocusedAppNavigationSurfaceProvider, + getFocusedAppPanelController, +} from "@/lib/app-navigation-host"; import { createPluginPanelController, createRetiredOpenPanel, @@ -408,13 +411,20 @@ export function ThreadActionCollectors({ setSnapshot({ ...snapshot, requestRename: requestRenameUnavailable }); }; }, []); - return records.map((record) => ( - - - - - - )); + return ( + + {records.map((record) => ( + + + + + + ))} + + ); } function containRun( diff --git a/apps/app/src/test/panel-controller-contract.tsx b/apps/app/src/test/panel-controller-contract.tsx index 3e59e0cc8ce..a2ba0a0cdcc 100644 --- a/apps/app/src/test/panel-controller-contract.tsx +++ b/apps/app/src/test/panel-controller-contract.tsx @@ -1,17 +1,23 @@ import { useLayoutEffect, type ReactNode } from "react"; import { act } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { + BbNavigate, + ExperimentalFilePreviewOptions, ExperimentalOpenTabOptions, ExperimentalPanelController, ExperimentalPanelTabs, ExperimentalTabReference, JsonValue, } from "@get-bb/plugin-sdk"; +import type { TerminalSession } from "@bb/server-contract"; +import { createTerminalFixedPanelTab } from "@bb/client-core"; +import { sdk } from "@/lib/sdk"; +import { useBbNavigate } from "@/lib/plugin-navigation-hooks"; import { - experimental_useAppPanel, - experimental_useFixedTabTarget, - experimental_usePanelTabs, + experimental_useAppPanel as useAppPanel, + experimental_useFixedTabTarget as useFixedTabTarget, + experimental_usePanelTabs as usePanelTabs, } from "@/lib/plugin-sdk-hooks"; import { useFixedPanelTabsState } from "@/lib/fixed-panel-tabs"; import { @@ -37,8 +43,20 @@ interface ContractTab { panelTabId: string; } +export interface PanelContractOpenTargets { + terminal: TerminalSession; + file: ExperimentalFilePreviewOptions; + url: string; +} + +export interface PanelContractNavigation { + navigate: () => BbNavigate; + open: PanelContractOpenTargets; +} + export interface PanelContractSurface { panel: () => ExperimentalPanelController; + navigation: PanelContractNavigation | null; tabs: () => ExperimentalPanelTabs; snapshot: () => PanelContractSnapshot; renderedTarget: () => string | null; @@ -73,7 +91,7 @@ export function ContractTargetedFixedTab({ }: { tab: ExperimentalTabReference & { availability: "fixed" }; }) { - const target = experimental_useFixedTabTarget({ + const target = useFixedTabTarget({ ...tab, experimental_target: contractTarget, }); @@ -97,6 +115,7 @@ export function ContractActionTab({ params }: { params: JsonValue | null }) { export interface ContractPanelRef { current: ExperimentalPanelController | null; tabs?: ExperimentalPanelTabs; + navigate?: BbNavigate; } export function readContractPanel(ref: ContractPanelRef) { @@ -109,9 +128,30 @@ export function readContractTabs(ref: ContractPanelRef) { return ref.tabs; } +export function readContractNavigate(ref: ContractPanelRef) { + if (ref.navigate === undefined) + throw new Error("panel probe has not rendered"); + return ref.navigate; +} + +function recordProbe( + probe: ContractPanelRef, + current: ExperimentalPanelController, + tabs: ExperimentalPanelTabs, + navigate: BbNavigate, +): void { + probe.current = current; + probe.tabs = tabs; + probe.navigate = navigate; +} + export function ContractPanelProbe({ probe }: { probe: ContractPanelRef }) { - probe.current = experimental_useAppPanel(); - probe.tabs = experimental_usePanelTabs(); + const current = useAppPanel(); + const tabs = usePanelTabs(); + const navigate = useBbNavigate(); + useLayoutEffect(() => { + recordProbe(probe, current, tabs, navigate); + }); return null; } @@ -123,6 +163,14 @@ function call(run: () => T): T { return result; } +async function callAsync(run: () => Promise): Promise { + let result!: T; + await act(async () => { + result = await run(); + }); + return result; +} + function openFixed(surface: PanelContractSurface, entry: ContractTab) { return call(() => surface.panel().openTab({ tab: fixedTab(entry) })); } @@ -143,6 +191,8 @@ function actionOptions( export interface PanelContractSupport { fixedTabs: boolean; + actionTabs: boolean; + navigation: boolean; } function required(value: T | null): T { @@ -257,43 +307,53 @@ export function describePanelControllerContract( }, ); - it("focuses the action instance with the same params and opens siblings for different params", async () => { - const surface = await mount(); - const one = surface.action.panelTabId({ n: 1 }); - const two = surface.action.panelTabId({ n: 2 }); - expect( - call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))), - ).toBe(true); - expect( - call(() => surface.panel().openTab(actionOptions(surface, { n: 2 }))), - ).toBe(true); - expect( - call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))), - ).toBe(true); - const snapshot = surface.snapshot(); - expect(snapshot).toMatchObject({ isOpen: true, activeTabId: one }); - expect(snapshot.tabIds.filter((id) => id === one)).toHaveLength(1); - expect(snapshot.tabIds.filter((id) => id === two)).toHaveLength(1); - }); + it.runIf(supports.actionTabs)( + "focuses the action instance with the same params and opens siblings for different params", + async () => { + const surface = await mount(); + const one = surface.action.panelTabId({ n: 1 }); + const two = surface.action.panelTabId({ n: 2 }); + expect( + call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))), + ).toBe(true); + expect( + call(() => surface.panel().openTab(actionOptions(surface, { n: 2 }))), + ).toBe(true); + expect( + call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))), + ).toBe(true); + const snapshot = surface.snapshot(); + expect(snapshot).toMatchObject({ isOpen: true, activeTabId: one }); + expect(snapshot.tabIds.filter((id) => id === one)).toHaveLength(1); + expect(snapshot.tabIds.filter((id) => id === two)).toHaveLength(1); + }, + ); - it("toggles an action tab closed only when the instance with the same params is selected", async () => { - const surface = await mount(); - call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); - call(() => surface.panel().openTab(actionOptions(surface, { n: 2 }))); - expect( - call(() => surface.panel().toggleTab(actionOptions(surface, { n: 1 }))), - ).toBe(true); - expect(surface.snapshot()).toMatchObject({ - isOpen: true, - activeTabId: surface.action.panelTabId({ n: 1 }), - }); - expect( - call(() => surface.panel().toggleTab(actionOptions(surface, { n: 1 }))), - ).toBe(true); - expect(surface.snapshot().isOpen).toBe(false); - }); + it.runIf(supports.actionTabs)( + "toggles an action tab closed only when the instance with the same params is selected", + async () => { + const surface = await mount(); + call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); + call(() => surface.panel().openTab(actionOptions(surface, { n: 2 }))); + expect( + call(() => + surface.panel().toggleTab(actionOptions(surface, { n: 1 })), + ), + ).toBe(true); + expect(surface.snapshot()).toMatchObject({ + isOpen: true, + activeTabId: surface.action.panelTabId({ n: 1 }), + }); + expect( + call(() => + surface.panel().toggleTab(actionOptions(surface, { n: 1 })), + ), + ).toBe(true); + expect(surface.snapshot().isOpen).toBe(false); + }, + ); - it("closes the side panel", async () => { + it.runIf(supports.actionTabs)("closes the side panel", async () => { const surface = await mount(); call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); expect(surface.snapshot().isOpen).toBe(true); @@ -303,7 +363,8 @@ export function describePanelControllerContract( it("declines unknown tabs, wrong contexts and wrong availability without changing state", async () => { const surface = await mount(); - call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); + if (supports.actionTabs) + call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); const before = surface.snapshot(); const declined: ExperimentalOpenTabOptions[] = [ { @@ -329,44 +390,50 @@ export function describePanelControllerContract( expect(surface.snapshot()).toEqual(before); }); - it("lists open tabs and selects or closes them by key, as the tab strip does", async () => { - const surface = await mount(); - call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); - call(() => surface.panel().openTab(actionOptions(surface, { n: 2 }))); - const first = surface.action.panelTabId({ n: 1 }); - const second = surface.action.panelTabId({ n: 2 }); - expect(surface.tabs().selectedKey).toBe(second); - expect(surface.panel().getTabs()).toEqual(surface.tabs()); - expect( - surface.tabs().tabs.find((tab) => tab.key === first), - ).toMatchObject({ - closable: true, - detail: { - kind: "plugin", - pluginId: CONTRACT_PLUGIN_ID, - tab: { ...surface.action.tab, availability: "action" }, - params: { n: 1 }, - }, - }); - - expect(call(() => surface.panel().selectTab(first))).toBe(true); - expect(surface.snapshot().activeTabId).toBe(first); - expect(surface.tabs().selectedKey).toBe(first); - expect(call(() => surface.panel().closeTab(first))).toBe(true); - expect(surface.snapshot().tabIds).not.toContain(first); - expect(surface.tabs().tabs.map((tab) => tab.key)).not.toContain(first); - expect(call(() => surface.panel().selectTab("missing"))).toBe(false); - expect(call(() => surface.panel().closeTab("missing"))).toBe(false); - - call(() => surface.panel().close()); - expect(surface.snapshot().isOpen).toBe(false); - expect(call(() => surface.panel().selectTab(second))).toBe(true); - expect(surface.snapshot()).toMatchObject({ - isOpen: true, - activeTabId: second, - }); - expect(surface.tabs()).toMatchObject({ open: true, selectedKey: second }); - }); + it.runIf(supports.actionTabs)( + "lists open tabs and selects or closes them by key, as the tab strip does", + async () => { + const surface = await mount(); + call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); + call(() => surface.panel().openTab(actionOptions(surface, { n: 2 }))); + const first = surface.action.panelTabId({ n: 1 }); + const second = surface.action.panelTabId({ n: 2 }); + expect(surface.tabs().selectedKey).toBe(second); + expect(surface.panel().getTabs()).toEqual(surface.tabs()); + expect( + surface.tabs().tabs.find((tab) => tab.key === first), + ).toMatchObject({ + closable: true, + detail: { + kind: "plugin", + pluginId: CONTRACT_PLUGIN_ID, + tab: { ...surface.action.tab, availability: "action" }, + params: { n: 1 }, + }, + }); + + expect(call(() => surface.panel().selectTab(first))).toBe(true); + expect(surface.snapshot().activeTabId).toBe(first); + expect(surface.tabs().selectedKey).toBe(first); + expect(call(() => surface.panel().closeTab(first))).toBe(true); + expect(surface.snapshot().tabIds).not.toContain(first); + expect(surface.tabs().tabs.map((tab) => tab.key)).not.toContain(first); + expect(call(() => surface.panel().selectTab("missing"))).toBe(false); + expect(call(() => surface.panel().closeTab("missing"))).toBe(false); + + call(() => surface.panel().close()); + expect(surface.snapshot().isOpen).toBe(false); + expect(call(() => surface.panel().selectTab(second))).toBe(true); + expect(surface.snapshot()).toMatchObject({ + isOpen: true, + activeTabId: second, + }); + expect(surface.tabs()).toMatchObject({ + open: true, + selectedKey: second, + }); + }, + ); it.runIf(supports.fixedTabs)( "lists fixed tabs as selectable but not closable", @@ -402,17 +469,79 @@ export function describePanelControllerContract( }, ); - it("routes the panel.toggle command through the controller", async () => { - const surface = await mount(); - call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); - const active = surface.snapshot().activeTabId; - expect(call(() => surface.command("panel.toggle"))).toBe(true); - expect(surface.snapshot().isOpen).toBe(false); - expect(call(() => surface.command("panel.toggle"))).toBe(true); - expect(surface.snapshot().isOpen).toBe(true); - if (surface.toggleRestoresActiveTab) - expect(surface.snapshot().activeTabId).toBe(active); - }); + it.runIf(supports.navigation)( + "opens a terminal, selects its tab and reveals the closed side panel", + async () => { + const surface = await mount(); + const { navigate, open } = required(surface.navigation); + const session = open.terminal; + vi.spyOn(sdk.terminals, "get").mockResolvedValue(session); + call(() => surface.panel().close()); + expect(surface.snapshot().isOpen).toBe(false); + expect( + await callAsync(() => + navigate().experimental_openTerminal({ terminalId: session.id }), + ), + ).toBe(true); + expect(surface.snapshot()).toMatchObject({ + isOpen: true, + activeTabId: createTerminalFixedPanelTab({ terminalId: session.id }) + .id, + }); + }, + ); + + it.runIf(supports.navigation)( + "opens a file preview, selects its tab and reveals the closed side panel, reusing the tab for the same file", + async () => { + const surface = await mount(); + const { navigate, open } = required(surface.navigation); + call(() => surface.panel().close()); + const before = surface.snapshot(); + expect( + call(() => navigate().experimental_openFilePreview(open.file)), + ).toBe(true); + const opened = surface.snapshot(); + expect(opened.isOpen).toBe(true); + expect(opened.activeTabId).not.toBeNull(); + expect(before.tabIds).not.toContain(opened.activeTabId); + call(() => surface.panel().close()); + expect( + call(() => navigate().experimental_openFilePreview(open.file)), + ).toBe(true); + expect(surface.snapshot()).toEqual(opened); + }, + ); + + it.runIf(supports.navigation)( + "opens a URL in the panel browser and reveals the closed side panel when the in-app browser is available", + async () => { + const surface = await mount(); + const { navigate, open } = required(surface.navigation); + call(() => surface.panel().close()); + const before = surface.snapshot(); + expect(call(() => navigate().openUrl(open.url))).toBe(true); + const opened = surface.snapshot(); + expect(opened.isOpen).toBe(true); + expect(opened.activeTabId).not.toBeNull(); + expect(before.tabIds).not.toContain(opened.activeTabId); + }, + ); + + it.runIf(supports.actionTabs)( + "routes the panel.toggle command through the controller", + async () => { + const surface = await mount(); + call(() => surface.panel().openTab(actionOptions(surface, { n: 1 }))); + const active = surface.snapshot().activeTabId; + expect(call(() => surface.command("panel.toggle"))).toBe(true); + expect(surface.snapshot().isOpen).toBe(false); + expect(call(() => surface.command("panel.toggle"))).toBe(true); + expect(surface.snapshot().isOpen).toBe(true); + if (surface.toggleRestoresActiveTab) + expect(surface.snapshot().activeTabId).toBe(active); + }, + ); }); } diff --git a/apps/app/src/views/RootComposeView.contract.test.tsx b/apps/app/src/views/RootComposeView.contract.test.tsx index 8044762d59d..a5c6f6896a6 100644 --- a/apps/app/src/views/RootComposeView.contract.test.tsx +++ b/apps/app/src/views/RootComposeView.contract.test.tsx @@ -19,8 +19,8 @@ import { } from "@/lib/plugin-app-definition"; import { getFocusedAppPanelController, - resetFocusedAppPanelControllersForTest, -} from "@/lib/app-fixed-tab-navigation"; + resetFocusedAppNavigationSurfacesForTest, +} from "@/lib/app-navigation-host"; import { createPluginPanelController } from "@/lib/plugin-panel-controller"; import { DefaultPaneContextProvider } from "@/views/thread-detail/PaneContext"; import { ROOT_COMPOSE_FIXED_PANEL_STATE_ID } from "@/views/RootComposePanelTabContent"; @@ -30,11 +30,18 @@ import { ContractStateProbe, contractActionPanelTabId, describePanelControllerContract, + readContractNavigate, snapshotFromState, type ContractStateSink, } from "@/test/panel-controller-contract"; +import { makeTerminalSession } from "@/test/fixtures/terminal-sessions"; import { RootComposeView } from "./RootComposeView"; +const probe = vi.hoisted( + (): import("@/test/panel-controller-contract").ContractPanelRef => ({ + current: null, + }), +); const appCommandHandlers = vi.hoisted( () => new Map boolean | void>(), ); @@ -73,9 +80,20 @@ vi.mock("@/views/RootComposeSecondaryContent", async () => { ), }; }); -vi.mock("@/components/promptbox/NewThreadPromptBox", () => ({ - NewThreadPromptBox: () =>
, -})); +vi.mock("@/components/promptbox/NewThreadPromptBox", async () => { + const { PluginContext } = await import("@/components/plugin/plugin-context"); + const { ContractPanelProbe, CONTRACT_PLUGIN_ID } = + await import("@/test/panel-controller-contract"); + return { + NewThreadPromptBox: () => ( +
+ + + +
+ ), + }; +}); vi.mock("@/hooks/queries/thread-terminal-queries", async (importOriginal) => ({ ...(await importOriginal< typeof import("@/hooks/queries/thread-terminal-queries") @@ -93,13 +111,19 @@ vi.mock("@/hooks/queries/machine-provider-queries", () => ({ vi.mock("@/hooks/queries/plugin-settings-queries", () => ({ usePluginList: () => ({ data: { plugins: [] } }), })); -vi.mock("@/lib/sdk", () => ({ +vi.mock("@/lib/sdk", async (importOriginal) => ({ + ...(await importOriginal()), sdk: { system: { experimental_recordTelemetryEvent: vi.fn().mockResolvedValue(undefined), }, + terminals: { get: vi.fn() }, }, })); +vi.mock("@/lib/bb-desktop", async (importOriginal) => ({ + ...(await importOriginal()), + isDesktopBrowserAvailable: () => true, +})); vi.mock("@/hooks/queries/sidebar-navigation-query", () => ({ useSidebarNavigation: () => ({ data: { @@ -123,7 +147,7 @@ vi.mock("@/hooks/queries/sidebar-navigation-query", () => ({ vi.mock("@/hooks/queries/host-queries", () => ({ useHosts: () => ({ data: [] }), selectHosts: (hosts: T[] | undefined) => hosts ?? [], - selectPrimaryHost: () => null, + selectPrimaryHost: () => ({ id: "host_contract" }), })); vi.mock("@/hooks/queries/system-queries", () => ({ useSystemProviders: () => ({ data: undefined }), @@ -132,7 +156,10 @@ vi.mock("@/hooks/queries/system-queries", () => ({ useKnownProviderModelCatalogScope: () => undefined, useHostProviderCliStatus: () => ({ data: undefined }), useSystemConfig: () => ({ - data: { primaryHostId: null, generalSettings: defaultAppSettings }, + data: { + primaryHostId: "host_contract", + generalSettings: defaultAppSettings, + }, }), useSystemExecutionOptions: () => ({ data: undefined, @@ -141,7 +168,10 @@ vi.mock("@/hooks/queries/system-queries", () => ({ isPlaceholderData: false, }), })); -vi.mock("@/hooks/queries/thread-panel-queries", () => ({ +vi.mock("@/hooks/queries/thread-panel-queries", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("@/hooks/queries/thread-panel-queries") + >()), useThreadStorageFiles: () => ({ data: undefined, error: null, @@ -188,6 +218,7 @@ vi.mock("@/components/dialogs/ProjectMachineSetupDialog", () => ({ })); const NO_TABS = { open: false, selectedKey: null, tabs: [] }; +const CONTRACT_HOST_ID = "host_contract"; const actionTab = { id: "chat", @@ -217,12 +248,12 @@ beforeEach(() => { afterEach(() => { cleanup(); resetPluginSlotStoreForTest(); - resetFocusedAppPanelControllersForTest(); + resetFocusedAppNavigationSurfacesForTest(); }); describePanelControllerContract( "New thread screen", - { fixedTabs: false }, + { fixedTabs: false, actionTabs: true, navigation: true }, async () => { const sink: ContractStateSink = { current: null }; const router = createMemoryRouter( @@ -266,6 +297,22 @@ describePanelControllerContract( ); return { panel: () => panel, + navigation: { + navigate: () => readContractNavigate(probe), + open: { + terminal: makeTerminalSession({ + id: "term_contract", + threadId: null, + environmentId: null, + hostId: CONTRACT_HOST_ID, + }), + file: { + target: { kind: "host", hostId: CONTRACT_HOST_ID, path: "/a.md" }, + location: null, + }, + url: "https://example.com/contract", + }, + }, snapshot: () => snapshotFromState(sink), tabs: () => getFocusedAppPanelController()?.getTabs() ?? NO_TABS, renderedTarget: () => null, diff --git a/apps/app/src/views/RootComposeView.tsx b/apps/app/src/views/RootComposeView.tsx index 2e5e52a90b4..5b4ad49d41f 100644 --- a/apps/app/src/views/RootComposeView.tsx +++ b/apps/app/src/views/RootComposeView.tsx @@ -116,7 +116,7 @@ import { } from "@/lib/fixed-panel-tabs"; import type { MarkdownPreviewLinkHandler } from "@/components/ui/markdown-link"; import { UrlOpenRoutingProvider } from "@/lib/url-open-routing"; -import { AppNavigationHostProvider } from "@/lib/app-navigation-host"; +import { AppNavigationSurfaceProvider } from "@/lib/app-navigation-host"; import { useAppPanelController } from "@/lib/app-fixed-tab-navigation"; import { useRootComposeProjectId } from "@/lib/root-compose-selection"; import { @@ -957,7 +957,6 @@ function RootComposeSurface({ activeTabId: isSecondaryPanelOpen ? activeFixedSecondaryTabId : null, close: closeWorkspacePanel, destinations: panelDestinations, - isFocused: isFocusedPane, }); const rootPluginPanelActions = usePluginNewThreadPanelActions({ panel, @@ -1422,7 +1421,10 @@ function RootComposeSurface({ - + {promptBox} - + diff --git a/apps/app/src/views/ToolsView.plugin-detail.test.tsx b/apps/app/src/views/ToolsView.plugin-detail.test.tsx index 3585eadd690..c778a4b6223 100644 --- a/apps/app/src/views/ToolsView.plugin-detail.test.tsx +++ b/apps/app/src/views/ToolsView.plugin-detail.test.tsx @@ -59,7 +59,9 @@ import { } from "@/components/commands/AppCommandProvider"; import { getFixedPanelTabsStateStorageKey } from "@bb/client-core"; import { resetFixedPanelTabsStateForTest } from "@/lib/fixed-panel-tabs"; -import { getFocusedAppPanelController } from "@/lib/app-fixed-tab-navigation"; +import { getFocusedAppPanelController } from "@/lib/app-navigation-host"; +import { createPluginPanelController } from "@/lib/plugin-panel-controller"; +import type { ExperimentalOpenTabOptions } from "@get-bb/plugin-sdk"; import { createBbDesktopApi } from "@/test/bb-desktop-test-utils"; import type { BbDesktopCloseWindowRequestHandler } from "@bb/desktop-contract"; @@ -2711,3 +2713,64 @@ describe("plugin detail source and settings", () => { ); }); }); + +describe("Plugins view panel controller", () => { + it("gives plugin commands a panel that declines plugin tabs without changing the view's tabs", async () => { + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url === "/api/v1/plugins") { + return Response.json({ enabled: true, plugins: [] }); + } + if (url.startsWith("/api/v1/plugin-catalog/search")) { + return Response.json({ results: [], collections: [] }); + } + return Response.json({ error: "not found" }, { status: 404 }); + }), + ); + renderWithQueryClient( + + + + + + + , + ); + await waitFor(() => expect(getFocusedAppPanelController()).not.toBeNull()); + const panel = createPluginPanelController( + "contract", + getFocusedAppPanelController, + ); + const before = panel.getTabs(); + const declined: ExperimentalOpenTabOptions[] = [ + { + tab: { + id: "probe", + context: { kind: "thread" }, + availability: "action", + }, + }, + { + tab: { + id: "probe", + context: { kind: "thread" }, + availability: "fixed", + }, + }, + { + tab: { + id: "probe", + context: { kind: "nav-panel", panelId: "plugins" }, + availability: "action", + }, + }, + ]; + for (const options of declined) { + expect(panel.openTab(options)).toBe(false); + expect(panel.toggleTab(options)).toBe(false); + } + expect(panel.getTabs()).toEqual(before); + }); +}); diff --git a/apps/app/src/views/ToolsView.tsx b/apps/app/src/views/ToolsView.tsx index d95c786b821..866fc10cb7b 100644 --- a/apps/app/src/views/ToolsView.tsx +++ b/apps/app/src/views/ToolsView.tsx @@ -1,5 +1,5 @@ import { AppPanelTabsPublisher } from "@/lib/app-panel-tabs"; -import { AppNavigationHostProvider } from "@/lib/app-navigation-host"; +import { AppNavigationSurfaceProvider } from "@/lib/app-navigation-host"; import { useAppPanelController, type AppFixedTabDestination, @@ -658,7 +658,6 @@ export function PluginsView({ detailKey }: { detailKey?: string } = {}) { activeTabId: isPanelOpen ? (activeTab?.id ?? null) : null, close: closePanel, destinations: NO_PANEL_DESTINATIONS, - isFocused: paneContext?.isFocused ?? true, }); const navigationCapabilities = useMemo( () => ({ panel: panelController }), @@ -701,7 +700,10 @@ export function PluginsView({ detailKey }: { detailKey?: string } = {}) { ); return ( - +
- + ); } diff --git a/apps/app/src/views/thread-detail/SplitThreadArea.test.tsx b/apps/app/src/views/thread-detail/SplitThreadArea.test.tsx index df6c16e7f79..0bf3579d817 100644 --- a/apps/app/src/views/thread-detail/SplitThreadArea.test.tsx +++ b/apps/app/src/views/thread-detail/SplitThreadArea.test.tsx @@ -3415,3 +3415,84 @@ describe("SplitThreadArea compact breakpoint crossings", () => { expect(paneMounts.get("new-thread")).toBe(1); }); }); + +function UnsavedPluginForm() { + const [value, setValue] = useState(""); + return ( + setValue(event.target.value)} + /> + ); +} + +describe("SplitThreadArea single-pane breakpoint contract", () => { + const SINGLE_PANE_SURFACES: ReadonlyArray<{ + name: string; + path: string; + content: PaneContent; + rootTestId: string; + }> = [ + { + name: "thread", + path: threadPath("thr-a"), + content: threadContent("thr-a"), + rootTestId: "pane-thr-a", + }, + { + name: "new thread", + path: "/", + content: newThreadContent, + rootTestId: "root-compose-view", + }, + { + name: "plugin navigation panel", + path: "/plugins/docs/docs", + content: docsContent, + rootTestId: "plugin-browser-host", + }, + ]; + + it.each(SINGLE_PANE_SURFACES)( + "keeps a single $name pane mounted across compact breakpoint crossings", + async ({ path, content, rootTestId }) => { + setPluginSlotRegistrations( + "docs", + makePluginRegistrationSet({ + navPanels: [ + { + id: "docs", + title: "Docs", + icon: "FileText", + path: "docs", + component: UnsavedPluginForm, + }, + ], + }), + ); + renderSplitArea({ + path, + layout: { + root: { type: "pane", paneId: "pane-1", content }, + focusedPaneId: "pane-1", + }, + routeAwareContent: true, + }); + const root = await screen.findByTestId(rootTestId); + const input = screen.queryByTestId("plugin-form-input"); + expect(input !== null).toBe(content.kind === "plugin-panel"); + if (input !== null) + fireEvent.change(input, { target: { value: "unsaved plugin form" } }); + + for (const compact of [true, false, true, false]) { + setCompactViewport(compact); + expect(screen.getByTestId(rootTestId)).toBe(root); + if (input !== null) { + expect(screen.getByTestId("plugin-form-input")).toBe(input); + expect(input.value).toBe("unsaved plugin form"); + } + } + }, + ); +}); diff --git a/apps/app/src/views/thread-detail/SplitThreadArea.tsx b/apps/app/src/views/thread-detail/SplitThreadArea.tsx index 0b4d5a21df2..6ba1609e20b 100644 --- a/apps/app/src/views/thread-detail/SplitThreadArea.tsx +++ b/apps/app/src/views/thread-detail/SplitThreadArea.tsx @@ -722,10 +722,7 @@ function SplitThreadAreaContent({ routeContent }: SplitThreadAreaProps) { const firstPane = panes[0]; const singlePane = panes.length === 1 && firstPane !== undefined ? firstPane : null; - const keepsSinglePane = - singlePane !== null && - (currentContent.kind === "thread" || currentContent.kind === "new-thread"); - if (!splitWorkspaceActive && !keepsSinglePane) { + if (!splitWorkspaceActive && singlePane === null) { return ( ({ probe: { current: null, } as import("@/test/panel-controller-contract").ContractPanelRef, - probeHost: "prompt" as "prompt" | "headerRow", + probeHost: "prompt" as + | "prompt" + | "headerRow" + | "threadAction" + | "messageAction" + | "paletteCommand" + | "newTabAction", sink: { current: null, } as import("@/test/panel-controller-contract").ContractStateSink, @@ -75,7 +95,12 @@ const ENVIRONMENT = makeEnvironment({ id: "env_contract", projectId: "proj_contract", }); +const THREAD_ACTION_TARGET = toThreadActionTarget(THREAD, null); +vi.mock("@/lib/bb-desktop", async (importOriginal) => ({ + ...(await importOriginal()), + isDesktopBrowserAvailable: () => true, +})); vi.mock("@/components/commands/AppCommandProvider", async (importOriginal) => ({ ...(await importOriginal< typeof import("@/components/commands/AppCommandProvider") @@ -119,12 +144,29 @@ vi.mock("./ThreadDetailPromptArea", async () => { const { PluginContext } = await import("@/components/plugin/plugin-context"); const { ContractPanelProbe } = await import("@/test/panel-controller-contract"); + const { ThreadTimelineRows } = + await import("@/components/thread/timeline/ThreadTimelineRows"); + const { conversationRow } = + await import("@/test/fixtures/thread-timeline-rows"); return { ThreadDetailPromptArea: () => fixtures.probeHost === "prompt" ? ( + ) : fixtures.probeHost === "messageAction" ? ( + ) : null, }; }); @@ -166,23 +208,29 @@ async function mountThreadView( { path: "/", element: ( - {}} - > - + undefined} /> - - + {}} + > + + + + ), }, ], @@ -208,10 +256,75 @@ async function mountThreadView( ]), ), ); + if (probeHost === "threadAction") + await waitFor(() => expect(probe.current).not.toBeNull()); + if (probeHost === "messageAction") { + fireEvent.click( + await screen.findByRole("button", { name: "Probe message" }), + ); + await waitFor(() => expect(probe.current).not.toBeNull()); + } + if (probeHost === "paletteCommand") { + await waitFor(() => expect(getFocusedAppPanelController()).not.toBeNull()); + const [command] = buildFocusedSurfacePaletteActions({ + slots: getPluginSlotSnapshot().commandPaletteActions.flatMap((slot) => + slot.pluginId === CONTRACT_PLUGIN_ID && slot.target === "app" + ? [slot] + : [], + ), + threadId: THREAD.id, + projectId: THREAD.projectId, + }); + act(() => command?.run()); + expect(probe.current).not.toBeNull(); + } + if (probeHost === "newTabAction") { + act(() => { + appCommandHandlers.get("file.quickOpen")?.(); + }); + await waitFor(() => + expect( + document.getElementById("plugin-action:contract:launcher"), + ).not.toBeNull(), + ); + fireEvent.click( + document.getElementById("plugin-action:contract:launcher")!, + ); + await waitFor(() => expect(probe.current).not.toBeNull()); + } + const exposesNavigation = + probeHost === "prompt" || + probeHost === "headerRow" || + probeHost === "threadAction"; return { panel: () => readContractPanel(probe), + navigation: exposesNavigation + ? { + navigate: () => readContractNavigate(probe), + open: { + terminal: makeTerminalSession({ + id: "term_contract", + threadId: THREAD.id, + environmentId: ENVIRONMENT.id, + hostId: ENVIRONMENT.hostId, + }), + file: { + target: { + kind: "thread-storage", + threadId: THREAD.id, + path: "a.md", + }, + location: null, + }, + url: "https://example.com/contract", + }, + } + : null, snapshot: () => snapshotFromState(sink), - tabs: () => readContractTabs(probe), + tabs: () => + probeHost === "prompt" || probeHost === "headerRow" + ? readContractTabs(probe) + : readContractPanel(probe).getTabs(), renderedTabVisible: () => screen.queryByTestId("contract-tab-visible")?.textContent ?? null, renderedTarget: () => @@ -234,20 +347,56 @@ async function mountThreadView( }; } -describePanelControllerContract("thread view", { fixedTabs: true }, () => +const FULL_SUPPORT = { + fixedTabs: true, + actionTabs: true, + navigation: true, +} as const; +const PANEL_ONLY_SUPPORT = { ...FULL_SUPPORT, navigation: false } as const; + +describePanelControllerContract("thread view", FULL_SUPPORT, () => mountThreadView("prompt"), ); -describePanelControllerContract("thread header row", { fixedTabs: true }, () => +describePanelControllerContract("thread header row", FULL_SUPPORT, () => mountThreadView("headerRow"), ); +describePanelControllerContract("thread header action", FULL_SUPPORT, () => + mountThreadView("threadAction"), +); + +describePanelControllerContract( + "thread message action", + PANEL_ONLY_SUPPORT, + () => mountThreadView("messageAction"), +); + +describePanelControllerContract( + "command palette command on a thread", + PANEL_ONLY_SUPPORT, + () => mountThreadView("paletteCommand"), +); + +describePanelControllerContract( + "thread new-tab plugin action", + PANEL_ONLY_SUPPORT, + () => mountThreadView("newTabAction"), +); + function HeaderRowProbe() { return fixtures.probeHost === "headerRow" ? ( + ) : fixtures.probeHost === "threadAction" ? ( + ) : null; } +function ThreadActionProbe() { + useThreadHeaderActionEntries(THREAD_ACTION_TARGET); + return null; +} + const targetedTab = { id: "summary", context: { kind: "thread" }, @@ -297,6 +446,50 @@ beforeEach(() => { id: "probe", component: HeaderRowProbe, }); + app.slots.messageAction({ + id: "probe-message", + title: "Probe message", + icon: "Zap", + run: ({ experimental_panel }) => { + if (fixtures.probeHost === "messageAction") + fixtures.probe.current = experimental_panel; + }, + }); + app.commands.register({ + id: "probe-command", + title: "Probe command", + run: ({ experimental_panel }) => { + if (fixtures.probeHost === "paletteCommand") + fixtures.probe.current = experimental_panel; + }, + }); + app.slots.experimental_tab({ + id: "launcher", + context: { kind: "thread" }, + availability: "action", + title: "Launcher", + icon: "Zap", + component: ContractActionTab, + run: ({ experimental_panel }) => { + if (fixtures.probeHost === "newTabAction") + fixtures.probe.current = experimental_panel; + }, + }); + app.slots.experimental_threadAction({ + id: "probe", + title: "Probe", + icon: "Info", + group: "probe", + placement: "header", + item: ({ navigate, experimental_panel }) => { + if (fixtures.probeHost === "threadAction") { + fixtures.probe.current = experimental_panel; + fixtures.probe.tabs = undefined; + fixtures.probe.navigate = navigate; + } + return null; + }, + }); }), ), ); @@ -304,8 +497,10 @@ beforeEach(() => { afterEach(() => { cleanup(); + vi.restoreAllMocks(); + resetThreadActionRegistryForTest(); resetPluginSlotStoreForTest(); - resetFocusedAppPanelControllersForTest(); + resetFocusedAppNavigationSurfacesForTest(); }); describe("experimental_threadHeaderRow", () => { diff --git a/apps/app/src/views/thread-detail/ThreadDetailView.tsx b/apps/app/src/views/thread-detail/ThreadDetailView.tsx index d908b2f1b75..269047a2f6e 100644 --- a/apps/app/src/views/thread-detail/ThreadDetailView.tsx +++ b/apps/app/src/views/thread-detail/ThreadDetailView.tsx @@ -1,6 +1,5 @@ import { AppPanelTabsPublisher } from "@/lib/app-panel-tabs"; import { - getThreadFixedTabOwnerId, useAppPanelController, useSetFixedTabTarget, } from "@/lib/app-fixed-tab-navigation"; @@ -10,7 +9,6 @@ import { usePluginPanelActions, } from "@/components/plugin/PluginPanelActions"; import { useAppCommandHandler } from "@/components/commands/AppCommandProvider"; -import { GIT_DIFF_TAB_REFERENCE } from "@/lib/git-diff-tab"; import { useEnvironmentCheckoutDisplay } from "@/hooks/queries/git-plugin-queries"; import { useThreadFixedTabs, @@ -34,10 +32,10 @@ import { useImmediateRouteNavigate } from "@/components/ui/app-route-anchor"; import { useAtom } from "jotai"; import { useDesktopBrowserReveal } from "@/lib/use-desktop-browser-reveal"; import { + type ThreadTimelineConsumerMessageAction, type ThreadTimelineForkMessageHandler, type ThreadTimelineLinkHandler, type ThreadTimelineLocalFileLink, - type TimelineTitleActionResolver, } from "@/components/thread/timeline"; import { ThreadProviderContext } from "@/components/thread/thread-provider-context"; import { type ThreadListEntry } from "@bb/domain"; @@ -76,7 +74,6 @@ import { formatEnvironmentDisplay, type EnvironmentDisplayHostContext, } from "@bb/core-ui"; -import { assertNever } from "@bb/thread-view"; import { useCreateThreadInEnvironment } from "@/hooks/useCreateThreadInEnvironment"; import { useHostDaemon } from "@/hooks/useHostDaemon"; import { useLiveFileOpenTargets } from "@/hooks/useLiveFileOpenTargets"; @@ -136,13 +133,13 @@ import { LazyThreadTerminalPanel, LazyWorkspaceFilePreviewTabContent, } from "@/components/secondary-panel/lazySecondaryPanelComponents"; -import { - SIDE_CHAT_PLUGIN_ID, - SIDE_CHAT_PLUGIN_PANEL_ACTION_ID, -} from "@/lib/side-chat-plugin"; import { usePanelTabPresenter } from "@/components/secondary-panel/usePanelTabPresenter"; import { createFileOpenerOriginalTab } from "@/components/plugin/file-opener-tabs"; import { ThreadTimelineNavigationProvider } from "@/components/thread/timeline/ThreadTimelineNavigationContext"; +import { + resolveThreadEnvironmentAccess, + useThreadTimelineTitleActions, +} from "./thread-screen-hosts"; import { AttachmentOpenerContext, type OpenAttachmentRequest, @@ -154,7 +151,7 @@ import { Icon } from "@bb/shared-ui/icon"; import { getBbDesktopInfo, isDesktopBrowserAvailable } from "@/lib/bb-desktop"; import { UrlOpenRoutingProvider } from "@/lib/url-open-routing"; import { - AppNavigationHostProvider, + AppNavigationSurfaceProvider, useAppNavigationHost, } from "@/lib/app-navigation-host"; import { getFileBasename } from "@/lib/live-file-navigation"; @@ -200,7 +197,6 @@ import { useUpdateFixedPanelTabsState, } from "@/lib/fixed-panel-tabs"; import type { SecondaryFileFixedPanelTab } from "@/lib/fixed-panel-tabs-state"; -import { resolveGitDiffTabStatus } from "@/components/secondary-panel/gitDiffTabEligibility"; import { isRootThread } from "./threadParentSelectorOptions"; import { useIsCompactViewport } from "@bb/shared-ui/hooks/use-compact-viewport"; import { usePointerCoarse } from "@bb/shared-ui/hooks/use-pointer-coarse"; @@ -219,6 +215,8 @@ const EMPTY_PROJECT_THREAD_SUBSET_FILTERS = const EMPTY_TERMINAL_SESSIONS: readonly TerminalSession[] = []; const THREAD_HEADER_ACTIONS_GROUP = "0_header"; const THREAD_DETAIL_SCREEN_PRESENTATION = { kind: "page" } as const; +const NO_CONSUMER_MESSAGE_ACTIONS: readonly ThreadTimelineConsumerMessageAction[] = + []; type OpenFilePreviewHandler = (relativePath: string) => void; @@ -304,25 +302,16 @@ function ThreadDetailViewInternal( staleTime: 5_000, }); const environment = environmentQuery.data; - const hostLifecycle = - environment === undefined || environment.hostLifecycle === "active" - ? null - : environment.hostLifecycle; - const executionUnavailable = - hostLifecycle !== null || environment?.status === "destroyed"; - const gitDiffTabStatus = resolveGitDiffTabStatus({ - environmentId: thread?.environmentId ?? null, - environmentIsGitRepo: environment?.isGitRepo, + const { + executionUnavailable, + gitDiffTabStatus, + contextEnvironmentId: threadEnvironmentId, + reusesEnvironment, + } = resolveThreadEnvironmentAccess({ + thread: thread ?? null, + environment: environment ?? null, environmentLoadFailed: environmentQuery.isError, - environmentOwnsPath: environment?.managed, - hasResolvedThread: thread !== undefined, - threadArchived: thread?.archivedAt != null || executionUnavailable, }); - const canUseGitUi = !executionUnavailable && gitDiffTabStatus === "eligible"; - const threadEnvironmentId = - canUseGitUi && environment !== undefined && thread?.environmentId - ? thread.environmentId - : null; const threadTabEnvironmentId = thread?.environmentId ?? null; const threadTabEnvironment = useMemo( () => @@ -753,7 +742,6 @@ function ThreadDetailViewInternal( activeTabId: isSecondaryPanelOpen ? activeFixedSecondaryTabId : null, close: closeWorkspacePanel, destinations: panelDestinations, - isFocused, }); const toggleSecondaryPanel = useCallback(() => { if (isSecondaryPanelOpen) panel.close(); @@ -773,15 +761,6 @@ function ThreadDetailViewInternal( }), [panel], ); - const openSecondaryPanelDiffFile = useCallback( - (path: string) => - panel.openTab({ - tab: GIT_DIFF_TAB_REFERENCE, - availability: "fixed", - target: { kind: "file", path }, - }), - [panel], - ); const handleSelectFileSearchResult = useCallback( (selection: FileSearchSelection) => { @@ -1107,51 +1086,15 @@ function ThreadDetailViewInternal( ({ href }) => openBrowserUrl(href), [openBrowserUrl], ); - const handleTimelineTitleAction = useCallback( - (action) => { - switch (action.kind) { - case "open-file-diff": - return () => { - if (openSecondaryPanelDiffFile(action.path)) return; - const environmentId = thread?.environmentId; - if (environmentId === null || environmentId === undefined) return; - openLiveFilePreview({ - target: { kind: "workspace", environmentId, path: action.path }, - location: null, - }); - }; - case "open-local-file": - return () => { - handleOpenTimelineLocalFileLink({ - lineRange: null, - openTargetId: null, - path: action.path, - }); - }; - case "open-plugin-side-chat": - return () => { - panel.openTab({ - tab: { - ownerId: getThreadFixedTabOwnerId(SIDE_CHAT_PLUGIN_ID), - tabId: SIDE_CHAT_PLUGIN_PANEL_ACTION_ID, - }, - availability: "action", - params: { threadId: action.threadId, sourceThreadId: threadId }, - }); - }; - default: - return assertNever(action); - } - }, - [ - handleOpenTimelineLocalFileLink, - openLiveFilePreview, - openSecondaryPanelDiffFile, - panel, - thread?.environmentId, - threadId, - ], - ); + const handleTimelineTitleAction = useThreadTimelineTitleActions({ + threadId, + projectId, + openThread: navigateInPane, + environmentId: thread?.environmentId ?? null, + panel, + openFilePreview: openLiveFilePreview, + openLocalFileLink: handleOpenTimelineLocalFileLink, + }); const metadataStorage = useMemo( () => resolvedThreadEnvironmentHost?.status === "connected" @@ -1403,15 +1346,8 @@ function ThreadDetailViewInternal( machineProviders: registeredMachineProviders, }) : undefined; - const isThreadOnReusableEnvironment = - !executionUnavailable && - environment !== undefined && - environment.status === "ready" && - environment.path !== null; const onCreateNewThreadInEnvironment = - isThreadOnReusableEnvironment && projectId && thread.environmentId !== null - ? createThreadInEnvironment - : undefined; + reusesEnvironment && projectId ? createThreadInEnvironment : null; const threadTitle = getThreadDisplayTitle(thread); const responsiveWorkspaceActions: PluginThreadActionsInlineItem[] = workspaceOpenPath && preferredDirectoryTarget @@ -1446,7 +1382,9 @@ function ThreadDetailViewInternal( : []; const threadActionTarget = toThreadActionTarget( thread, - isThreadOnReusableEnvironment && thread.environmentId !== null + reusesEnvironment && + thread.environmentId !== null && + environment?.path != null ? { id: thread.environmentId, path: environment.path } : null, ); @@ -1552,6 +1490,7 @@ function ThreadDetailViewInternal( environmentCheckout: threadCheckoutDisplay, environmentChrome: composerEnvironmentChrome, contextEnvironmentId: threadEnvironmentId, + focusRequest: null, onCreateNewThreadInEnvironment, onOpenThreadInfo: openThreadInfo, permissionPolicy: "editable", @@ -1564,8 +1503,10 @@ function ThreadDetailViewInternal( timelineEnabled={timelineEnabled} timelineHost={{ environmentHostName: threadEnvironmentHost?.name ?? null, - includePluginMessageActions: true, - onForkMessage: isForkAvailable ? handleForkMessage : undefined, + consumerMessageActions: NO_CONSUMER_MESSAGE_ACTIONS, + leadingContent: null, + messageActionSurface: "thread-view", + onForkMessage: isForkAvailable ? handleForkMessage : null, onTitleAction: handleTimelineTitleAction, unreadDividerAutoScroll: unreadDividerState.autoScroll, unreadDividerPlacement: unreadDividerState.placement, @@ -1735,7 +1676,10 @@ function ThreadDetailViewInternal( workspaceRootPath={environment?.path ?? undefined} > - + - + diff --git a/apps/app/src/views/thread-detail/ThreadScreen.surface-contract.test.tsx b/apps/app/src/views/thread-detail/ThreadScreen.surface-contract.test.tsx new file mode 100644 index 00000000000..684716eaadd --- /dev/null +++ b/apps/app/src/views/thread-detail/ThreadScreen.surface-contract.test.tsx @@ -0,0 +1,415 @@ +// @vitest-environment jsdom + +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import type { ExperimentalMessageActionSurface } from "@get-bb/plugin-sdk"; +import { Provider } from "jotai"; +import type { ReactNode } from "react"; +import { MemoryRouter } from "react-router-dom"; +import { + afterEach, + beforeEach, + describe, + expect, + it, + vi, + type Mock, +} from "vitest"; +import { makeEnvironment } from "@bb/test-helpers/domain-fixtures"; +import type { UseThreadTimelineControllerResult } from "@/components/thread/timeline"; +import { LazyPluginThreadChat } from "@/components/plugin/LazyPluginThreadChat"; +import { PluginSlotMount } from "@/components/plugin/PluginSlotMount"; +import { + AppNavigationHostProvider, + type AppFilePreviewIntent, +} from "@/lib/app-navigation-host"; +import { resetFixedPanelTabsStateForTest } from "@/lib/fixed-panel-tabs"; +import { markPluginFrontendsSettled } from "@/lib/plugin-frontend-boot-state"; +import { pluginSdkAppImplementation } from "@/lib/plugin-sdk-app-impl"; +import { + resetPluginSlotStoreForTest, + setPluginSlotRegistrations, +} from "@/lib/plugin-slots"; +import { sdk } from "@/lib/sdk"; +import { makePluginRegistrationSet } from "@/test/fixtures/plugins"; +import { makeThreadResponse } from "@/test/fixtures/thread-responses"; +import { + conversationRow, + fileChangeRow, +} from "@/test/fixtures/thread-timeline-rows"; +import { + ContractStateProbe, + snapshotFromState, + type ContractStateSink, +} from "@/test/panel-controller-contract"; +import { createQueryClientTestHarness } from "@/test/queryClientTestHarness"; +import { DefaultPaneContextProvider } from "./PaneContext"; +import { ThreadDetailView } from "./ThreadDetailView"; + +await LazyPluginThreadChat.preload(); + +const mocks = vi.hoisted(() => ({ + promptAreaProps: [] as Array>, +})); + +const ENVIRONMENT = makeEnvironment({ + id: "env_surface", + projectId: "proj_surface", + status: "ready", + isGitRepo: true, + path: "/workspace", +}); + +const THREAD = makeThreadResponse({ + id: "thr_surface", + projectId: "proj_surface", + environmentId: ENVIRONMENT.id, + status: "idle", + runtime: { displayStatus: "idle" }, +}); + +const CONTEXT_WINDOW_USAGE = { + usedTokens: 1200, + maxTokens: 200000, +} as unknown as UseThreadTimelineControllerResult["contextWindowUsage"]; + +const TIMELINE: UseThreadTimelineControllerResult = { + activeBackgroundCommands: [], + activePromptMode: null, + activeThinking: null, + activeWorkflows: [], + contextBoundarySeq: null, + contextWindowUsage: CONTEXT_WINDOW_USAGE, + hasOlderTimelineRows: false, + isCatchingUpTimeline: false, + isLoadingOlderTimelineRows: false, + loadOlderTimelineRows: async () => {}, + modelFallback: null, + pendingTodos: null, + providerCommands: null, + sessionOptions: null, + timelineError: null, + timelineLoading: false, + timelineRows: [ + conversationRow({ + id: "assistant_row", + role: "assistant", + text: "An assistant answer.", + threadId: THREAD.id, + }), + fileChangeRow({ id: "edit_row", path: "README.md", threadId: THREAD.id }), + ], +}; + +vi.mock("@/hooks/useRealtimeSubscription", () => ({ + useHostListRealtimeSubscription: vi.fn(), + useThreadDetailRealtimeSubscription: vi.fn(), + useThreadTimelineRealtimeSubscription: vi.fn(), + useThreadListRealtimeSubscription: vi.fn(), + useEnvironmentDetailRealtimeSubscription: vi.fn(), + useSystemRealtimeSubscription: vi.fn(), +})); + +vi.mock("@/hooks/useHostDaemon", () => ({ + useHostDaemon: () => ({ isLocalDaemonHost: () => true }), +})); + +vi.mock("@/hooks/queries/thread-queries", async (importOriginal) => ({ + ...(await importOriginal()), + useChildThreads: () => ({ data: [] }), + useThreadPendingInteractions: () => ({ data: [] }), +})); + +vi.mock("@/hooks/queries/child-thread-pending-interactions", () => ({ + useChildThreadPendingAttention: () => [], +})); + +vi.mock("@/hooks/queries/environment-queries", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("@/hooks/queries/environment-queries") + >()), + useEnvironment: () => ({ + data: ENVIRONMENT, + isLoading: false, + isError: false, + refetch: vi.fn(), + }), +})); + +vi.mock("@/components/thread/timeline", async (importOriginal) => ({ + ...(await importOriginal()), + useThreadTimelineController: () => TIMELINE, +})); + +vi.mock("./ThreadDetailPromptArea", () => ({ + ThreadDetailPromptArea: (props: Record) => { + mocks.promptAreaProps.push(props); + return
; + }, +})); + +vi.mock("@/components/commands/AppCommandProvider", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("@/components/commands/AppCommandProvider") + >()), + useAppCommandHandler: () => undefined, + useAppCommandShortcut: () => null, +})); + +vi.mock("@bb/shared-ui/hooks/use-compact-viewport", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("@bb/shared-ui/hooks/use-compact-viewport") + >()), + useIsCompactViewport: () => false, +})); + +vi.mock("./ThreadDetailHeader", () => ({ + ThreadDetailHeader: () =>
, +})); + +vi.mock("./ThreadDetailSecondaryContent", () => ({ + ThreadDetailSecondaryContent: ({ + header, + main, + }: { + header: ReactNode; + main: ReactNode; + }) => ( + <> + {header} + {main} + + ), +})); + +vi.mock("./useThreadDetailThread", () => ({ + useThreadDetailThread: () => ({ + hasThreadDetailBootstrapSettled: true, + threadDetailBootstrapQuery: { isFetching: false }, + threadQuery: { + data: THREAD, + isFetching: false, + isLoadingError: false, + error: null, + }, + unreadDividerState: { ready: true, autoScroll: false, placement: null }, + }), +})); + +interface ThreadScreenSurface { + name: string; + messageActionSurface: ExperimentalMessageActionSurface; + hasComposer: boolean; + contextEnvironmentId: string | null; + render: (hosts: SurfaceHosts) => ReactNode; + openedReadme: (hosts: SurfaceHosts) => boolean; +} + +interface SurfaceHosts { + openFilePreview: Mock<(intent: AppFilePreviewIntent) => boolean>; + sink: ContractStateSink; +} + +function pluginThreadChat(variant: "full" | "compact" | "timeline") { + return ({ openFilePreview }: SurfaceHosts) => ( + + + + + + ); +} + +function pluginOpenedReadme({ openFilePreview }: SurfaceHosts) { + return openFilePreview.mock.calls.some( + ([intent]) => + intent.target.kind === "workspace" && + intent.target.environmentId === ENVIRONMENT.id && + intent.target.path === "README.md", + ); +} + +const SURFACES: readonly ThreadScreenSurface[] = [ + { + name: "thread page", + messageActionSurface: "thread-view", + hasComposer: true, + contextEnvironmentId: ENVIRONMENT.id, + render: ({ sink }) => ( + {}} + > + + + + ), + openedReadme: ({ sink }) => { + const snapshot = snapshotFromState(sink); + return ( + snapshot.isOpen && + snapshot.activeTabId !== null && + snapshot.activeTabId.includes("README.md") + ); + }, + }, + { + name: "plugin ThreadChat full", + messageActionSurface: "embedded-chat", + hasComposer: true, + contextEnvironmentId: null, + render: pluginThreadChat("full"), + openedReadme: pluginOpenedReadme, + }, + { + name: "plugin ThreadChat compact", + messageActionSurface: "embedded-chat", + hasComposer: true, + contextEnvironmentId: null, + render: pluginThreadChat("compact"), + openedReadme: pluginOpenedReadme, + }, + { + name: "plugin ThreadChat timeline", + messageActionSurface: "embedded-chat", + hasComposer: false, + contextEnvironmentId: null, + render: pluginThreadChat("timeline"), + openedReadme: pluginOpenedReadme, + }, +]; + +beforeEach(() => { + markPluginFrontendsSettled(); + window.localStorage.clear(); + resetFixedPanelTabsStateForTest(); + mocks.promptAreaProps = []; + vi.spyOn(sdk.threads, "get").mockResolvedValue(THREAD as never); + vi.spyOn(sdk.hosts, "list").mockResolvedValue([] as never); + setPluginSlotRegistrations( + "provider", + makePluginRegistrationSet({ + messageActions: [ + { + id: "summarize", + title: "Summarize", + icon: "Zap", + experimental_surfaces: ["thread-view", "embedded-chat"], + run: vi.fn(), + }, + { + id: "thread-view-only", + title: "Thread view only", + icon: "Zap", + experimental_surfaces: ["thread-view"], + run: vi.fn(), + }, + { + id: "thread-chat-only", + title: "ThreadChat only", + icon: "Zap", + experimental_surfaces: ["embedded-chat"], + run: vi.fn(), + }, + ], + }), + ); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + resetPluginSlotStoreForTest(); +}); + +function renderSurface(surface: ThreadScreenSurface) { + const hosts: SurfaceHosts = { + openFilePreview: vi.fn((_intent: AppFilePreviewIntent) => true), + sink: { current: null }, + }; + const { wrapper: Wrapper } = createQueryClientTestHarness(); + const view = render( + + + {surface.render(hosts)} + + , + ); + return { ...view, hosts }; +} + +async function findRow(container: HTMLElement, rowId: string) { + await waitFor(() => + expect( + container.querySelector(`[data-timeline-row-id="${rowId}"]`), + ).not.toBeNull(), + ); + return container.querySelector( + `[data-timeline-row-id="${rowId}"]`, + )!; +} + +describe.each(SURFACES)("ThreadScreen surface contract: $name", (surface) => { + it("shows every registered plugin message action on the thread's messages", async () => { + const { container } = renderSurface(surface); + const row = await findRow(container, "assistant_row"); + expect(row.querySelector('[aria-label="Summarize"]')).not.toBeNull(); + }); + + it("shows a message action only on the surfaces it declares", async () => { + const { container } = renderSurface(surface); + const row = await findRow(container, "assistant_row"); + await waitFor(() => + expect(row.querySelector('[aria-label="Summarize"]')).not.toBeNull(), + ); + expect(row.querySelector('[aria-label="Thread view only"]') !== null).toBe( + surface.messageActionSurface === "thread-view", + ); + expect(row.querySelector('[aria-label="ThreadChat only"]') !== null).toBe( + surface.messageActionSurface === "embedded-chat", + ); + }); + + it("opens a changed file from its timeline title", async () => { + const { container, hosts } = renderSurface(surface); + const row = await findRow(container, "edit_row"); + const title = [...row.querySelectorAll('[role="link"]')].find((element) => + element.textContent?.includes("README.md"), + ); + expect(title).toBeDefined(); + fireEvent.click(title!); + await waitFor(() => expect(surface.openedReadme(hosts)).toBe(true)); + }); + + it.runIf(surface.hasComposer)( + "gives the composer the thread's context usage, context environment and new-thread action", + async () => { + renderSurface(surface); + await waitFor(() => + expect(screen.getByTestId("prompt-area")).toBeTruthy(), + ); + const props = mocks.promptAreaProps.at(-1)!; + expect(props.contextWindowUsage).toBe(CONTEXT_WINDOW_USAGE); + expect(props.contextEnvironmentId).toBe(surface.contextEnvironmentId); + expect(typeof props.onCreateNewThreadInEnvironment).toBe("function"); + }, + ); +}); diff --git a/apps/app/src/views/thread-detail/ThreadScreen.test.tsx b/apps/app/src/views/thread-detail/ThreadScreen.test.tsx index b80af11e853..132a61dcd6b 100644 --- a/apps/app/src/views/thread-detail/ThreadScreen.test.tsx +++ b/apps/app/src/views/thread-detail/ThreadScreen.test.tsx @@ -139,6 +139,9 @@ function screenElement(presentation: ThreadScreenPresentation) { environmentCheckout: undefined, environmentChrome: undefined, contextEnvironmentId: null, + focusRequest: null, + onCreateNewThreadInEnvironment: null, + onOpenThreadInfo: null, permissionPolicy: "snapshot", }} environment={null} @@ -148,8 +151,12 @@ function screenElement(presentation: ThreadScreenPresentation) { thread={THREAD} timelineEnabled timelineHost={{ + consumerMessageActions: [], environmentHostName: null, - includePluginMessageActions: false, + leadingContent: null, + messageActionSurface: "thread-view", + onForkMessage: null, + onTitleAction: null, unreadDividerAutoScroll: false, unreadDividerPlacement: null, }} diff --git a/apps/app/src/views/thread-detail/ThreadScreen.tsx b/apps/app/src/views/thread-detail/ThreadScreen.tsx index 0b7c9d20efb..ce86f535385 100644 --- a/apps/app/src/views/thread-detail/ThreadScreen.tsx +++ b/apps/app/src/views/thread-detail/ThreadScreen.tsx @@ -7,6 +7,8 @@ import { useState, type ReactNode, } from "react"; +import type { ExperimentalMessageActionSurface } from "@get-bb/plugin-sdk"; +import { MessageActionSurfaceProvider } from "@/lib/message-action-surface"; import { nanoid } from "nanoid"; import { defaultAppSettings, type Environment } from "@bb/domain"; import type { ThreadResponse, TimelineRow } from "@bb/server-contract"; @@ -99,12 +101,12 @@ export type ThreadScreenPresentation = | { kind: "transcript"; layout: "contained" | "document" }; export interface ThreadScreenTimelineHost { - consumerMessageActions?: readonly ThreadTimelineConsumerMessageAction[]; + consumerMessageActions: readonly ThreadTimelineConsumerMessageAction[]; environmentHostName: string | null; - includePluginMessageActions: boolean; - leadingContent?: ReactNode; - onForkMessage?: ThreadTimelineForkMessageHandler; - onTitleAction?: TimelineTitleActionResolver; + leadingContent: ReactNode; + messageActionSurface: ExperimentalMessageActionSurface; + onForkMessage: ThreadTimelineForkMessageHandler | null; + onTitleAction: TimelineTitleActionResolver | null; unreadDividerAutoScroll: boolean; unreadDividerPlacement: ThreadTimelineUnreadDividerPlacement | null; } @@ -113,9 +115,9 @@ export interface ThreadScreenComposerHost { environmentCheckout: WorkspaceCheckoutDisplay | undefined; environmentChrome: EnvironmentSummaryChrome | undefined; contextEnvironmentId: string | null; - focusRequest?: number; - onCreateNewThreadInEnvironment?: () => void; - onOpenThreadInfo?: () => void; + focusRequest: number | null; + onCreateNewThreadInEnvironment: (() => void) | null; + onOpenThreadInfo: (() => void) | null; permissionPolicy: ThreadComposerPermissionPolicy; } @@ -553,7 +555,7 @@ export function ThreadScreen({ ); const composerFocusRequestKey = useComposerFocusRequestKey( draftStorageKey, - composer?.focusRequest, + composer?.focusRequest ?? undefined, ); const [timelineNavigationTargetRowId, setTimelineNavigationTargetRowId] = useState(null); @@ -581,54 +583,55 @@ export function ThreadScreen({ const selectionAddToChat = composer ? handleAddToChat : undefined; const surface = ( - - ) : undefined - } - timelineErrorClassName={ - isPanelPresentation ? "mx-2 mt-4 text-destructive" : undefined - } - leadingContent={timelineHost.leadingContent} - consumerMessageActions={timelineHost.consumerMessageActions} - includePluginMessageActions={timelineHost.includePluginMessageActions} - onForkMessage={timelineHost.onForkMessage} - onEditMessage={handleEditSentMessage} - inlineMessageEditor={inlineMessageEditor} - onMessageAddToChat={selectionAddToChat} - onSelectionAddToChat={selectionAddToChat} - onLoadOlderRows={timeline.loadOlderTimelineRows} - onTitleAction={timelineHost.onTitleAction} - projectId={projectId} - resolveMentionLink={resolveMentionLink} - showOngoingIndicator={ - thread.status !== "stopping" && - !hasPendingInteraction && - isRunningThreadRuntimeDisplayStatus(thread.runtime.displayStatus) && - !isThreadTimelinePending - } - timelineRows={timelineRows} - timelineNavigationTargetRowId={timelineNavigationTargetRowId} - isStopping={thread.status === "stopping"} - stoppingAnchorAt={thread.updatedAt} - threadId={thread.id} - threadRuntimeDisplayStatus={thread.runtime.displayStatus} - unreadDividerAutoScroll={timelineHost.unreadDividerAutoScroll} - unreadDividerPlacement={timelineHost.unreadDividerPlacement} - /> + + + ) : undefined + } + timelineErrorClassName={ + isPanelPresentation ? "mx-2 mt-4 text-destructive" : undefined + } + leadingContent={timelineHost.leadingContent} + consumerMessageActions={timelineHost.consumerMessageActions} + onForkMessage={timelineHost.onForkMessage ?? undefined} + onEditMessage={handleEditSentMessage} + inlineMessageEditor={inlineMessageEditor} + onMessageAddToChat={selectionAddToChat} + onSelectionAddToChat={selectionAddToChat} + onLoadOlderRows={timeline.loadOlderTimelineRows} + onTitleAction={timelineHost.onTitleAction ?? undefined} + projectId={projectId} + resolveMentionLink={resolveMentionLink} + showOngoingIndicator={ + thread.status !== "stopping" && + !hasPendingInteraction && + isRunningThreadRuntimeDisplayStatus(thread.runtime.displayStatus) && + !isThreadTimelinePending + } + timelineRows={timelineRows} + timelineNavigationTargetRowId={timelineNavigationTargetRowId} + isStopping={thread.status === "stopping"} + stoppingAnchorAt={thread.updatedAt} + threadId={thread.id} + threadRuntimeDisplayStatus={thread.runtime.displayStatus} + unreadDividerAutoScroll={timelineHost.unreadDividerAutoScroll} + unreadDividerPlacement={timelineHost.unreadDividerPlacement} + /> + ); @@ -653,8 +656,10 @@ export function ThreadScreen({ canRestoreEnvironment={thread.canRestoreEnvironment} environmentGoneStatus={resolveEnvironmentGoneStatus(environment)} environmentHostId={environment?.hostId} - onCreateNewThreadInEnvironment={composer.onCreateNewThreadInEnvironment} - onOpenThreadInfo={composer.onOpenThreadInfo} + onCreateNewThreadInEnvironment={ + composer.onCreateNewThreadInEnvironment ?? undefined + } + onOpenThreadInfo={composer.onOpenThreadInfo ?? undefined} projectId={projectId} resolveMentionLink={resolveMentionLink} composerFocusRequestKey={composerFocusRequestKey} diff --git a/apps/app/src/views/thread-detail/thread-screen-hosts.test.tsx b/apps/app/src/views/thread-detail/thread-screen-hosts.test.tsx new file mode 100644 index 00000000000..a009c8d8872 --- /dev/null +++ b/apps/app/src/views/thread-detail/thread-screen-hosts.test.tsx @@ -0,0 +1,54 @@ +// @vitest-environment jsdom + +import { renderHook } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { + UNAVAILABLE_APP_PANEL_CONTROLLER, + getThreadFixedTabOwnerId, +} from "@/lib/app-fixed-tab-navigation"; +import { + SIDE_CHAT_PLUGIN_ID, + SIDE_CHAT_PLUGIN_PANEL_ACTION_ID, +} from "@/lib/side-chat-plugin"; +import { useThreadTimelineTitleActions } from "./thread-screen-hosts"; + +function resolveSideChat(panelAccepts: boolean) { + const openTab = vi.fn(() => panelAccepts); + const openThread = vi.fn(); + const { result } = renderHook(() => + useThreadTimelineTitleActions({ + threadId: "thr_main", + projectId: "proj_main", + environmentId: null, + panel: { ...UNAVAILABLE_APP_PANEL_CONTROLLER, openTab }, + openFilePreview: () => false, + openLocalFileLink: () => false, + openThread, + }), + ); + result.current({ kind: "open-plugin-side-chat", threadId: "thr_side" })?.(); + return { openTab, openThread }; +} + +describe("useThreadTimelineTitleActions side chat titles", () => { + it("opens the side chat in the surface's panel when the panel hosts it", () => { + const { openTab, openThread } = resolveSideChat(true); + expect(openTab).toHaveBeenCalledWith({ + tab: { + ownerId: getThreadFixedTabOwnerId(SIDE_CHAT_PLUGIN_ID), + tabId: SIDE_CHAT_PLUGIN_PANEL_ACTION_ID, + }, + availability: "action", + params: { threadId: "thr_side", sourceThreadId: "thr_main" }, + }); + expect(openThread).not.toHaveBeenCalled(); + }); + + it("opens the side chat thread when the surface's panel cannot host it", () => { + const { openThread } = resolveSideChat(false); + expect(openThread).toHaveBeenCalledWith({ + projectId: "proj_main", + threadId: "thr_side", + }); + }); +}); diff --git a/apps/app/src/views/thread-detail/thread-screen-hosts.ts b/apps/app/src/views/thread-detail/thread-screen-hosts.ts new file mode 100644 index 00000000000..a2505bd4215 --- /dev/null +++ b/apps/app/src/views/thread-detail/thread-screen-hosts.ts @@ -0,0 +1,132 @@ +import { useCallback } from "react"; +import type { Environment } from "@bb/domain"; +import { assertNever } from "@bb/thread-view"; +import type { TimelineTitleActionResolver } from "@/components/thread/timeline/TimelineTitleView"; +import type { ThreadTimelineLocalFileLinkHandler } from "@/components/thread/timeline/types"; +import { resolveGitDiffTabStatus } from "@/components/secondary-panel/gitDiffTabEligibility"; +import { + getThreadFixedTabOwnerId, + type AppPanelController, +} from "@/lib/app-fixed-tab-navigation"; +import type { AppFilePreviewIntent } from "@/lib/app-navigation-host"; +import { GIT_DIFF_TAB_REFERENCE } from "@/lib/git-diff-tab"; +import { + SIDE_CHAT_PLUGIN_ID, + SIDE_CHAT_PLUGIN_PANEL_ACTION_ID, +} from "@/lib/side-chat-plugin"; + +interface ThreadEnvironmentAccessArgs { + thread: { + environmentId: string | null; + archivedAt: number | null; + } | null; + environment: Environment | null; + environmentLoadFailed: boolean; +} + +export function resolveThreadEnvironmentAccess({ + thread, + environment, + environmentLoadFailed, +}: ThreadEnvironmentAccessArgs) { + const hostLifecycle = + environment === null || environment.hostLifecycle === "active" + ? null + : environment.hostLifecycle; + const executionUnavailable = + hostLifecycle !== null || environment?.status === "destroyed"; + const gitDiffTabStatus = resolveGitDiffTabStatus({ + environmentId: thread?.environmentId ?? null, + environmentIsGitRepo: environment?.isGitRepo, + environmentLoadFailed, + environmentOwnsPath: environment?.managed, + hasResolvedThread: thread !== null, + threadArchived: thread?.archivedAt != null || executionUnavailable, + }); + const canUseGitUi = !executionUnavailable && gitDiffTabStatus === "eligible"; + return { + executionUnavailable, + gitDiffTabStatus, + canUseGitUi, + contextEnvironmentId: + canUseGitUi && environment !== null && thread?.environmentId + ? thread.environmentId + : null, + reusesEnvironment: + !executionUnavailable && + environment !== null && + environment.status === "ready" && + environment.path !== null && + thread?.environmentId != null, + }; +} + +export function useThreadTimelineTitleActions({ + threadId, + projectId, + environmentId, + panel, + openFilePreview, + openLocalFileLink, + openThread, +}: { + threadId: string; + projectId: string; + environmentId: string | null; + panel: AppPanelController; + openFilePreview: (intent: AppFilePreviewIntent) => boolean; + openLocalFileLink: ThreadTimelineLocalFileLinkHandler; + openThread: (target: { projectId: string; threadId: string }) => void; +}): TimelineTitleActionResolver { + return useCallback( + (action) => { + switch (action.kind) { + case "open-file-diff": + return () => { + const openedDiff = panel.openTab({ + tab: GIT_DIFF_TAB_REFERENCE, + availability: "fixed", + target: { kind: "file", path: action.path }, + }); + if (openedDiff || environmentId === null) return; + openFilePreview({ + target: { kind: "workspace", environmentId, path: action.path }, + location: null, + }); + }; + case "open-local-file": + return () => { + openLocalFileLink({ + lineRange: null, + openTargetId: null, + path: action.path, + }); + }; + case "open-plugin-side-chat": + return () => { + const openedInPanel = panel.openTab({ + tab: { + ownerId: getThreadFixedTabOwnerId(SIDE_CHAT_PLUGIN_ID), + tabId: SIDE_CHAT_PLUGIN_PANEL_ACTION_ID, + }, + availability: "action", + params: { threadId: action.threadId, sourceThreadId: threadId }, + }); + if (!openedInPanel) + openThread({ projectId, threadId: action.threadId }); + }; + default: + return assertNever(action); + } + }, + [ + environmentId, + openFilePreview, + openLocalFileLink, + openThread, + panel, + projectId, + threadId, + ], + ); +} diff --git a/docs/api_to_audit.md b/docs/api_to_audit.md index 012998997f1..9a407bdd374 100644 --- a/docs/api_to_audit.md +++ b/docs/api_to_audit.md @@ -291,6 +291,29 @@ Before stabilizing, audit compact and embedded placement, variable-height metadata and scroll anchoring, unmount cleanup, asynchronous updates, origin filtering, and render isolation during streaming and across messages. +## `PluginMessageActionRegistration.experimental_surfaces` (`@get-bb/plugin-sdk/app`) + +Requires SDK 0.6.161. + +`app.slots.messageAction({ ..., experimental_surfaces })` limits the action to +some thread timelines. `"thread-view"` is bb's thread view, including split panes; +`"embedded-chat"` is an embedded `ThreadChat` in any variant. Omitted, the action +shows on both. An empty array or any other value fails registration. Type: +`ExperimentalMessageActionSurface`. + +Each `ThreadScreen` host states its surface (`ThreadScreenTimelineHost.messageActionSurface`), +and the timeline reads the slots through `useSurfaceMessageActionSlots` +(`apps/app/src/lib/message-action-surface.tsx`), so every surface filters the same way. + +Caller: the bundled Side chat plugin's "Reply in side chat" declares +`["thread-view"]`. Its side chat tab only exists in the thread view's panel, and a +side chat is itself an embedded `ThreadChat`, so the action stays out of side +chats and other plugins' embedded chats. + +Before stabilizing, decide whether surfaces should instead follow panel +capability (whether the surface's panel can host the tab the action opens), and +whether more surfaces (New thread previews, plugin documents) need names. + ## `app.commands.register` Unprefixed by explicit request. Registers frontend commands diff --git a/packages/domain/src/plugin-sdk-version.ts b/packages/domain/src/plugin-sdk-version.ts index 45adcc2bcf6..b1832abd476 100644 --- a/packages/domain/src/plugin-sdk-version.ts +++ b/packages/domain/src/plugin-sdk-version.ts @@ -1,3 +1,3 @@ -export const PLUGIN_SDK_VERSION = "0.6.160"; +export const PLUGIN_SDK_VERSION = "0.6.161"; export const PLUGIN_SDK_MAJOR = Number(PLUGIN_SDK_VERSION.split(".", 1)[0]); diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json index fe43762d2fe..59db3b6d7a0 100644 --- a/packages/plugin-sdk/package.json +++ b/packages/plugin-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@get-bb/plugin-sdk", - "version": "0.6.160", + "version": "0.6.161", "license": "MIT", "homepage": "https://github.com/get-bb/bb#readme", "bugs": { diff --git a/packages/plugin-sdk/src/app-contract.ts b/packages/plugin-sdk/src/app-contract.ts index f45d7136f5c..38c0b1c566e 100644 --- a/packages/plugin-sdk/src/app-contract.ts +++ b/packages/plugin-sdk/src/app-contract.ts @@ -3620,6 +3620,9 @@ export interface ExperimentalMessageMetadataRegistration { component: ComponentType; } +/** A timeline a `messageAction` can show in; see {@link PluginMessageActionRegistration.experimental_surfaces}. */ +export type ExperimentalMessageActionSurface = "thread-view" | "embedded-chat"; + /** Context handed to a `messageAction`'s `run`. */ export interface PluginMessageActionContext { /** The thread whose timeline surfaced the action. */ @@ -3641,12 +3644,13 @@ export interface PluginMessageActionContext { } /** - * An action on chat messages in the main thread timeline: an icon button in - * the per-message action bar (user and assistant messages) and an entry in - * the assistant-message text-selection menu. Embedded `ThreadChat` timelines - * do not show slot-registered actions. Host-rendered chrome — the plugin - * supplies title, icon, and `run` behavior only. Resolved icon names take precedence over - * plugin branding; omitted or unknown names fall back to branding. + * An action on chat messages in every thread timeline, including embedded + * `ThreadChat` timelines unless `experimental_surfaces` narrows it: an icon + * button in the per-message action bar (user and assistant messages) and an + * entry in the assistant-message text-selection menu. Host-rendered chrome — + * the plugin supplies title, icon, and `run` behavior only. Resolved icon + * names take precedence over plugin branding; omitted or unknown names fall + * back to branding. */ export interface PluginMessageActionRegistration { /** Unique within the plugin; letters, digits, `-`, `_`. */ @@ -3654,6 +3658,12 @@ export interface PluginMessageActionRegistration { /** Tooltip / menu label for the action. */ title: string; icon?: BbIconName; + /** + * Timelines that show the action: `"thread-view"` is bb's thread view and + * `"embedded-chat"` an embedded `ThreadChat`. Omit for both. Experimental: + * see docs/api_to_audit.md. + */ + experimental_surfaces?: readonly ExperimentalMessageActionSurface[]; /** * Runs when the user activates the action. Errors (sync or async) are * contained and logged; they never break the timeline. @@ -4334,6 +4344,13 @@ export interface ComposerCustomization { id: string; /** Composer kinds where this customization is active; omit for all kinds. */ scopes?: readonly PluginComposerScope["kind"][]; + /** + * Controls rendered in the composer's action row, before the voice, stop + * and submit controls. The collapsed single-line layout leaves them out, + * as it does bb's `+` menu and model picker; they show once the composer + * expands. bb shows the first three plugins' actions inline and the rest + * behind a "More plugin actions" button. + */ actions?: readonly { id: string; component: ComponentType }[]; banners?: readonly { id: string; @@ -4868,8 +4885,8 @@ export type ExperimentalComposerSubmitOptions = ComposerSubmitOptions; /** * A consumer-supplied action on the messages of one `ThreadChat` instance, * rendered in the embedded timeline's per-message action bar alongside the - * native actions. Slot-registered `messageAction`s do not appear there. Unlike - * the `messageAction` slot this is scoped to the rendering component, not + * native and slot-registered `messageAction` actions. Unlike the + * `messageAction` slot this is scoped to the rendering component, not * registered globally. */ export interface ThreadChatMessageAction { @@ -5128,9 +5145,10 @@ export interface NewThreadRequest { */ export interface NewThreadComposerProps { /** - * Seeds the project picker. The user can change it, including choosing - * "Don't work in a project"; see {@link NewThreadRequest.projectId} for the - * submitted projectless shape. + * Seeds the project picker. Omitted, the picker starts on the project the + * user last picked in bb's New thread view. The user can change it, + * including choosing "Don't work in a project"; see + * {@link NewThreadRequest.projectId} for the submitted projectless shape. */ defaultProjectId?: string; /** diff --git a/packages/plugin-sdk/src/internal/plugin-app-collector.ts b/packages/plugin-sdk/src/internal/plugin-app-collector.ts index c2c89ad6c49..e3c603a8efb 100644 --- a/packages/plugin-sdk/src/internal/plugin-app-collector.ts +++ b/packages/plugin-sdk/src/internal/plugin-app-collector.ts @@ -12,6 +12,7 @@ export { export { type CollectedPluginProviderIconRegistration, type CollectedPluginCommandRegistration, + type CollectedPluginMessageActionRegistration, type CollectedPluginAppRegistrations, type LegacyThreadPanelActionRegistration, type LegacyThreadHeaderActionRegistration, diff --git a/packages/plugin-sdk/src/internal/plugin-app-message-action.test.ts b/packages/plugin-sdk/src/internal/plugin-app-message-action.test.ts new file mode 100644 index 00000000000..e7c5c7e5127 --- /dev/null +++ b/packages/plugin-sdk/src/internal/plugin-app-message-action.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vitest"; +import type { PluginMessageActionRegistration } from "../app-contract.js"; +import { collectPluginAppRegistrations } from "./plugin-app-collector.js"; + +function collect(registration: PluginMessageActionRegistration) { + return collectPluginAppRegistrations({ + __bbPluginApp: true, + setup(app) { + app.slots.messageAction(registration); + }, + }).messageActions; +} + +const run = () => {}; + +describe("messageAction surfaces", () => { + it("shows an action on every surface unless it names some", () => { + expect( + collect({ id: "everywhere", title: "Everywhere", run })[0] + ?.experimental_surfaces, + ).toEqual(["thread-view", "embedded-chat"]); + expect( + collect({ + id: "thread-only", + title: "Thread only", + experimental_surfaces: ["thread-view"], + run, + })[0]?.experimental_surfaces, + ).toEqual(["thread-view"]); + }); + + it("rejects an empty or unknown surface list", () => { + const register = (experimental_surfaces: unknown) => () => + collect({ + id: "action", + title: "Action", + experimental_surfaces: + experimental_surfaces as PluginMessageActionRegistration["experimental_surfaces"], + run, + }); + expect(register([])).toThrow(/experimental_surfaces/); + expect(register(["sidebar"])).toThrow(/experimental_surfaces/); + expect(register("thread-view")).toThrow(/experimental_surfaces/); + }); +}); diff --git a/packages/plugin-sdk/src/internal/plugin-app-registration-collector.ts b/packages/plugin-sdk/src/internal/plugin-app-registration-collector.ts index 4967646ed41..5f0c7c510ba 100644 --- a/packages/plugin-sdk/src/internal/plugin-app-registration-collector.ts +++ b/packages/plugin-sdk/src/internal/plugin-app-registration-collector.ts @@ -22,6 +22,7 @@ import type { PluginCommandRegistration, ExperimentalComposerCommandRegistration, PluginMessageActionRegistration, + ExperimentalMessageActionSurface, ExperimentalMessageMetadataRegistration, PluginMessageDirectiveRegistration, PluginNavPanelRegistration, @@ -308,6 +309,41 @@ export type CollectedPluginCommandRegistration = defaultShortcut: CollectedCommandShortcut; }); +export type CollectedPluginMessageActionRegistration = Omit< + PluginMessageActionRegistration, + "experimental_surfaces" +> & { + experimental_surfaces: readonly ExperimentalMessageActionSurface[]; +}; + +const MESSAGE_ACTION_SURFACES: readonly ExperimentalMessageActionSurface[] = [ + "thread-view", + "embedded-chat", +]; + +function isMessageActionSurface( + value: unknown, +): value is ExperimentalMessageActionSurface { + return value === "thread-view" || value === "embedded-chat"; +} + +function collectMessageActionSurfaces( + kind: string, + value: unknown, +): readonly ExperimentalMessageActionSurface[] { + if (value === undefined) return MESSAGE_ACTION_SURFACES; + if ( + !Array.isArray(value) || + value.length === 0 || + !value.every(isMessageActionSurface) + ) { + throw new Error( + `${kind}: "experimental_surfaces" must be a non-empty array of "thread-view" or "embedded-chat", got ${JSON.stringify(value)}`, + ); + } + return MESSAGE_ACTION_SURFACES.filter((surface) => value.includes(surface)); +} + export interface CollectedPluginAppRegistrations { homepageSections: PluginHomepageSectionRegistration[]; settingsSections: PluginSettingsSectionRegistration[]; @@ -340,7 +376,7 @@ export interface CollectedPluginAppRegistrations { composers: ExperimentalComposerRegistration[]; messageDirectives: PluginMessageDirectiveRegistration[]; codeFenceRenderers: ExperimentalCodeFenceRendererRegistration[]; - messageActions: PluginMessageActionRegistration[]; + messageActions: CollectedPluginMessageActionRegistration[]; messageMetadata: ExperimentalMessageMetadataRegistration[]; commandPaletteActions: CollectedPluginCommandRegistration[]; providerIcons: CollectedPluginProviderIconRegistration[]; @@ -1260,6 +1296,10 @@ export function collectPluginAppRegistrations( icon: requireNonEmptyString(kind, "icon", registration.icon), } : {}), + experimental_surfaces: collectMessageActionSurfaces( + kind, + registration.experimental_surfaces, + ), run: registration.run, }); }, diff --git a/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-components.md b/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-components.md index 25837f8ff9a..b544901758e 100644 --- a/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-components.md +++ b/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-components.md @@ -22,7 +22,8 @@ className?, leadingContent?, messageActions? }` — scrolling with it; `messageActions` is a list of `ThreadChatMessageAction` entries `{ id, title, icon?, roles?, run }` rendered in this instance's per-message action bar after the native - actions (slot-registered `messageAction`s do not appear in `ThreadChat`) — `roles` limits the action to `"user"` and/or + actions and the slot-registered `messageAction`s whose + `experimental_surfaces` include `"embedded-chat"` — `roles` limits the action to `"user"` and/or `"assistant"` messages (omitted = both), and `run(message)` receives the same narrow `ThreadChatMessageReference` as the `messageAction` slot; errors from `run` are contained and logged, never breaking the timeline. diff --git a/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-renderer-slots.md b/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-renderer-slots.md index 6872f6b4a7b..9abdd32a2f5 100644 --- a/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-renderer-slots.md +++ b/plugins/bb-guide/skills/bb-plugin-authoring/references/frontend-renderer-slots.md @@ -210,9 +210,11 @@ message, Original }` — render fenced code blocks of chosen languages in public contract and examples. - `messageAction` → an action on chat messages: an icon button in the per-message action bar (user and assistant messages) and an entry in the - assistant-message text-selection menu. Slot actions are limited to the main - timeline; embedded `ThreadChat` suppresses them on both surfaces. Host-rendered chrome, no plugin - component — registration: `{ id, title, icon?, run }`. Activating it calls + assistant-message text-selection menu, in bb's thread view and in embedded + `ThreadChat`. `experimental_surfaces` limits it to `"thread-view"` and/or + `"embedded-chat"` (omitted = both); an empty or unknown list fails + registration. Host-rendered chrome, no plugin + component — registration: `{ id, title, icon?, experimental_surfaces?, run }`. Activating it calls `run(context)` with `{ threadId, message, selectedText?, experimental_panel, composer }`: `message` is a narrow stable reference `{ id, threadId, role: "user" | "assistant", text, sourceSeqEnd, experimental_messageSeq }` (never diff --git a/plugins/plugin-api-docs/src/surfaces.ts b/plugins/plugin-api-docs/src/surfaces.ts index 3607af05a34..a6a46a55568 100644 --- a/plugins/plugin-api-docs/src/surfaces.ts +++ b/plugins/plugin-api-docs/src/surfaces.ts @@ -400,7 +400,8 @@ export const SURFACE_GROUPS: SurfaceGroup[] = [ summary: "Add an action to messages in a thread. With this, a plugin can:", bullets: [ - "Appear under messages on hover, or on text selected in a reply, in the main timeline only", + "Appear under messages on hover, or on text selected in a reply", + "Show in bb's thread view, in embedded ThreadChat, or in only one of them", "Receive the message with the sequence its link uses, or the selected text", "Open a [side-panel tab](thread-panel) or write into the composer with the result", ], @@ -408,6 +409,8 @@ export const SURFACE_GROUPS: SurfaceGroup[] = [ "PluginMessageActionRegistration", "PluginMessageActionContext", "ThreadChatMessageReference", + "PluginMessageActionRegistration.experimental_surfaces", + "ExperimentalMessageActionSurface", ], firstParty: ["Side chat"], }, diff --git a/plugins/side-chat/app.tsx b/plugins/side-chat/app.tsx index 6be1f67f315..3b5a4b143a9 100644 --- a/plugins/side-chat/app.tsx +++ b/plugins/side-chat/app.tsx @@ -287,6 +287,7 @@ export default definePluginApp((app) => { id: "reply-in-side-chat", title: "Reply in side chat", icon: "SideChat", + experimental_surfaces: ["thread-view"], async run(context: PluginMessageActionContext) { const anchorText = context.selectedText ?? context.message.text; await openSideChat({