diff --git a/apps/desktop/src/renderer/components/LanguageAwareI18nProvider/LanguageAwareI18nProvider.test.tsx b/apps/desktop/src/renderer/components/LanguageAwareI18nProvider/LanguageAwareI18nProvider.test.tsx index a5dac2ebfd4..f79463b1fd1 100644 --- a/apps/desktop/src/renderer/components/LanguageAwareI18nProvider/LanguageAwareI18nProvider.test.tsx +++ b/apps/desktop/src/renderer/components/LanguageAwareI18nProvider/LanguageAwareI18nProvider.test.tsx @@ -8,6 +8,19 @@ import { test, } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import * as authClientModule from "renderer/lib/auth-client"; +import * as electronTrpcModule from "renderer/lib/electron-trpc"; +import * as posthogModule from "renderer/lib/posthog"; + +// mock.module rewrites live bindings process-wide and bun runs every suite in +// one process, so these stubs outlive this file unless they are put back. +// Which suite that breaks depends on bun's file order, which shifts whenever a +// test file is added anywhere in the app. +const realModules = { + "renderer/lib/auth-client": { ...authClientModule }, + "renderer/lib/electron-trpc": { ...electronTrpcModule }, + "renderer/lib/posthog": { ...posthogModule }, +}; // happy-dom is process-wide; unregister in afterAll so the shared mock // document is restored for the other renderer suites. @@ -91,6 +104,9 @@ afterEach(() => { } }); afterAll(async () => { + for (const [specifier, exports] of Object.entries(realModules)) { + mock.module(specifier, () => exports); + } if (!alreadyRegistered) await GlobalRegistrator.unregister(); }); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/DashboardSidebarWorkspaceChips.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/DashboardSidebarWorkspaceChips.tsx index 487aa699b23..fc1f0febfd2 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/DashboardSidebarWorkspaceChips.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/DashboardSidebarWorkspaceChips.tsx @@ -1,10 +1,12 @@ import { cn } from "@superset/ui/utils"; import type { MouseEventHandler } from "react"; +import { useWorkspacePageCommentsWaiting } from "renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider"; import { useDashboardSidebarWorkspacePorts } from "renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPortsProvider"; import { useInlineWorkspacePortsEnabled } from "renderer/stores/inline-workspace-ports"; import { useWorkspaceAgentsRowEnabled } from "renderer/stores/workspace-agents-row"; import type { DashboardSidebarWorkspaceIndentation } from "../../../../../../types"; import { DashboardSidebarAgentsChip } from "./components/DashboardSidebarAgentsChip"; +import { DashboardSidebarPageCommentsChip } from "./components/DashboardSidebarPageCommentsChip"; import { DashboardSidebarPortsChip } from "./components/DashboardSidebarPortsChip"; import { useDashboardSidebarWorkspaceRunningAgents } from "./hooks/useDashboardSidebarWorkspaceRunningAgents"; @@ -18,9 +20,9 @@ interface DashboardSidebarWorkspaceChipsProps { /** * Activity line beneath a workspace row, left-aligned with the title: an - * agents chip and a ports chip. Agent chips appear only when more than one - * agent is running — a lone agent is the norm for a workspace and showing it - * adds no signal. + * agents chip, a ports chip and a page-comments chip. Agent chips appear only + * when more than one agent is running — a lone agent is the norm for a + * workspace and showing it adds no signal. */ export function DashboardSidebarWorkspaceChips({ workspaceId, @@ -34,6 +36,7 @@ export function DashboardSidebarWorkspaceChips({ const portGroup = useDashboardSidebarWorkspacePorts(workspaceId); const ports = inlineWorkspacePortsEnabled ? (portGroup?.ports ?? []) : []; const runningAgents = useDashboardSidebarWorkspaceRunningAgents(workspaceId); + const pageCommentsWaiting = useWorkspacePageCommentsWaiting(workspaceId); // One agent alone is what the pane already shows; the chip earns its // place once there is more than one, or once the one has subagents // running underneath it that the sidebar would otherwise never surface. @@ -45,7 +48,7 @@ export function DashboardSidebarWorkspaceChips({ ? runningAgents : []; - if (ports.length === 0 && agents.length === 0) { + if (ports.length === 0 && agents.length === 0 && pageCommentsWaiting === 0) { return null; } @@ -87,6 +90,7 @@ export function DashboardSidebarWorkspaceChips({ )} {ports.length > 0 && } + ); } diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/DashboardSidebarPageCommentsChip.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/DashboardSidebarPageCommentsChip.test.tsx new file mode 100644 index 00000000000..8f2fca173d9 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/DashboardSidebarPageCommentsChip.test.tsx @@ -0,0 +1,71 @@ +import { afterAll, afterEach, describe, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; + +// happy-dom over the preloaded plain-object document — Radix's tooltip trigger +// needs a real DOM. Bun runs test files sequentially in one process and +// happy-dom's globals are process-wide, so we MUST unregister in afterAll to +// restore the shared mock document for the other renderer suites. +const alreadyRegistered = GlobalRegistrator.isRegistered; +if (!alreadyRegistered) GlobalRegistrator.register(); +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +const { cleanup, render } = await import("@testing-library/react"); +const { DashboardSidebarPageCommentsChip } = await import( + "./DashboardSidebarPageCommentsChip" +); + +afterEach(cleanup); +afterAll(async () => { + if (!alreadyRegistered) await GlobalRegistrator.unregister(); +}); + +describe("DashboardSidebarPageCommentsChip", () => { + test("renders nothing when no comment is waiting", () => { + const { container } = render( + , + ); + + expect(container.firstElementChild).toBeNull(); + }); + + test("describes the count without relying on the tooltip", () => { + const { container } = render( + , + ); + + const chip = container.firstElementChild as HTMLElement; + expect(chip.querySelector("span[aria-hidden='true']")?.textContent).toBe( + "3", + ); + expect(chip.querySelector(".sr-only")?.textContent).toBe( + "3 page comments are waiting on an agent here", + ); + }); + + test("caps the rendered count but describes the real one", () => { + const { container } = render( + , + ); + + const chip = container.firstElementChild as HTMLElement; + expect(chip.querySelector("span[aria-hidden='true']")?.textContent).toBe( + "99+", + ); + expect(chip.querySelector(".sr-only")?.textContent).toBe( + "150 page comments are waiting on an agent here", + ); + }); + + test("carries the comment icon the other chips' chassis expects", () => { + const { container } = render( + , + ); + + const chip = container.firstElementChild as HTMLElement; + expect(chip.className).toContain("rounded-full"); + expect(chip.className).toContain("bg-muted/60"); + expect(chip.querySelector("svg")).not.toBeNull(); + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/DashboardSidebarPageCommentsChip.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/DashboardSidebarPageCommentsChip.tsx new file mode 100644 index 00000000000..490e0cbb43f --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/DashboardSidebarPageCommentsChip.tsx @@ -0,0 +1,55 @@ +import { Plural } from "@lingui/react/macro"; +import { Badge } from "@superset/ui/badge"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@superset/ui/tooltip"; +import { LuMessageSquare } from "react-icons/lu"; +import { STROKE_WIDTH } from "renderer/screens/main/components/WorkspaceSidebar/constants"; + +const MAX_RENDERED_COUNT = 99; + +interface DashboardSidebarPageCommentsChipProps { + count: number; +} + +/** + * Page-comment chip on the workspace activity line: how many page comments are + * waiting on an agent in this workspace. Unlike its neighbours there is no + * hover card — the read model behind it counts threads and cannot list them. + */ +export function DashboardSidebarPageCommentsChip({ + count, +}: DashboardSidebarPageCommentsChipProps) { + if (count <= 0) return null; + + return ( + + + + + + + + + + + + + + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/index.ts new file mode 100644 index 00000000000..1d9f1b3fa03 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarWorkspaceItem/components/DashboardSidebarExpandedWorkspaceRow/components/DashboardSidebarWorkspaceChips/components/DashboardSidebarPageCommentsChip/index.ts @@ -0,0 +1 @@ +export { DashboardSidebarPageCommentsChip } from "./DashboardSidebarPageCommentsChip"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider/DashboardSidebarPageCommentsProvider.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider/DashboardSidebarPageCommentsProvider.tsx new file mode 100644 index 00000000000..49b99e3ded6 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider/DashboardSidebarPageCommentsProvider.tsx @@ -0,0 +1,45 @@ +import { createContext, type ReactNode, useContext, useMemo } from "react"; +import { useActiveOrganizationId } from "renderer/hooks/useActiveOrganizationId"; +import { cloudTrpc } from "renderer/lib/cloud-trpc"; + +const WAITING_REFETCH_INTERVAL_MS = 60_000; +const WAITING_STALE_TIME_MS = 30_000; + +const DashboardSidebarPageCommentsContext = createContext | null>(null); + +export function DashboardSidebarPageCommentsProvider({ + children, +}: { + children: ReactNode; +}) { + const organizationId = useActiveOrganizationId(); + const { data } = cloudTrpc.pageComment.waitingByWorkspace.useQuery( + undefined, + { + enabled: organizationId !== null, + refetchInterval: WAITING_REFETCH_INTERVAL_MS, + staleTime: WAITING_STALE_TIME_MS, + }, + ); + + const waitingByWorkspaceId = useMemo( + () => + new Map( + (data ?? []).map((row) => [row.workspaceId, row.waitingCount] as const), + ), + [data], + ); + + return ( + + {children} + + ); +} + +export function useWorkspacePageCommentsWaiting(workspaceId: string): number { + return useContext(DashboardSidebarPageCommentsContext)?.get(workspaceId) ?? 0; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider/index.ts new file mode 100644 index 00000000000..051889ed08f --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider/index.ts @@ -0,0 +1,4 @@ +export { + DashboardSidebarPageCommentsProvider, + useWorkspacePageCommentsWaiting, +} from "./DashboardSidebarPageCommentsProvider"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/layout.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/layout.tsx index 873862966ba..a0c3b4cf76d 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/layout.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/layout.tsx @@ -13,6 +13,7 @@ import { useQuickCreateWorkspace } from "renderer/hooks/useQuickCreateWorkspace" import { useHotkey } from "renderer/hotkeys"; import { electronTrpc } from "renderer/lib/electron-trpc"; import { DashboardSidebar } from "renderer/routes/_authenticated/_dashboard/components/DashboardSidebar"; +import { DashboardSidebarPageCommentsProvider } from "renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPageCommentsProvider"; import { DashboardSidebarPortsProvider } from "renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/DashboardSidebarPortsProvider"; import { PortForwardsProvider } from "renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/providers/PortForwardsProvider"; import { useDevSeedV2Sidebar } from "renderer/routes/_authenticated/hooks/useDevSeedV2Sidebar"; @@ -269,52 +270,54 @@ function DashboardLayout() { selectedWorkspaceIsRemote) } > - - -
- - {sidebarOutsideColumn && sidebarPanel} -
- {!hideTopBar && } -
- {!sidebarOutsideColumn && sidebarPanel} -
- {versionMismatch ? ( - // A v2 user on a stale v1 workspace route has nothing to go - // back to, so send them somewhere actionable instead of a - // dead-end "pick a workspace" screen. v1 users keep the - // static state — /new-workspace is a v2-only surface. - isV2CloudEnabled ? ( - + + + +
+ + {sidebarOutsideColumn && sidebarPanel} +
+ {!hideTopBar && } +
+ {!sidebarOutsideColumn && sidebarPanel} +
+ {versionMismatch ? ( + // A v2 user on a stale v1 workspace route has nothing to go + // back to, so send them somewhere actionable instead of a + // dead-end "pick a workspace" screen. v1 users keep the + // static state — /new-workspace is a v2-only surface. + isV2CloudEnabled ? ( + + ) : ( + + ) ) : ( - - ) - ) : ( - - - - )} + + + + )} +
-
-
- - {deleteTarget && ( - { - if (!open) setDeleteTarget(null); - }} +
- )} -
- + + {deleteTarget && ( + { + if (!open) setDeleteTarget(null); + }} + /> + )} +
+
+
); } diff --git a/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/CollectionsProvider.tsx b/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/CollectionsProvider.tsx index 76f27643456..8d65a74b85d 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/CollectionsProvider.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/CollectionsProvider.tsx @@ -1,4 +1,3 @@ -import { CLOUD_QUERY_KEY_ROOT } from "@superset/cloud-client"; import { createContext, type ReactNode, @@ -11,11 +10,7 @@ import { } from "react"; import { env } from "renderer/env.renderer"; import { authClient } from "renderer/lib/auth-client"; -import { - CLOUD_TRPC_ROUTER_ROOTS, - cloudTrpc, - setCloudOrganizationId, -} from "renderer/lib/cloud-trpc"; +import { cloudTrpc, setCloudOrganizationId } from "renderer/lib/cloud-trpc"; import { electronTrpc } from "renderer/lib/electron-trpc"; import { electronTrpcClient } from "renderer/lib/trpc-client"; import { electronQueryClient } from "renderer/providers/ElectronTRPCProvider/ElectronTRPCProvider"; @@ -25,29 +20,7 @@ import { getCollections, preloadCollections, } from "./collections"; - -// Cloud query procedures take no organizationId input (the server scopes by -// active org), so their React Query keys don't encode the org — on org switch -// the previous org's rows must be dropped, not just marked stale. -const ORG_SCOPED_CLOUD_ROUTERS = new Set(CLOUD_TRPC_ROUTER_ROOTS); - -function dropCloudQueriesForOrgSwitch(): void { - electronQueryClient.removeQueries({ - predicate: (query) => { - const [head, second] = query.queryKey; - if (Array.isArray(head)) { - return ( - typeof head[0] === "string" && ORG_SCOPED_CLOUD_ROUTERS.has(head[0]) - ); - } - return ( - head === CLOUD_QUERY_KEY_ROOT && - typeof second === "string" && - ORG_SCOPED_CLOUD_ROUTERS.has(second) - ); - }, - }); -} +import { dropCloudQueriesForOrgSwitch } from "./dropCloudQueriesForOrgSwitch"; type CollectionsContextType = ReturnType & { activeOrganizationId: string; @@ -215,7 +188,7 @@ export function CollectionsProvider({ children }: { children: ReactNode }) { previousOrganizationIdRef.current && previousOrganizationIdRef.current !== activeOrganizationId ) { - dropCloudQueriesForOrgSwitch(); + dropCloudQueriesForOrgSwitch(electronQueryClient); } previousOrganizationIdRef.current = activeOrganizationId; } diff --git a/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/dropCloudQueriesForOrgSwitch.test.ts b/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/dropCloudQueriesForOrgSwitch.test.ts new file mode 100644 index 00000000000..c3fa77557f4 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/dropCloudQueriesForOrgSwitch.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "bun:test"; +import { QueryClient, QueryObserver } from "@tanstack/react-query"; +import { dropCloudQueriesForOrgSwitch } from "./dropCloudQueriesForOrgSwitch"; + +const WAITING_BY_WORKSPACE_KEY = [ + ["pageComment", "waitingByWorkspace"], + { type: "query" }, +]; +const PAGE_COMMENT_LIST_KEY = ["cloud", "pageComment", "list", "page-1"]; +const LOCAL_WORKSPACES_KEY = [["workspace", "list"], { type: "query" }]; + +function testQueryClient(): QueryClient { + return new QueryClient({ + defaultOptions: { + queries: { retry: false, gcTime: Number.POSITIVE_INFINITY }, + }, + }); +} + +async function until( + predicate: () => boolean, + description: string, +): Promise { + for (let attempt = 0; attempt < 200; attempt += 1) { + if (predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 5)); + } + throw new Error(`Timed out waiting for ${description}`); +} + +function mountedObserver( + client: QueryClient, + queryKey: readonly unknown[], + queryFn: () => Promise, +): { observer: QueryObserver; unsubscribe: () => void } { + const observer = new QueryObserver(client, { queryKey, queryFn }); + const unsubscribe = observer.subscribe(() => {}); + return { observer, unsubscribe }; +} + +describe("dropCloudQueriesForOrgSwitch", () => { + it("clears a still-mounted observer's rows and refetches them", async () => { + const client = testQueryClient(); + let organizationId = "org-a"; + const { observer, unsubscribe } = mountedObserver( + client, + WAITING_BY_WORKSPACE_KEY, + async () => [`${organizationId}-row`], + ); + + await until( + () => observer.getCurrentResult().data !== undefined, + "the first organization's rows", + ); + expect(observer.getCurrentResult().data).toEqual(["org-a-row"]); + + organizationId = "org-b"; + dropCloudQueriesForOrgSwitch(client); + + expect(observer.getCurrentResult().data).toBeUndefined(); + + await until( + () => observer.getCurrentResult().data !== undefined, + "the second organization's rows", + ); + expect(observer.getCurrentResult().data).toEqual(["org-b-row"]); + + unsubscribe(); + }); + + it("clears cloud queries keyed under the flat cloud root", async () => { + const client = testQueryClient(); + const { observer, unsubscribe } = mountedObserver( + client, + PAGE_COMMENT_LIST_KEY, + async () => ["comment"], + ); + + await until( + () => observer.getCurrentResult().data !== undefined, + "the page comment list", + ); + + dropCloudQueriesForOrgSwitch(client); + + expect(observer.getCurrentResult().data).toBeUndefined(); + + unsubscribe(); + }); + + it("leaves queries outside the cloud routers untouched", async () => { + const client = testQueryClient(); + const { observer, unsubscribe } = mountedObserver( + client, + LOCAL_WORKSPACES_KEY, + async () => ["local-workspace"], + ); + + await until( + () => observer.getCurrentResult().data !== undefined, + "the local workspace list", + ); + + dropCloudQueriesForOrgSwitch(client); + + expect(observer.getCurrentResult().data).toEqual(["local-workspace"]); + + unsubscribe(); + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/dropCloudQueriesForOrgSwitch.ts b/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/dropCloudQueriesForOrgSwitch.ts new file mode 100644 index 00000000000..47adb7aeec3 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/providers/CollectionsProvider/dropCloudQueriesForOrgSwitch.ts @@ -0,0 +1,35 @@ +import { CLOUD_QUERY_KEY_ROOT } from "@superset/cloud-client"; +import type { QueryClient } from "@tanstack/react-query"; +import { CLOUD_TRPC_ROUTER_ROOTS } from "renderer/lib/cloud-trpc"; + +const ORG_SCOPED_CLOUD_ROUTERS = new Set(CLOUD_TRPC_ROUTER_ROOTS); + +function isOrgScopedCloudQuery(queryKey: readonly unknown[]): boolean { + const [head, second] = queryKey; + if (Array.isArray(head)) { + return typeof head[0] === "string" && ORG_SCOPED_CLOUD_ROUTERS.has(head[0]); + } + return ( + head === CLOUD_QUERY_KEY_ROOT && + typeof second === "string" && + ORG_SCOPED_CLOUD_ROUTERS.has(second) + ); +} + +/** + * Cloud query procedures take no organizationId input (the server scopes by + * the org header this window sends), so their React Query keys don't encode + * the org: on a switch the previous org's rows are indistinguishable from the + * new org's by key alone and must be cleared. + * + * `resetQueries`, not `removeQueries`: removing a query drops it from the + * cache without notifying the observers still mounted on it, so a provider + * that stays mounted across the switch keeps handing out the previous org's + * rows until something else makes it re-render. Resetting clears the data and + * refetches the mounted ones against the new org's header. + */ +export function dropCloudQueriesForOrgSwitch(queryClient: QueryClient): void { + void queryClient.resetQueries({ + predicate: (query) => isOrgScopedCloudQuery(query.queryKey), + }); +} diff --git a/apps/web/src/app/page/[slug]/components/PageCommentHintBar/PageCommentHintBar.tsx b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/PageCommentHintBar.tsx new file mode 100644 index 00000000000..55514411802 --- /dev/null +++ b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/PageCommentHintBar.tsx @@ -0,0 +1,41 @@ +"use client"; + +import { PageCommentHint } from "@superset/ui/page-comments"; +import { useEffect, useState } from "react"; +import { usePageWatch } from "../../hooks/usePageWatch"; +import { + hasSeenPageCommentHint, + rememberPageCommentHint, +} from "./utils/pageCommentHintSeen"; + +interface PageCommentHintBarProps { + slug: string; + initialWatching: boolean; +} + +export function PageCommentHintBar({ + slug, + initialWatching, +}: PageCommentHintBarProps) { + const [visible, setVisible] = useState(false); + const { watching } = usePageWatch(slug, { + watching: initialWatching, + agentId: null, + }); + + useEffect(() => { + setVisible(!hasSeenPageCommentHint()); + }, []); + + if (!visible) return null; + + return ( + { + rememberPageCommentHint(); + setVisible(false); + }} + /> + ); +} diff --git a/apps/web/src/app/page/[slug]/components/PageCommentHintBar/index.ts b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/index.ts new file mode 100644 index 00000000000..3937753d74d --- /dev/null +++ b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/index.ts @@ -0,0 +1 @@ +export { PageCommentHintBar } from "./PageCommentHintBar"; diff --git a/apps/web/src/app/page/[slug]/components/PageCommentHintBar/utils/pageCommentHintSeen/index.ts b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/utils/pageCommentHintSeen/index.ts new file mode 100644 index 00000000000..cb104cb44cd --- /dev/null +++ b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/utils/pageCommentHintSeen/index.ts @@ -0,0 +1,4 @@ +export { + hasSeenPageCommentHint, + rememberPageCommentHint, +} from "./pageCommentHintSeen"; diff --git a/apps/web/src/app/page/[slug]/components/PageCommentHintBar/utils/pageCommentHintSeen/pageCommentHintSeen.ts b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/utils/pageCommentHintSeen/pageCommentHintSeen.ts new file mode 100644 index 00000000000..a61063dacca --- /dev/null +++ b/apps/web/src/app/page/[slug]/components/PageCommentHintBar/utils/pageCommentHintSeen/pageCommentHintSeen.ts @@ -0,0 +1,17 @@ +const PAGE_COMMENT_HINT_KEY = "superset-page-comment-hint-v1"; + +export function hasSeenPageCommentHint(): boolean { + try { + return window.localStorage.getItem(PAGE_COMMENT_HINT_KEY) !== null; + } catch { + return true; + } +} + +export function rememberPageCommentHint(): void { + try { + window.localStorage.setItem(PAGE_COMMENT_HINT_KEY, "seen"); + } catch { + // localStorage unavailable; the hint shows again next visit + } +} diff --git a/apps/web/src/app/page/[slug]/components/PageHeaderBar/components/PageWatchBadge/PageWatchBadge.tsx b/apps/web/src/app/page/[slug]/components/PageHeaderBar/components/PageWatchBadge/PageWatchBadge.tsx index 5be3ae5adaf..8f22db65b95 100644 --- a/apps/web/src/app/page/[slug]/components/PageHeaderBar/components/PageWatchBadge/PageWatchBadge.tsx +++ b/apps/web/src/app/page/[slug]/components/PageHeaderBar/components/PageWatchBadge/PageWatchBadge.tsx @@ -1,11 +1,7 @@ "use client"; import { Tooltip, TooltipContent, TooltipTrigger } from "@superset/ui/tooltip"; -import { useQuery } from "@tanstack/react-query"; -import { useTRPC } from "@/trpc/react"; - -const WATCHING_REFRESH_MS = 30_000; -const IDLE_REFRESH_MS = 5 * 60_000; +import { usePageWatch } from "../../../../hooks/usePageWatch"; interface PageWatchBadgeProps { slug: string; @@ -18,20 +14,10 @@ export function PageWatchBadge({ initialWatching, initialAgentId, }: PageWatchBadgeProps) { - const trpc = useTRPC(); - const { data } = useQuery({ - ...trpc.page.get.queryOptions({ slug }), - refetchInterval: (query) => - (query.state.data?.watch.watching ?? initialWatching) - ? WATCHING_REFRESH_MS - : IDLE_REFRESH_MS, - refetchIntervalInBackground: false, - }); - - const watch = data?.watch ?? { + const watch = usePageWatch(slug, { watching: initialWatching, agentId: initialAgentId, - }; + }); if (!watch.watching) return null; diff --git a/apps/web/src/app/page/[slug]/hooks/usePageWatch/index.ts b/apps/web/src/app/page/[slug]/hooks/usePageWatch/index.ts new file mode 100644 index 00000000000..9d8f06ebe6e --- /dev/null +++ b/apps/web/src/app/page/[slug]/hooks/usePageWatch/index.ts @@ -0,0 +1 @@ +export { type PageWatchSnapshot, usePageWatch } from "./usePageWatch"; diff --git a/apps/web/src/app/page/[slug]/hooks/usePageWatch/usePageWatch.ts b/apps/web/src/app/page/[slug]/hooks/usePageWatch/usePageWatch.ts new file mode 100644 index 00000000000..9cbdbf1cd81 --- /dev/null +++ b/apps/web/src/app/page/[slug]/hooks/usePageWatch/usePageWatch.ts @@ -0,0 +1,29 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { useTRPC } from "@/trpc/react"; + +const WATCHING_REFRESH_MS = 30_000; +const IDLE_REFRESH_MS = 5 * 60_000; + +export interface PageWatchSnapshot { + watching: boolean; + agentId: string | null; +} + +export function usePageWatch( + slug: string, + initial: PageWatchSnapshot, +): PageWatchSnapshot { + const trpc = useTRPC(); + const { data } = useQuery({ + ...trpc.page.get.queryOptions({ slug }), + refetchInterval: (query) => + (query.state.data?.watch.watching ?? initial.watching) + ? WATCHING_REFRESH_MS + : IDLE_REFRESH_MS, + refetchIntervalInBackground: false, + }); + + return data?.watch ?? initial; +} diff --git a/apps/web/src/app/page/[slug]/page.tsx b/apps/web/src/app/page/[slug]/page.tsx index caf6263f792..c9d5f538694 100644 --- a/apps/web/src/app/page/[slug]/page.tsx +++ b/apps/web/src/app/page/[slug]/page.tsx @@ -11,6 +11,7 @@ import { notFound } from "next/navigation"; import { cache } from "react"; import { initServerI18n } from "@/lib/i18n-server"; import { api } from "../../../trpc/server"; +import { PageCommentHintBar } from "./components/PageCommentHintBar"; import { PageCommentsShell } from "./components/PageCommentsShell"; import { PageHeaderBar } from "./components/PageHeaderBar"; import { PageUnavailable } from "./components/PageUnavailable"; @@ -192,6 +193,13 @@ export default async function PublishedPage({ } /> + {previewing ? null : ( + + )} +
diff --git a/packages/i18n/locales/cs/messages.po b/packages/i18n/locales/cs/messages.po index d0afe091001..d9d6e3b442d 100644 --- a/packages/i18n/locales/cs/messages.po +++ b/packages/i18n/locales/cs/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# komentář} few {# komentáře} many {# komentá msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# soubor} few {# soubory} many {# souboru} other {# souborů}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# komentář ke stránce zde čeká na agenta} few {# komentáře ke stránce zde čekají na agenta} many {# komentáře ke stránce zde čeká na agenta} other {# komentářů ke stránce zde čeká na agenta}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# hledání} few {# hledání} many {# hledání} other {# hledání}}" @@ -3283,6 +3286,12 @@ msgstr "Klikněte na <0>Importovat motiv a vyberte stažený soubor." msgid "Click a terminal script to edit its details." msgstr "Kliknutím na terminálový skript upravíte jeho podrobnosti." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Klikněte na cokoli na této stránce a okomentujte to. Stránku sleduje agent, který váš komentář převezme a stránku znovu publikuje." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Klikněte na cokoli na této stránce a okomentujte to. Právě ji nesleduje žádný agent, takže se váš komentář uloží na stránce." + msgid "Click here if not redirected" msgstr "Pokud nedojde k přesměrování, klikněte sem" @@ -7144,6 +7153,9 @@ msgstr "Google neudělil trvalý přístup. Odeberte Superset z přístupu třet msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Rozumím" + msgid "Grant the OS permissions Superset needs." msgstr "Udělte systémová oprávnění, která Superset potřebuje." diff --git a/packages/i18n/locales/de/messages.po b/packages/i18n/locales/de/messages.po index 8e5849e4d22..281bb523fdb 100644 --- a/packages/i18n/locales/de/messages.po +++ b/packages/i18n/locales/de/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# Kommentar} other {# Kommentare}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# Datei} other {# Dateien}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# Seitenkommentar wartet hier auf einen Agenten} other {# Seitenkommentare warten hier auf einen Agenten}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# Suche} other {# Suchen}}" @@ -3283,6 +3286,12 @@ msgstr "Klicke auf <0>Theme importieren und wähle die heruntergeladene Date msgid "Click a terminal script to edit its details." msgstr "Klicke ein Terminal-Skript an, um seine Details zu bearbeiten." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Klicke auf ein beliebiges Element dieser Seite, um es zu kommentieren. Ein Agent beobachtet die Seite, greift deinen Kommentar auf und veröffentlicht die Seite neu." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Klicke auf ein beliebiges Element dieser Seite, um es zu kommentieren. Derzeit beobachtet kein Agent die Seite, dein Kommentar wird also auf der Seite gespeichert." + msgid "Click here if not redirected" msgstr "Hier klicken, falls du nicht weitergeleitet wirst" @@ -7144,6 +7153,9 @@ msgstr "Google hat keinen dauerhaften Zugriff gewährt. Entferne Superset aus de msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Verstanden" + msgid "Grant the OS permissions Superset needs." msgstr "Erteile die Systemberechtigungen, die Superset braucht." diff --git a/packages/i18n/locales/en/messages.po b/packages/i18n/locales/en/messages.po index 7cf3ac40d09..d7d20d7e4d3 100644 --- a/packages/i18n/locales/en/messages.po +++ b/packages/i18n/locales/en/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# comment} other {# comments}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# file} other {# files}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# search} other {# searches}}" @@ -3283,6 +3286,12 @@ msgstr "Click <0>Import Theme and select the downloaded file." msgid "Click a terminal script to edit its details." msgstr "Click a terminal script to edit its details." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." + msgid "Click here if not redirected" msgstr "Click here if not redirected" @@ -7144,6 +7153,9 @@ msgstr "Google did not grant lasting access. Remove Superset from your Google ac msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Got it" + msgid "Grant the OS permissions Superset needs." msgstr "Grant the OS permissions Superset needs." diff --git a/packages/i18n/locales/es/messages.po b/packages/i18n/locales/es/messages.po index 5f259376a47..1a32368c4a5 100644 --- a/packages/i18n/locales/es/messages.po +++ b/packages/i18n/locales/es/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# comentario} other {# comentarios}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# archivo} other {# archivos}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# comentario de página espera aquí a un agente} other {# comentarios de página esperan aquí a un agente}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# búsqueda} other {# búsquedas}}" @@ -3283,6 +3286,12 @@ msgstr "Haz clic en <0>Importar tema y selecciona el archivo descargado." msgid "Click a terminal script to edit its details." msgstr "Haz clic en un script de terminal para editar sus detalles." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Haz clic en cualquier elemento de esta página para comentarlo. Un agente la está observando y recogerá tu comentario para volver a publicar la página." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Haz clic en cualquier elemento de esta página para comentarlo. Ahora mismo no hay ningún agente observándola, así que tu comentario queda guardado en la página." + msgid "Click here if not redirected" msgstr "Haz clic aquí si no se te redirige" @@ -7144,6 +7153,9 @@ msgstr "Google no concedió un acceso duradero. Quita Superset del acceso de ter msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Entendido" + msgid "Grant the OS permissions Superset needs." msgstr "Concede los permisos del sistema que Superset necesita." diff --git a/packages/i18n/locales/fr/messages.po b/packages/i18n/locales/fr/messages.po index f5dddc9241d..262acbdaff7 100644 --- a/packages/i18n/locales/fr/messages.po +++ b/packages/i18n/locales/fr/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# commentaire} other {# commentaires}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# fichier} other {# fichiers}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# commentaire de page attend ici un agent} other {# commentaires de page attendent ici un agent}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# recherche} other {# recherches}}" @@ -3283,6 +3286,12 @@ msgstr "Cliquez sur <0>Importer un thème et sélectionnez le fichier télé msgid "Click a terminal script to edit its details." msgstr "Cliquez sur un script de terminal pour modifier ses détails." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Cliquez sur n'importe quel élément de cette page pour le commenter. Un agent surveille la page : il prendra en compte votre commentaire et republiera la page." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Cliquez sur n'importe quel élément de cette page pour le commenter. Aucun agent ne la surveille pour le moment : votre commentaire est enregistré sur la page." + msgid "Click here if not redirected" msgstr "Cliquez ici si la redirection n'a pas lieu" @@ -7144,6 +7153,9 @@ msgstr "Google n'a pas accordé d'accès durable. Retirez Superset des accès ti msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "J'ai compris" + msgid "Grant the OS permissions Superset needs." msgstr "Accordez à Superset les autorisations système dont il a besoin." diff --git a/packages/i18n/locales/id/messages.po b/packages/i18n/locales/id/messages.po index 414bb052447..a501217bfd8 100644 --- a/packages/i18n/locales/id/messages.po +++ b/packages/i18n/locales/id/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# komentar} other {# komentar}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# file} other {# file}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# komentar halaman menunggu agen di sini} other {# komentar halaman menunggu agen di sini}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# pencarian} other {# pencarian}}" @@ -3283,6 +3286,12 @@ msgstr "Klik <0>Import Theme dan pilih file yang sudah diunduh." msgid "Click a terminal script to edit its details." msgstr "Klik sebuah skrip terminal untuk mengedit detailnya." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Klik apa pun di halaman ini untuk mengomentarinya. Ada agen yang sedang mengawasi, dan akan menindaklanjuti komentar Anda lalu menerbitkan ulang halaman ini." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Klik apa pun di halaman ini untuk mengomentarinya. Saat ini tidak ada agen yang mengawasi, jadi komentar Anda disimpan di halaman ini." + msgid "Click here if not redirected" msgstr "Klik di sini kalau tidak dialihkan" @@ -7144,6 +7153,9 @@ msgstr "Google tidak memberikan akses jangka panjang. Hapus Superset dari akses msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Mengerti" + msgid "Grant the OS permissions Superset needs." msgstr "Berikan izin OS yang dibutuhkan Superset." diff --git a/packages/i18n/locales/it/messages.po b/packages/i18n/locales/it/messages.po index ab43e9bcd8e..553aec68082 100644 --- a/packages/i18n/locales/it/messages.po +++ b/packages/i18n/locales/it/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# commento} other {# commenti}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# file} other {# file}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# commento alla pagina è in attesa di un agente qui} other {# commenti alla pagina sono in attesa di un agente qui}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# ricerca} other {# ricerche}}" @@ -3283,6 +3286,12 @@ msgstr "Clicca su <0>Importa tema e seleziona il file scaricato." msgid "Click a terminal script to edit its details." msgstr "Clicca su uno script del terminale per modificarne i dettagli." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Fai clic su qualsiasi elemento di questa pagina per commentarlo. Un agente la sta osservando: prenderà in carico il tuo commento e ripubblicherà la pagina." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Fai clic su qualsiasi elemento di questa pagina per commentarlo. Al momento nessun agente la sta osservando, quindi il tuo commento viene salvato sulla pagina." + msgid "Click here if not redirected" msgstr "Clicca qui se non vieni reindirizzato" @@ -7144,6 +7153,9 @@ msgstr "Google non ha concesso un accesso duraturo. Rimuovi Superset dagli acces msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Ho capito" + msgid "Grant the OS permissions Superset needs." msgstr "Concedi le autorizzazioni di sistema di cui Superset ha bisogno." diff --git a/packages/i18n/locales/ja/messages.po b/packages/i18n/locales/ja/messages.po index 40ab48153ee..55cc8f3750a 100644 --- a/packages/i18n/locales/ja/messages.po +++ b/packages/i18n/locales/ja/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {#件のコメント} other {#件のコメント}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {#件のファイル} other {#件のファイル}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {#件のページコメントがここでエージェントを待っています} other {#件のページコメントがここでエージェントを待っています}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {#件の検索} other {#件の検索}}" @@ -3283,6 +3286,12 @@ msgstr "<0>テーマをインポートをクリックし、ダウンロー msgid "Click a terminal script to edit its details." msgstr "ターミナルスクリプトをクリックして詳細を編集します。" +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "このページの好きな要素をクリックするとコメントできます。エージェントが監視中で、コメントを受け取ってページを再公開します。" + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "このページの好きな要素をクリックするとコメントできます。現在は監視中のエージェントがいないため、コメントはページに保存されます。" + msgid "Click here if not redirected" msgstr "リダイレクトされない場合はこちらをクリック" @@ -7144,6 +7153,9 @@ msgstr "Googleが継続的なアクセスを許可しませんでした。Google msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "了解" + msgid "Grant the OS permissions Superset needs." msgstr "Supersetに必要なOS権限を許可します。" diff --git a/packages/i18n/locales/ko/messages.po b/packages/i18n/locales/ko/messages.po index da98c1b1cad..429978bf22b 100644 --- a/packages/i18n/locales/ko/messages.po +++ b/packages/i18n/locales/ko/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {댓글 #개} other {댓글 #개}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {파일 #개} other {파일 #개}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {페이지 댓글 #개가 여기서 에이전트를 기다리는 중} other {페이지 댓글 #개가 여기서 에이전트를 기다리는 중}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {검색 #회} other {검색 #회}}" @@ -3283,6 +3286,12 @@ msgstr "<0>테마 가져오기를 클릭하고 다운로드한 파일을 선 msgid "Click a terminal script to edit its details." msgstr "터미널 스크립트를 클릭하면 세부 정보를 편집합니다." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "이 페이지의 아무 요소나 클릭해 댓글을 남기세요. 에이전트가 지켜보고 있으며, 댓글을 받아 페이지를 다시 게시합니다." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "이 페이지의 아무 요소나 클릭해 댓글을 남기세요. 지금은 지켜보는 에이전트가 없으므로 댓글은 페이지에 저장됩니다." + msgid "Click here if not redirected" msgstr "이동하지 않으면 여기를 클릭하세요" @@ -7144,6 +7153,9 @@ msgstr "Google이 지속적인 접근 권한을 부여하지 않았습니다. Go msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "알겠습니다" + msgid "Grant the OS permissions Superset needs." msgstr "Superset에 필요한 OS 권한을 허용합니다." diff --git a/packages/i18n/locales/nl/messages.po b/packages/i18n/locales/nl/messages.po index 50da8de9aae..fcab7273b4f 100644 --- a/packages/i18n/locales/nl/messages.po +++ b/packages/i18n/locales/nl/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# opmerking} other {# opmerkingen}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# bestand} other {# bestanden}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# paginareactie wacht hier op een agent} other {# paginareacties wachten hier op een agent}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# zoekopdracht} other {# zoekopdrachten}}" @@ -3283,6 +3286,12 @@ msgstr "Klik op <0>Thema importeren en kies het gedownloade bestand." msgid "Click a terminal script to edit its details." msgstr "Klik op een terminalscript om de details te bewerken." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Klik op iets op deze pagina om erop te reageren. Een agent kijkt mee, pakt je reactie op en publiceert de pagina opnieuw." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Klik op iets op deze pagina om erop te reageren. Er kijkt nu geen agent mee, dus je reactie wordt op de pagina opgeslagen." + msgid "Click here if not redirected" msgstr "Klik hier als je niet wordt doorgestuurd" @@ -7144,6 +7153,9 @@ msgstr "Google heeft geen blijvende toegang verleend. Verwijder Superset uit de msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Begrepen" + msgid "Grant the OS permissions Superset needs." msgstr "Geef Superset de OS-rechten die het nodig heeft." diff --git a/packages/i18n/locales/pl/messages.po b/packages/i18n/locales/pl/messages.po index 83bf1a2a897..2fdcd4c2b88 100644 --- a/packages/i18n/locales/pl/messages.po +++ b/packages/i18n/locales/pl/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# komentarz} few {# komentarze} many {# komentarzy} msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# plik} few {# pliki} many {# plików} other {# pliku}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# komentarz do strony czeka tu na agenta} few {# komentarze do strony czekają tu na agenta} many {# komentarzy do strony czeka tu na agenta} other {# komentarza do strony czeka tu na agenta}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# wyszukiwanie} few {# wyszukiwania} many {# wyszukiwań} other {# wyszukiwania}}" @@ -3283,6 +3286,12 @@ msgstr "Kliknij <0>Importuj motyw i wskaż pobrany plik." msgid "Click a terminal script to edit its details." msgstr "Kliknij skrypt terminala, aby edytować jego szczegóły." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Kliknij dowolny element tej strony, aby go skomentować. Stronę obserwuje agent, który podejmie Twój komentarz i opublikuje stronę ponownie." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Kliknij dowolny element tej strony, aby go skomentować. Obecnie nie obserwuje jej żaden agent, więc Twój komentarz zostanie zapisany na stronie." + msgid "Click here if not redirected" msgstr "Kliknij tutaj, jeśli przekierowanie nie nastąpi" @@ -7144,6 +7153,9 @@ msgstr "Google nie przyznało trwałego dostępu. Usuń Superset z dostępu apli msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Rozumiem" + msgid "Grant the OS permissions Superset needs." msgstr "Przyznaj uprawnienia systemowe, których potrzebuje Superset." diff --git a/packages/i18n/locales/pt-BR/messages.po b/packages/i18n/locales/pt-BR/messages.po index 32b7e5cb762..083c56f8564 100644 --- a/packages/i18n/locales/pt-BR/messages.po +++ b/packages/i18n/locales/pt-BR/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# comentário} other {# comentários}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# arquivo} other {# arquivos}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# comentário da página aguarda um agente aqui} other {# comentários da página aguardam um agente aqui}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# busca} other {# buscas}}" @@ -3283,6 +3286,12 @@ msgstr "Clique em <0>Importar tema e selecione o arquivo baixado." msgid "Click a terminal script to edit its details." msgstr "Clique em um script de terminal para editar os detalhes." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Clique em qualquer elemento desta página para comentá-lo. Um agente está acompanhando e vai considerar seu comentário e republicar a página." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Clique em qualquer elemento desta página para comentá-lo. No momento nenhum agente está acompanhando, então seu comentário fica salvo na página." + msgid "Click here if not redirected" msgstr "Clique aqui se não for redirecionado" @@ -7144,6 +7153,9 @@ msgstr "O Google não concedeu acesso duradouro. Remova o Superset dos acessos d msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Entendi" + msgid "Grant the OS permissions Superset needs." msgstr "Conceda as permissões do sistema de que o Superset precisa." diff --git a/packages/i18n/locales/ru/messages.po b/packages/i18n/locales/ru/messages.po index 34f12a805b2..bf577524907 100644 --- a/packages/i18n/locales/ru/messages.po +++ b/packages/i18n/locales/ru/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# комментарий} few {# комментар msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# файл} few {# файла} many {# файлов} other {# файла}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# комментарий к странице ждёт здесь агента} few {# комментария к странице ждут здесь агента} many {# комментариев к странице ждут здесь агента} other {# комментария к странице ждут здесь агента}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# поиск} few {# поиска} many {# поисков} other {# поиска}}" @@ -3283,6 +3286,12 @@ msgstr "Нажмите <0>Импорт темы и выберите скач msgid "Click a terminal script to edit its details." msgstr "Нажмите на скрипт терминала, чтобы изменить его." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Нажмите на любой элемент этой страницы, чтобы оставить комментарий. За страницей следит агент: он учтёт ваш комментарий и опубликует страницу заново." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Нажмите на любой элемент этой страницы, чтобы оставить комментарий. Сейчас за ней не следит ни один агент, поэтому ваш комментарий сохранится на странице." + msgid "Click here if not redirected" msgstr "Нажмите здесь, если переход не произошёл" @@ -7144,6 +7153,9 @@ msgstr "Google не выдал длительный доступ. Удалите msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Понятно" + msgid "Grant the OS permissions Superset needs." msgstr "Выдайте разрешения ОС, нужные Superset." diff --git a/packages/i18n/locales/tr/messages.po b/packages/i18n/locales/tr/messages.po index d9d6fabda2b..2d5d3a9812d 100644 --- a/packages/i18n/locales/tr/messages.po +++ b/packages/i18n/locales/tr/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# yorum} other {# yorum}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# dosya} other {# dosya}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# sayfa yorumu burada bir ajanı bekliyor} other {# sayfa yorumu burada bir ajanı bekliyor}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# arama} other {# arama}}" @@ -3283,6 +3286,12 @@ msgstr "<0>Temayı İçe Aktar seçeneğine tıklayın ve indirdiğiniz dosy msgid "Click a terminal script to edit its details." msgstr "Ayrıntılarını düzenlemek için bir terminal betiğine tıklayın." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Bu sayfadaki herhangi bir öğeye tıklayarak yorum yapın. Bir ajan sayfayı izliyor; yorumunuzu alıp sayfayı yeniden yayımlayacak." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Bu sayfadaki herhangi bir öğeye tıklayarak yorum yapın. Şu anda sayfayı izleyen bir ajan yok, bu yüzden yorumunuz sayfaya kaydedilir." + msgid "Click here if not redirected" msgstr "Yönlendirilmediyseniz buraya tıklayın" @@ -7144,6 +7153,9 @@ msgstr "Google kalıcı erişim vermedi. Superset'i Google hesabınızın üçü msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Anladım" + msgid "Grant the OS permissions Superset needs." msgstr "Superset'in ihtiyaç duyduğu işletim sistemi izinlerini verin." diff --git a/packages/i18n/locales/vi/messages.po b/packages/i18n/locales/vi/messages.po index d7061fcadba..90a72520fd9 100644 --- a/packages/i18n/locales/vi/messages.po +++ b/packages/i18n/locales/vi/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {# bình luận} other {# bình luận}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {# tệp} other {# tệp}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {# bình luận trên trang đang chờ agent ở đây} other {# bình luận trên trang đang chờ agent ở đây}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {# lượt tìm} other {# lượt tìm}}" @@ -3283,6 +3286,12 @@ msgstr "Nhấp <0>Import Theme và chọn tệp vừa tải." msgid "Click a terminal script to edit its details." msgstr "Nhấp vào một script terminal để sửa chi tiết." +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "Nhấp vào bất kỳ phần nào trên trang này để bình luận. Một agent đang theo dõi và sẽ tiếp nhận bình luận của bạn rồi đăng lại trang." + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "Nhấp vào bất kỳ phần nào trên trang này để bình luận. Hiện không có agent nào đang theo dõi, nên bình luận của bạn được lưu trên trang." + msgid "Click here if not redirected" msgstr "Nhấp vào đây nếu không được chuyển hướng" @@ -7144,6 +7153,9 @@ msgstr "Google không cấp quyền truy cập lâu dài. Hãy gỡ Superset kh msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "Đã hiểu" + msgid "Grant the OS permissions Superset needs." msgstr "Cấp các quyền hệ điều hành mà Superset cần." diff --git a/packages/i18n/locales/zh-CN/messages.po b/packages/i18n/locales/zh-CN/messages.po index 6d1746f47f3..8dd8eed1c68 100644 --- a/packages/i18n/locales/zh-CN/messages.po +++ b/packages/i18n/locales/zh-CN/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {#条评论} other {#条评论}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {#个文件} other {#个文件}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {#条页面评论正在这里等待智能体} other {#条页面评论正在这里等待智能体}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {#次搜索} other {#次搜索}}" @@ -3283,6 +3286,12 @@ msgstr "点击<0>导入主题,选择下载好的文件。" msgid "Click a terminal script to edit its details." msgstr "点击终端脚本以编辑其详情。" +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "点击本页任意元素即可评论。有智能体正在关注,会接收你的评论并重新发布页面。" + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "点击本页任意元素即可评论。目前没有智能体在关注,你的评论会保存在页面上。" + msgid "Click here if not redirected" msgstr "如果没有自动跳转,请点击这里" @@ -7144,6 +7153,9 @@ msgstr "Google没有授予持久访问权限。请在你的Google账户的第三 msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "知道了" + msgid "Grant the OS permissions Superset needs." msgstr "授予Superset所需的系统权限。" diff --git a/packages/i18n/locales/zh-TW/messages.po b/packages/i18n/locales/zh-TW/messages.po index e710d97df03..54f5da8452b 100644 --- a/packages/i18n/locales/zh-TW/messages.po +++ b/packages/i18n/locales/zh-TW/messages.po @@ -589,6 +589,9 @@ msgstr "{count, plural, one {#條評論} other {#條評論}}" msgid "{count, plural, one {# file} other {# files}}" msgstr "{count, plural, one {#個檔案} other {#個檔案}}" +msgid "{count, plural, one {# page comment is waiting on an agent here} other {# page comments are waiting on an agent here}}" +msgstr "{count, plural, one {#則頁面留言正在這裡等待代理程式處理} other {#則頁面留言正在這裡等待代理程式處理}}" + msgid "{count, plural, one {# search} other {# searches}}" msgstr "{count, plural, one {#次搜尋} other {#次搜尋}}" @@ -3283,6 +3286,12 @@ msgstr "點選<0>匯入主題,選擇下載好的檔案。" msgid "Click a terminal script to edit its details." msgstr "點選終端指令碼以編輯其詳情。" +msgid "Click anything on this page to comment on it. An agent is watching, and will pick your comment up and republish the page." +msgstr "點選本頁任何元素即可留言。有代理程式正在關注,會接收你的留言並重新發布頁面。" + +msgid "Click anything on this page to comment on it. No agent is watching right now, so your comment is saved on the page." +msgstr "點選本頁任何元素即可留言。目前沒有代理程式在關注,你的留言會保存在頁面上。" + msgid "Click here if not redirected" msgstr "如果沒有自動跳轉,請點選這裡" @@ -7144,6 +7153,9 @@ msgstr "Google沒有授予持久存取權限。請在你的Google帳戶的第三 msgid "Google Search Console" msgstr "Google Search Console" +msgid "Got it" +msgstr "知道了" + msgid "Grant the OS permissions Superset needs." msgstr "授予Superset所需的系統權限。" diff --git a/packages/trpc/src/router/page-comment/page-comment.ts b/packages/trpc/src/router/page-comment/page-comment.ts index a385188496a..06c8e20e6db 100644 --- a/packages/trpc/src/router/page-comment/page-comment.ts +++ b/packages/trpc/src/router/page-comment/page-comment.ts @@ -6,9 +6,10 @@ import { pageVersions, type SelectPage, users, + workspacePages, } from "@superset/db/schema"; import { TRPCError, type TRPCRouterRecord } from "@trpc/server"; -import { and, asc, eq, isNotNull, isNull } from "drizzle-orm"; +import { and, asc, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm"; import { protectedProcedure, userError } from "../../trpc"; import { assertPageReadable } from "../page/access"; import { requireActiveOrgMembership } from "../utils/active-org"; @@ -26,6 +27,7 @@ import { resolvePageCommentThreadSchema, } from "./schema"; import { shapeComment, shapeThread } from "./shape"; +import { countWaitingByWorkspace } from "./waiting"; async function loadReadablePage({ pageId, @@ -86,6 +88,43 @@ async function loadThread({ } export const pageCommentRouter = { + waitingByWorkspace: protectedProcedure.query(async ({ ctx }) => { + const organizationId = await requireActiveOrgMembership(ctx); + const userId = ctx.session.user.id; + + const rows = await db + .select({ + workspaceId: workspacePages.workspaceId, + agentActivatedAt: pageCommentThreads.agentActivatedAt, + resolvedAt: pageCommentThreads.resolvedAt, + lastAuthorKind: sql< + "human" | "agent" | null + >`(select ${pageComments.authorKind} from ${pageComments} + where ${pageComments.threadId} = ${pageCommentThreads.id} + and ${pageComments.deletedAt} is null + order by ${pageComments.createdAt} desc, ${pageComments.id} desc + limit 1)`, + watchedByAgent: pages.watchedByAgent, + watchHeartbeatAt: pages.watchHeartbeatAt, + }) + .from(pageCommentThreads) + .innerJoin(pages, eq(pages.id, pageCommentThreads.pageId)) + .innerJoin(workspacePages, eq(workspacePages.pageId, pages.id)) + .where( + and( + eq(pages.organizationId, organizationId), + isNotNull(pageCommentThreads.agentActivatedAt), + isNull(pageCommentThreads.resolvedAt), + or( + ne(pages.visibility, "just_me"), + eq(pages.createdByUserId, userId), + ), + ), + ); + + return countWaitingByWorkspace(rows, Date.now()); + }), + list: protectedProcedure .input(listPageCommentsSchema) .query(async ({ ctx, input }) => { diff --git a/packages/trpc/src/router/page-comment/waiting.test.ts b/packages/trpc/src/router/page-comment/waiting.test.ts new file mode 100644 index 00000000000..7b27fad84fc --- /dev/null +++ b/packages/trpc/src/router/page-comment/waiting.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, it } from "bun:test"; +import { WATCH_STALE_MS } from "../page/watch"; +import { + countWaitingByWorkspace, + isWaitingOnAgent, + type WaitingThreadRow, +} from "./waiting"; + +const activated = new Date("2026-09-01T00:00:00Z"); +const now = new Date("2026-09-01T12:00:00Z").getTime(); + +function thread( + overrides: Partial> = {}, +): Omit { + return { + agentActivatedAt: activated, + resolvedAt: null, + lastAuthorKind: "human", + watchedByAgent: "claude", + watchHeartbeatAt: new Date(now), + ...overrides, + }; +} + +describe("isWaitingOnAgent", () => { + it("waits when an activated, unresolved, watched thread ends on a human", () => { + expect(isWaitingOnAgent(thread(), now)).toBe(true); + }); + + it("does not wait when no agent has been activated on the thread", () => { + expect(isWaitingOnAgent(thread({ agentActivatedAt: null }), now)).toBe( + false, + ); + }); + + it("does not wait once the thread is resolved", () => { + expect(isWaitingOnAgent(thread({ resolvedAt: new Date() }), now)).toBe( + false, + ); + }); + + it("does not wait while the agent's reply is the last word", () => { + expect(isWaitingOnAgent(thread({ lastAuthorKind: "agent" }), now)).toBe( + false, + ); + }); + + it("waits again when a human follows up after an agent reply", () => { + expect(isWaitingOnAgent(thread({ lastAuthorKind: "human" }), now)).toBe( + true, + ); + }); + + it("does not wait when every comment on the thread was deleted", () => { + expect(isWaitingOnAgent(thread({ lastAuthorKind: null }), now)).toBe(false); + }); + + it("does not wait when the page was never watched", () => { + expect( + isWaitingOnAgent( + thread({ watchedByAgent: null, watchHeartbeatAt: null }), + now, + ), + ).toBe(false); + }); + + it("stops waiting once the watcher's heartbeat goes stale", () => { + const watched = thread({ + watchHeartbeatAt: new Date(now - WATCH_STALE_MS + 1_000), + }); + + expect(isWaitingOnAgent(watched, now)).toBe(true); + expect(isWaitingOnAgent(watched, now + 2_000)).toBe(false); + }); + + it("keeps waiting while the heartbeat stays inside the stale window", () => { + expect( + isWaitingOnAgent( + thread({ watchHeartbeatAt: new Date(now - WATCH_STALE_MS + 1) }), + now, + ), + ).toBe(true); + }); +}); + +describe("countWaitingByWorkspace", () => { + it("returns nothing when no thread is waiting", () => { + expect( + countWaitingByWorkspace( + [ + { workspaceId: "w1", ...thread({ lastAuthorKind: "agent" }) }, + { workspaceId: "w2", ...thread({ resolvedAt: activated }) }, + ], + now, + ), + ).toEqual([]); + }); + + it("counts waiting threads per workspace and drops the rest", () => { + expect( + countWaitingByWorkspace( + [ + { workspaceId: "w1", ...thread() }, + { workspaceId: "w1", ...thread() }, + { workspaceId: "w1", ...thread({ lastAuthorKind: "agent" }) }, + { workspaceId: "w2", ...thread() }, + { workspaceId: "w3", ...thread({ agentActivatedAt: null }) }, + ], + now, + ), + ).toEqual([ + { workspaceId: "w1", waitingCount: 2 }, + { workspaceId: "w2", waitingCount: 1 }, + ]); + }); + + it("counts one page linked to two workspaces against both", () => { + expect( + countWaitingByWorkspace( + [ + { workspaceId: "w1", ...thread() }, + { workspaceId: "w2", ...thread() }, + ], + now, + ), + ).toEqual([ + { workspaceId: "w1", waitingCount: 1 }, + { workspaceId: "w2", waitingCount: 1 }, + ]); + }); + + it("drops a workspace entirely once its watcher stops heartbeating", () => { + const rows: WaitingThreadRow[] = [ + { workspaceId: "w1", ...thread() }, + { workspaceId: "w1", ...thread() }, + ]; + + expect(countWaitingByWorkspace(rows, now)).toEqual([ + { workspaceId: "w1", waitingCount: 2 }, + ]); + expect(countWaitingByWorkspace(rows, now + WATCH_STALE_MS)).toEqual([]); + }); + + it("counts only the workspaces whose pages are still watched", () => { + expect( + countWaitingByWorkspace( + [ + { workspaceId: "w1", ...thread() }, + { + workspaceId: "w2", + ...thread({ + watchHeartbeatAt: new Date(now - WATCH_STALE_MS), + }), + }, + ], + now, + ), + ).toEqual([{ workspaceId: "w1", waitingCount: 1 }]); + }); +}); diff --git a/packages/trpc/src/router/page-comment/waiting.ts b/packages/trpc/src/router/page-comment/waiting.ts new file mode 100644 index 00000000000..656f9848902 --- /dev/null +++ b/packages/trpc/src/router/page-comment/waiting.ts @@ -0,0 +1,43 @@ +import type { SelectPageComment } from "@superset/db/schema"; +import { watchState } from "../page/watch"; + +export interface WaitingThreadRow { + workspaceId: string; + agentActivatedAt: Date | null; + resolvedAt: Date | null; + lastAuthorKind: SelectPageComment["authorKind"] | null; + watchedByAgent: string | null; + watchHeartbeatAt: Date | null; +} + +export interface WorkspaceWaitingCount { + workspaceId: string; + waitingCount: number; +} + +export function isWaitingOnAgent( + thread: Omit, + now: number, +): boolean { + return ( + thread.agentActivatedAt !== null && + thread.resolvedAt === null && + thread.lastAuthorKind === "human" && + watchState(thread, now).watching + ); +} + +export function countWaitingByWorkspace( + rows: WaitingThreadRow[], + now: number, +): WorkspaceWaitingCount[] { + const counts = new Map(); + for (const row of rows) { + if (!isWaitingOnAgent(row, now)) continue; + counts.set(row.workspaceId, (counts.get(row.workspaceId) ?? 0) + 1); + } + return [...counts].map(([workspaceId, waitingCount]) => ({ + workspaceId, + waitingCount, + })); +} diff --git a/packages/ui/src/components/PageComments/components/PageCommentHint/PageCommentHint.test.tsx b/packages/ui/src/components/PageComments/components/PageCommentHint/PageCommentHint.test.tsx new file mode 100644 index 00000000000..5c3000e1331 --- /dev/null +++ b/packages/ui/src/components/PageComments/components/PageCommentHint/PageCommentHint.test.tsx @@ -0,0 +1,53 @@ +import { describe, expect, it } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import { PageCommentHint } from "./PageCommentHint"; + +function render(props: { watching: boolean }): string { + return renderToStaticMarkup( + {}} />, + ); +} + +describe("PageCommentHint", () => { + it("promises a republish when an agent is watching", () => { + const markup = render({ watching: true }); + + expect(markup).toContain("An agent is watching"); + expect(markup).toContain("republish the page"); + expect(markup).not.toContain("No agent is watching"); + }); + + it("promises nothing when no agent is watching", () => { + const markup = render({ watching: false }); + + expect(markup).toContain("No agent is watching"); + expect(markup).toContain("saved on the page"); + expect(markup).not.toContain("republish the page"); + }); + + it("claims no delivery when no agent is watching", () => { + const markup = render({ watching: false }); + + for (const promise of [ + "recorded for", + "published the page", + "pick your comment up", + "sent to", + "notified", + ]) { + expect(markup).not.toContain(promise); + } + }); + + it("never names the watching agent", () => { + expect(render({ watching: true })).not.toContain("claude"); + }); + + it("always tells the reader that clicking is what starts a comment", () => { + for (const watching of [true, false]) { + expect(render({ watching })).toContain( + "Click anything on this page to comment on it.", + ); + } + }); +}); diff --git a/packages/ui/src/components/PageComments/components/PageCommentHint/PageCommentHint.tsx b/packages/ui/src/components/PageComments/components/PageCommentHint/PageCommentHint.tsx new file mode 100644 index 00000000000..3a8f5a8a87f --- /dev/null +++ b/packages/ui/src/components/PageComments/components/PageCommentHint/PageCommentHint.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { Trans } from "@lingui/react/macro"; +import { MousePointerClick } from "lucide-react"; +import { Button } from "../../../ui/button"; + +interface PageCommentHintProps { + watching: boolean; + onDismiss: () => void; +} + +export function PageCommentHint({ watching, onDismiss }: PageCommentHintProps) { + return ( +
+ + + {watching ? ( + + Click anything on this page to comment on it. An agent is watching, + and will pick your comment up and republish the page. + + ) : ( + + Click anything on this page to comment on it. No agent is watching + right now, so your comment is saved on the page. + + )} + + + +
+ ); +} diff --git a/packages/ui/src/components/PageComments/components/PageCommentHint/index.ts b/packages/ui/src/components/PageComments/components/PageCommentHint/index.ts new file mode 100644 index 00000000000..733dc821c01 --- /dev/null +++ b/packages/ui/src/components/PageComments/components/PageCommentHint/index.ts @@ -0,0 +1 @@ +export { PageCommentHint } from "./PageCommentHint"; diff --git a/packages/ui/src/components/PageComments/index.ts b/packages/ui/src/components/PageComments/index.ts index 09d5b824a2b..a6cb98329d6 100644 --- a/packages/ui/src/components/PageComments/index.ts +++ b/packages/ui/src/components/PageComments/index.ts @@ -16,6 +16,7 @@ export { CommentModeToggle, } from "./components/CommentModeToggle"; export { CommentsPanel } from "./components/CommentsPanel"; +export { PageCommentHint } from "./components/PageCommentHint"; export { PageCommentsView } from "./components/PageCommentsView"; export { PageFrame } from "./components/PageFrame"; export {