From c82530686b993983293cc4f564d13ebbb52167bc Mon Sep 17 00:00:00 2001 From: bk-agent-01 Date: Fri, 13 Nov 2026 08:35:48 +0000 Subject: [PATCH 01/15] feat(sidebar): new session from a group header, drag sessions into groups, device-local group mute Co-Authored-By: Claude Opus 5.5 --- .../src/components/PhaseGroupedSidebar.tsx | 269 ++++++++++++++++-- .../ThreadNotificationCoordinator.tsx | 18 +- .../PhaseSidebarGroupDrop.logic.test.ts | 56 ++++ .../sidebar/PhaseSidebarGroupDrop.logic.ts | 49 ++++ .../usePhaseSidebarCustomGroupRegistry.ts | 50 +--- .../src/fork/draftCustomGroupStore.test.ts | 56 ++++ apps/web/src/fork/draftCustomGroupStore.ts | 123 ++++++++ .../src/fork/threadCreationMetadata.test.ts | 17 ++ apps/web/src/fork/threadCreationMetadata.ts | 5 + .../web/src/phaseSidebarGroupingStore.test.ts | 30 ++ apps/web/src/phaseSidebarGroupingStore.ts | 15 +- docs/user/thread-sidebar.md | 19 +- .../phaseSidebarCustomGroupRegistry.test.ts | 59 ++++ .../state/phaseSidebarCustomGroupRegistry.ts | 38 ++- .../src/state/phaseSidebarGrouping.test.ts | 115 ++++++++ .../src/state/phaseSidebarGrouping.ts | 106 ++++++- 16 files changed, 926 insertions(+), 99 deletions(-) create mode 100644 apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.test.ts create mode 100644 apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.ts create mode 100644 apps/web/src/fork/draftCustomGroupStore.test.ts create mode 100644 apps/web/src/fork/draftCustomGroupStore.ts diff --git a/apps/web/src/components/PhaseGroupedSidebar.tsx b/apps/web/src/components/PhaseGroupedSidebar.tsx index 0704d304fbb7a..627135f4f9f9b 100644 --- a/apps/web/src/components/PhaseGroupedSidebar.tsx +++ b/apps/web/src/components/PhaseGroupedSidebar.tsx @@ -82,6 +82,7 @@ import { useMemo, useRef, useState, + type DragEvent as ReactDragEvent, type MouseEvent as ReactMouseEvent, type ReactNode, } from "react"; @@ -269,6 +270,13 @@ import { // T3-CUSTOM(expbkt3): shared custom groups and their colours (XFN-59). import { PhaseSidebarGroupColorSwatches } from "./sidebar/PhaseSidebarGroupColorSwatches"; import { usePhaseSidebarCustomGroupRegistry } from "./sidebar/usePhaseSidebarCustomGroupRegistry"; +// T3-CUSTOM(expbkt3): drag a session onto a group; "+" starts a session in a group. +import { + PHASE_SIDEBAR_ROW_DRAG_TYPE, + phaseSidebarSupportsMouseDrag, + resolvePhaseSidebarRowDrop, +} from "./sidebar/PhaseSidebarGroupDrop.logic"; +import { useDraftCustomGroupStore } from "../fork/draftCustomGroupStore"; import { MoveUnderSessionDialog } from "./sidebar/MoveUnderSessionDialog"; import { NewThreadProjectPicker } from "./sidebar/NewThreadProjectPicker"; // T3-CUSTOM(expbkt3): the dedicated unstarted-drafts group shares normal composer state. @@ -1133,6 +1141,8 @@ interface PhaseThreadRowProps { readonly customGroupLabel?: string | null; /** The group's colour (a hex value) from the shared registry, tinting that chip. */ readonly customGroupColor?: string | null; + /** Present in Custom mode with a mouse: the row drags onto a group section. */ + readonly dragActions?: PhaseThreadRowDragActions; // T3-CUSTOM(expbkt3): END } @@ -1143,6 +1153,19 @@ interface PhaseThreadRowGroupActions { readonly onCreateGroupWith: (row: PhaseSidebarRow) => void; } +/** T3-CUSTOM(expbkt3): dragging a row onto a custom group section; one stable object. */ +interface PhaseThreadRowDragActions { + readonly onDragStart: (row: PhaseSidebarRow) => void; + readonly onDragEnd: () => void; +} + +/** T3-CUSTOM(expbkt3): a custom group section as a drop target for a dragged row. */ +interface PhaseSidebarSectionRowDropTarget { + /** Whether the row being dragged may be dropped on `section` (not its own group). */ + readonly accepts: (section: PhaseSidebarGroupSection) => boolean; + readonly drop: (section: PhaseSidebarGroupSection) => void; +} + /** * T3-CUSTOM(expbkt3): Tree actions, keyed by scoped thread key so one object * instance serves every row. @@ -1225,6 +1248,7 @@ const PhaseThreadRow = memo(function PhaseThreadRow(props: PhaseThreadRowProps) customGroupId, customGroupLabel, customGroupColor, + dragActions, } = props; const threadRef = scopeThreadRef(row.thread.environmentId, row.thread.id); const threadKey = scopedThreadKey(threadRef); @@ -1820,6 +1844,19 @@ const PhaseThreadRow = memo(function PhaseThreadRow(props: PhaseThreadRowProps) : undefined } data-testid={`phase-thread-row-${row.thread.id}`} + // T3-CUSTOM(expbkt3): Custom mode drags the row onto a group section. Only a + // custom payload type is set, so the search box never takes the drop. + {...(dragActions !== undefined && !renaming && !isArchiving + ? { + draggable: true, + onDragStart: (event: ReactDragEvent) => { + event.dataTransfer.effectAllowed = "move"; + event.dataTransfer.setData(PHASE_SIDEBAR_ROW_DRAG_TYPE, threadKey); + dragActions.onDragStart(row); + }, + onDragEnd: () => dragActions.onDragEnd(), + } + : {})} onClick={handleClick} onDoubleClick={() => onStartRename(row)} onContextMenu={(event) => { @@ -2946,6 +2983,10 @@ export function PhaseGroupedSidebar() { const forgetCustomGroup = usePhaseSidebarGroupingStore((state) => state.forgetGroup); const moveCustomGroup = usePhaseSidebarGroupingStore((state) => state.moveGroup); const pruneGrouping = usePhaseSidebarGroupingStore((state) => state.prune); + // The header bell: this device's own mode, kept in local storage (see below). + const setGroupNotificationsLocally = usePhaseSidebarGroupingStore( + (state) => state.setGroupNotifications, + ); // "New group…" from a row files that row; "Rename" on a section renames it. const [groupNameDialogRow, setGroupNameDialogRow] = useState(null); const [groupRenameTarget, setGroupRenameTarget] = useState<{ @@ -3071,7 +3112,6 @@ export function PhaseGroupedSidebar() { renameGroup: renameSharedCustomGroup, deleteGroup: deleteSharedCustomGroup, recolorGroup: recolorSharedCustomGroup, - setGroupNotifications: setSharedCustomGroupNotifications, } = customGroupRegistry; const canRecolorCustomGroups = customGroupRegistry.homeEnvironmentId !== null; const createCustomGroup = useCallback( @@ -3105,16 +3145,6 @@ export function PhaseGroupedSidebar() { }, [deleteSharedCustomGroup, forgetCustomGroup, rowsInCustomGroup, setThreadCustomGroup], ); - // T3-CUSTOM(expbkt3): the header bell cycles all → parents → off. - const setCustomGroupNotifications = useCallback( - (groupId: string, notifications: ThreadCustomGroupNotificationMode) => - setSharedCustomGroupNotifications( - groupId, - customGroupLabels.get(groupId) ?? groupId, - notifications, - ), - [customGroupLabels, setSharedCustomGroupNotifications], - ); const recolorCustomGroup = useCallback( (groupId: string, colorId: string | null) => recolorSharedCustomGroup(groupId, customGroupLabels.get(groupId) ?? groupId, colorId), @@ -3134,6 +3164,41 @@ export function PhaseGroupedSidebar() { }), [customGroupLabels, customGroupOptions, setThreadCustomGroup], ); + // Custom mode: drag a session with the mouse onto a group's section to file + // it there, or onto "Ungrouped" to take it out — the same write as "Move to + // group". The dragged row sits in a ref, so a drag re-renders only the + // section it hovers. + const draggedRowRef = useRef(null); + const rowDragActions = useMemo( + () => + grouping.groupBy === "custom" && phaseSidebarSupportsMouseDrag() + ? { + onDragStart: (row) => { + draggedRowRef.current = row; + }, + onDragEnd: () => { + draggedRowRef.current = null; + }, + } + : undefined, + [grouping.groupBy], + ); + const sectionRowDropTarget = useMemo( + () => ({ + accepts: (section) => { + const row = draggedRowRef.current; + return row !== null && resolvePhaseSidebarRowDrop(row.customGroup, section) !== null; + }, + drop: (section) => { + const row = draggedRowRef.current; + draggedRowRef.current = null; + if (row === null) return; + const target = resolvePhaseSidebarRowDrop(row.customGroup, section); + if (target !== null) void setThreadCustomGroup(row, target.customGroup); + }, + }), + [setThreadCustomGroup], + ); /** The lifecycle groups, kept for the callers that reason about phases. */ const groups = sections; // T3-CUSTOM(expbkt3): END @@ -4087,20 +4152,63 @@ export function PhaseGroupedSidebar() { (row: PhaseSidebarRow) => void requestArchive(row), [requestArchive], ); - const startGlobalNewThread = useCallback(() => { - if (projects.length === 1 && projects[0]) { - void handleNewThread(scopeProjectRef(projects[0].environmentId, projects[0].id)); - return; - } - setProjectPickerOpen(true); - }, [handleNewThread, projects]); + // T3-CUSTOM(expbkt3): BEGIN — a custom group header's "+" starts a session + // in that group. The draft remembers the group (by its thread id) until its + // first send names it in the create input; a plain New thread clears it, so + // a reused draft never carries an old choice. + const setDraftCustomGroup = useDraftCustomGroupStore((state) => state.setTarget); + const pendingNewThreadGroupRef = useRef(null); + const openNewThread = useCallback( + (project: Pick, customGroup: string | null) => { + void handleNewThread(scopeProjectRef(project.environmentId, project.id)).then((draft) => { + if (draft) setDraftCustomGroup(draft.threadId, customGroup); + }); + }, + [handleNewThread, setDraftCustomGroup], + ); + // One project goes straight to its draft; several open the picker, which + // then knows which group the session is for. + const startNewThreadIn = useCallback( + (customGroup: string | null) => { + pendingNewThreadGroupRef.current = customGroup; + if (projects.length === 1 && projects[0]) { + openNewThread(projects[0], customGroup); + return; + } + setProjectPickerOpen(true); + }, + [openNewThread, projects], + ); + const startGlobalNewThread = useCallback(() => startNewThreadIn(null), [startNewThreadIn]); const selectNewThreadProject = useCallback( (project: Project) => { setProjectPickerOpen(false); - void handleNewThread(scopeProjectRef(project.environmentId, project.id)); + openNewThread(project, pendingNewThreadGroupRef.current); + pendingNewThreadGroupRef.current = null; }, - [handleNewThread], + [openNewThread], ); + // Forget the group of a draft that is gone: sent (its create input already + // named the group) or discarded. Cheap when no draft has a group. + useEffect(() => { + const prune = () => { + const { targets, prune: pruneTargets } = useDraftCustomGroupStore.getState(); + if (Object.keys(targets).length === 0) return; + if (!useComposerDraftStore.persist.hasHydrated()) return; + pruneTargets( + new Set( + Object.values(useComposerDraftStore.getState().draftThreadsByThreadKey).map( + (draft) => draft.threadId, + ), + ), + ); + }; + prune(); + return useComposerDraftStore.subscribe((state, previous) => { + if (state.draftThreadsByThreadKey !== previous.draftThreadsByThreadKey) prune(); + }); + }, []); + // T3-CUSTOM(expbkt3): END // T3-CUSTOM(expbkt3): BEGIN — the project picker names the machine a project // lives on, so two same-named projects are told apart by where they run. // Stable identities: the picker memoizes its option list on these. @@ -4188,6 +4296,7 @@ export function PhaseGroupedSidebar() { onCreateThread={createThreadFromRow} // T3-CUSTOM(expbkt3): custom groups. {...(groupActions ? { groupActions } : {})} + {...(rowDragActions ? { dragActions: rowDragActions } : {})} customGroupId={phaseSidebarCustomGroupIdForRow(row)} // T3-CUSTOM(expbkt3): in Custom mode a chip names the group as the // registry spells it (the section header's label), not the row's own spelling. @@ -4353,20 +4462,23 @@ export function PhaseGroupedSidebar() { onRenameGroup: () => setGroupRenameTarget({ id: section.id, label: section.label }), onDeleteGroup: () => deleteCustomGroup(section.id), + onNewSessionInGroup: () => startNewThreadIn(section.label), ...(canRecolorCustomGroups ? { onRecolorGroup: (colorId: string | null) => recolorCustomGroup(section.id, colorId), - // T3-CUSTOM(expbkt3): shared like the colour, so the same hosts can write it. - onSetGroupNotifications: (mode: ThreadCustomGroupNotificationMode) => - setCustomGroupNotifications(section.id, mode), } : {}), } : {})} - {...(section.kind === "custom" && section.isUngrouped && canRecolorCustomGroups - ? // T3-CUSTOM(expbkt3): "Ungrouped" has a bell too, kept as a host setting. - { onSetGroupNotifications: customGroupRegistry.setUngroupedNotifications } + // T3-CUSTOM(expbkt3): every group's bell, "Ungrouped" included, is this + // device's own mode, so it needs no host this session may write. + {...(section.kind === "custom" + ? { + onSetGroupNotifications: (mode: ThreadCustomGroupNotificationMode) => + setGroupNotificationsLocally(section.id, mode), + ...(rowDragActions ? { rowDropTarget: sectionRowDropTarget } : {}), + } : {})} /> ))} @@ -4521,7 +4633,12 @@ const GROUP_NOTIFICATION_LABELS = { * A custom group's header also carries its colour (a dot and a tint, from the * shared registry) and its actions — colour, rename, delete — which float * inside the right end of the pill on hover or keyboard focus, so a managed - * header is exactly as wide as every other one (XFN-59). + * header is exactly as wide as every other one (XFN-59). Beside its label sit + * the notification bell and a "+" that starts a session in the group. + * + * In Custom mode the whole section (header and rows) is a drop target for a + * dragged session row; the highlight is this section's own state, so a drag + * re-renders nothing else. */ function PhaseSidebarSectionBlock({ section, @@ -4533,6 +4650,8 @@ function PhaseSidebarSectionBlock({ onDeleteGroup, onRecolorGroup, onSetGroupNotifications, + onNewSessionInGroup, + rowDropTarget, }: { readonly section: PhaseSidebarGroupSection; readonly collapsed: boolean; @@ -4544,8 +4663,12 @@ function PhaseSidebarSectionBlock({ readonly onDeleteGroup?: () => void; /** Absent when no connected host keeps shared groups for this session. */ readonly onRecolorGroup?: (colorId: string | null) => void; - /** T3-CUSTOM(expbkt3): absent when no connected host keeps shared groups for this session. */ + /** T3-CUSTOM(expbkt3): this device's notification mode for the group. */ readonly onSetGroupNotifications?: (mode: ThreadCustomGroupNotificationMode) => void; + /** T3-CUSTOM(expbkt3): the header's "+"; absent on "Ungrouped" and other sections. */ + readonly onNewSessionInGroup?: () => void; + /** T3-CUSTOM(expbkt3): Custom mode with a mouse: dragged rows drop here. */ + readonly rowDropTarget?: PhaseSidebarSectionRowDropTarget; }) { const { summary } = section; const phaseId = phaseSidebarSectionPhase(section); @@ -4559,6 +4682,52 @@ function PhaseSidebarSectionBlock({ const notificationMode = section.notifications ?? "all"; const NotificationIcon = GROUP_NOTIFICATION_ICONS[notificationMode]; const [colorPickerOpen, setColorPickerOpen] = useState(false); + // T3-CUSTOM(expbkt3): BEGIN — a dragged session row over this section. + const [rowDropActive, setRowDropActive] = useState(false); + // A drag cancelled (Escape) or dropped elsewhere may never send this section + // a dragleave, so the highlight also clears when any drag ends. + useEffect(() => { + if (!rowDropActive) return; + const clear = () => setRowDropActive(false); + window.addEventListener("dragend", clear, true); + window.addEventListener("drop", clear, true); + return () => { + window.removeEventListener("dragend", clear, true); + window.removeEventListener("drop", clear, true); + }; + }, [rowDropActive]); + const acceptsRowDrag = (event: ReactDragEvent) => + rowDropTarget !== undefined && + event.dataTransfer.types.includes(PHASE_SIDEBAR_ROW_DRAG_TYPE) && + rowDropTarget.accepts(section); + const rowDropHandlers = + rowDropTarget === undefined + ? {} + : { + onDragEnter: (event: ReactDragEvent) => { + if (!acceptsRowDrag(event)) return; + event.preventDefault(); + setRowDropActive(true); + }, + onDragOver: (event: ReactDragEvent) => { + if (!acceptsRowDrag(event)) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + if (!rowDropActive) setRowDropActive(true); + }, + onDragLeave: (event: ReactDragEvent) => { + const next = event.relatedTarget; + if (next instanceof Node && event.currentTarget.contains(next)) return; + setRowDropActive(false); + }, + onDrop: (event: ReactDragEvent) => { + setRowDropActive(false); + if (!acceptsRowDrag(event)) return; + event.preventDefault(); + rowDropTarget?.drop(section); + }, + }; + // T3-CUSTOM(expbkt3): END // A custom group says in words what needs you, open or closed, in place of // its session count and the closed-header pills. const summaryWords = @@ -4646,7 +4815,7 @@ function PhaseSidebarSectionBlock({ - {GROUP_NOTIFICATION_LABELS[notificationMode]} · click for{" "} + {GROUP_NOTIFICATION_LABELS[notificationMode]} on this device · click for{" "} {GROUP_NOTIFICATION_LABELS[ nextThreadCustomGroupNotificationMode(notificationMode) ].toLowerCase()} @@ -4659,6 +4828,35 @@ function PhaseSidebarSectionBlock({ data-testid="phase-sidebar-section-notifications" /> ) : null} + {/* T3-CUSTOM(expbkt3): "+" starts a session in this group; on hover, like the bell. */} + {onNewSessionInGroup ? ( + + { + event.stopPropagation(); + onNewSessionInGroup(); + }} + onKeyDown={(event) => { + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + event.stopPropagation(); + onNewSessionInGroup(); + }} + /> + } + > + + + New session in {section.label} + + ) : null} {summaryWords.length > 0 ? ( {/* A quiet boundary before live agent work. */} {showRunningDivider ? : null} @@ -4781,7 +4985,10 @@ function PhaseSidebarSectionBlock({ )} {collapsed ? null : section.nodes.length === 0 ? (

- Empty — use “Move to group” on a session. + {/* T3-CUSTOM(expbkt3): rows drag onto a group in Custom mode. */} + {rowDropTarget + ? "Empty — drag a session here, or use “Move to group” on it." + : "Empty — use “Move to group” on a session."}

) : (
    diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index aa8941d8e296c..0a6829ac27c44 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -26,7 +26,8 @@ import { import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings"; import { isWindowsPlatform } from "../lib/utils"; import { environmentSummaries } from "../state/presentation"; -// T3-CUSTOM(expbkt3): per-group notification mode. +// T3-CUSTOM(expbkt3): per-group notification mode, and this device's own override of it. +import { usePhaseSidebarGroupingStore } from "../phaseSidebarGroupingStore"; import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment"; import { environmentServerConfigsAtom } from "../state/server"; import { environmentShell } from "../state/shell"; @@ -98,14 +99,16 @@ export function startThreadNotifications( } else openToasts.set(key, remaining); }; // T3-CUSTOM(expbkt3): BEGIN — a custom group's notification mode (all, parents, off). - // The mode lives in the shared group registry, merged across hosts the way the - // sidebar shows it, so the bell a user sees is the rule that applies. + // The shared mode lives in the group registry, merged across hosts the way the + // sidebar shows it; this device's own mode (the sidebar bell, kept in local + // storage) outranks it, so the bell a user sees is the rule that applies. const currentGroupRegistry = () => { const configs = registry.get(environmentServerConfigsAtom); const primary = registry.get(primaryEnvironmentIdAtom); return { groups: buildPhaseSidebarCustomGroupRegistry(configs, primary), ungrouped: resolvePhaseSidebarUngroupedNotifications(configs, primary), + overrides: usePhaseSidebarGroupingStore.getState().grouping.notificationOverrides, }; }; // A task delegated from another host is a child even where its parent is not listed. @@ -118,6 +121,7 @@ export function startThreadNotifications( thread.customGroup, thread.parentThreadId !== null || thread.delegatedFrom !== null, groups.ungrouped, + groups.overrides, ); // Muting a group also closes what its sessions already have on screen. const closeMutedPending = () => { @@ -478,8 +482,14 @@ export function startThreadNotifications( registry.subscribe(environmentThreadShells.hiddenThreadKeysAtom, closeHiddenPending), registry.subscribe(environmentThreadShells.anyEnvironmentHidingAtom, closeHiddenPending), registry.subscribe(environmentThreadShells.threadRefsAtom, closeHiddenPending), - // T3-CUSTOM(expbkt3): a group's mode changes through its host's server settings. + // T3-CUSTOM(expbkt3): a group's mode changes through its host's server settings, + // or through this device's override in the grouping store. registry.subscribe(environmentServerConfigsAtom, closeMutedPending), + usePhaseSidebarGroupingStore.subscribe((state, previous) => { + if (state.grouping.notificationOverrides !== previous.grouping.notificationOverrides) { + closeMutedPending(); + } + }), ]; onSettings(); diff --git a/apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.test.ts b/apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.test.ts new file mode 100644 index 0000000000000..c58dd4554ec01 --- /dev/null +++ b/apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.test.ts @@ -0,0 +1,56 @@ +// T3-CUSTOM(expbkt3): which drops of a session on a section write a group. +import { describe, expect, it } from "vite-plus/test"; + +import { + resolvePhaseSidebarRowDrop, + type PhaseSidebarRowDropSection, +} from "./PhaseSidebarGroupDrop.logic"; + +const group = (label: string): PhaseSidebarRowDropSection => ({ + kind: "custom", + id: label.toLowerCase(), + isUngrouped: false, + label, +}); +const UNGROUPED: PhaseSidebarRowDropSection = { + kind: "custom", + id: "ungrouped", + isUngrouped: true, + label: "Ungrouped", +}; + +describe("resolvePhaseSidebarRowDrop", () => { + it("files a session in another group under the header's label", () => { + expect(resolvePhaseSidebarRowDrop("Sprint 41", group("Sprint 42"))).toEqual({ + customGroup: "Sprint 42", + }); + expect(resolvePhaseSidebarRowDrop(null, group("Sprint 42"))).toEqual({ + customGroup: "Sprint 42", + }); + }); + + it("refuses a drop on the session's own group, whatever its spelling", () => { + expect(resolvePhaseSidebarRowDrop("sprint 42", group("Sprint 42"))).toBeNull(); + expect(resolvePhaseSidebarRowDrop("Sprint 42", group("Sprint 42"))).toBeNull(); + }); + + it("takes a grouped session out of its group on Ungrouped, and refuses an ungrouped one", () => { + expect(resolvePhaseSidebarRowDrop("Sprint 42", UNGROUPED)).toEqual({ customGroup: null }); + expect(resolvePhaseSidebarRowDrop(null, UNGROUPED)).toBeNull(); + expect(resolvePhaseSidebarRowDrop(undefined, UNGROUPED)).toBeNull(); + }); + + it("refuses sections that are not custom groups", () => { + expect( + resolvePhaseSidebarRowDrop(null, { + kind: "lifecycle", + id: "ready", + isUngrouped: false, + label: "Ready", + }), + ).toBeNull(); + expect( + resolvePhaseSidebarRowDrop(null, { kind: "custom", id: "", isUngrouped: false, label: " " }), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.ts b/apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.ts new file mode 100644 index 0000000000000..c3a35948eaae1 --- /dev/null +++ b/apps/web/src/components/sidebar/PhaseSidebarGroupDrop.logic.ts @@ -0,0 +1,49 @@ +// T3-CUSTOM(expbkt3): dragging a session onto a custom group section. +// +// In Custom mode a session row can be dragged with the mouse onto any custom +// group's section (its header or its rows) to file it there, and onto +// "Ungrouped" to take it out of its group. The write is the same +// thread.meta.update { customGroup } that "Move to group" sends. +import { isReservedThreadCustomGroup, normalizeThreadCustomGroup } from "@t3tools/contracts"; + +/** The drag payload type. Custom, so a text field (the search box) never accepts the drop. */ +export const PHASE_SIDEBAR_ROW_DRAG_TYPE = "application/x-t3-phase-sidebar-session"; + +export interface PhaseSidebarRowDropSection { + readonly kind: string; + /** The section id: a custom group's comparison key, or "ungrouped". */ + readonly id: string; + readonly isUngrouped: boolean; + /** The group's label as the header shows it. */ + readonly label: string; +} + +/** + * What a drop of a session on `section` writes: `{ customGroup }` (null + * removes the session from its group), or null when the drop is refused — + * not a custom group section, or the session is already filed there. + * `rowCustomGroup` is the session's own label. + */ +export function resolvePhaseSidebarRowDrop( + rowCustomGroup: string | null | undefined, + section: PhaseSidebarRowDropSection, +): { readonly customGroup: string | null } | null { + if (section.kind !== "custom") return null; + const current = + rowCustomGroup === null || rowCustomGroup === undefined + ? null + : normalizeThreadCustomGroup(rowCustomGroup); + if (section.isUngrouped) return current === null ? null : { customGroup: null }; + const label = section.label.trim(); + if (label.length === 0 || isReservedThreadCustomGroup(label)) return null; + if (current === section.id || current === normalizeThreadCustomGroup(label)) return null; + return { customGroup: label }; +} + +/** + * Rows drag only where the main pointer is a mouse or trackpad, so on a phone + * or tablet a long press keeps opening the row's menu. + */ +export function phaseSidebarSupportsMouseDrag(): boolean { + return typeof window !== "undefined" && window.matchMedia?.("(pointer: fine)")?.matches === true; +} diff --git a/apps/web/src/components/sidebar/usePhaseSidebarCustomGroupRegistry.ts b/apps/web/src/components/sidebar/usePhaseSidebarCustomGroupRegistry.ts index 922fc8a0a1929..a35813dfb9f78 100644 --- a/apps/web/src/components/sidebar/usePhaseSidebarCustomGroupRegistry.ts +++ b/apps/web/src/components/sidebar/usePhaseSidebarCustomGroupRegistry.ts @@ -13,7 +13,6 @@ import { phaseSidebarCustomGroupRegistryEnvironmentIds, planPhaseSidebarCustomGroupCreate, planPhaseSidebarCustomGroupDelete, - planPhaseSidebarCustomGroupNotifications, planPhaseSidebarCustomGroupRecolor, planPhaseSidebarCustomGroupRename, resolvePhaseSidebarCustomGroupHome, @@ -54,15 +53,13 @@ export interface PhaseSidebarCustomGroupRegistryControls { readonly deleteGroup: (id: string) => void; /** `colorId` null restores the default look. */ readonly recolorGroup: (id: string, label: string, colorId: string | null) => void; - /** T3-CUSTOM(expbkt3): which of the group's sessions may alert. */ - readonly setGroupNotifications: ( - id: string, - label: string, - notifications: ThreadCustomGroupNotificationMode, - ) => void; - /** T3-CUSTOM(expbkt3): the "Ungrouped" section's mode, and its setter (every writable host). */ + /** + * T3-CUSTOM(expbkt3): the "Ungrouped" section's shared mode (a host setting). + * Web only reads the shared modes: its bell writes this device's own mode + * (phaseSidebarGroupingStore), which outranks them. Mobile and the MCP + * control tools still write the shared ones. + */ readonly ungroupedNotifications: ThreadCustomGroupNotificationMode; - readonly setUngroupedNotifications: (notifications: ThreadCustomGroupNotificationMode) => void; } export function usePhaseSidebarCustomGroupRegistry(input: { @@ -155,39 +152,12 @@ export function usePhaseSidebarCustomGroupRegistry(input: { [homeEnvironmentId, registry, send, writableEnvironmentIds], ); - // T3-CUSTOM(expbkt3): per-group notification mode, written like a recolour. - const setGroupNotifications = useCallback( - (id: string, label: string, notifications: ThreadCustomGroupNotificationMode) => - send( - planPhaseSidebarCustomGroupNotifications({ - registry, - id, - label, - notifications, - writableEnvironmentIds, - homeEnvironmentId, - }), - ), - [homeEnvironmentId, registry, send, writableEnvironmentIds], - ); - - // T3-CUSTOM(expbkt3): "Ungrouped" has no registry entry, so its mode is a - // plain host setting, written to every host this session may write. + // T3-CUSTOM(expbkt3): "Ungrouped" has no registry entry, so its shared mode + // is a plain host setting. const ungroupedNotifications = useMemo( () => resolvePhaseSidebarUngroupedNotifications(serverConfigs, primaryEnvironmentId), [primaryEnvironmentId, serverConfigs], ); - const setUngroupedNotifications = useCallback( - (notifications: ThreadCustomGroupNotificationMode) => { - for (const environmentId of writableEnvironmentIds) { - void updateSettings({ - environmentId: environmentId as EnvironmentId, - input: { patch: { ungroupedThreadNotifications: notifications } }, - }); - } - }, - [updateSettings, writableEnvironmentIds], - ); return useMemo( () => ({ @@ -197,9 +167,7 @@ export function usePhaseSidebarCustomGroupRegistry(input: { renameGroup, deleteGroup, recolorGroup, - setGroupNotifications, ungroupedNotifications, - setUngroupedNotifications, }), [ createGroup, @@ -208,8 +176,6 @@ export function usePhaseSidebarCustomGroupRegistry(input: { recolorGroup, registry, renameGroup, - setGroupNotifications, - setUngroupedNotifications, ungroupedNotifications, ], ); diff --git a/apps/web/src/fork/draftCustomGroupStore.test.ts b/apps/web/src/fork/draftCustomGroupStore.test.ts new file mode 100644 index 0000000000000..97246cb8609e6 --- /dev/null +++ b/apps/web/src/fork/draftCustomGroupStore.test.ts @@ -0,0 +1,56 @@ +// T3-CUSTOM(expbkt3): the group a draft started from a group header's "+" lands in. +import { afterEach, describe, expect, it } from "vite-plus/test"; + +import { + DRAFT_CUSTOM_GROUP_STORAGE_KEY, + draftCustomGroupCreateFields, + pruneDraftCustomGroupTargets, + setDraftCustomGroupTarget, + useDraftCustomGroupStore, +} from "./draftCustomGroupStore"; + +afterEach(() => { + useDraftCustomGroupStore.setState({ targets: {} }); + useDraftCustomGroupStore.persist.clearStorage(); +}); + +describe("draft custom group targets", () => { + it("remembers, replaces and forgets a draft's group", () => { + const one = setDraftCustomGroupTarget({}, "thread-1", " Sprint 42 "); + expect(one).toEqual({ "thread-1": "Sprint 42" }); + expect(setDraftCustomGroupTarget(one, "thread-1", "Sprint 42")).toBe(one); + expect(setDraftCustomGroupTarget(one, "thread-1", "Bugs")).toEqual({ "thread-1": "Bugs" }); + // A plain New thread reusing the draft clears the choice. + expect(setDraftCustomGroupTarget(one, "thread-1", null)).toEqual({}); + expect(setDraftCustomGroupTarget(one, "thread-2", null)).toBe(one); + expect(setDraftCustomGroupTarget(one, "thread-1", " ")).toEqual({}); + }); + + it("forgets the group of a draft that was sent or discarded", () => { + const targets = { "thread-1": "Bugs", "thread-2": "Leads" }; + expect(pruneDraftCustomGroupTargets(targets, new Set(["thread-1", "thread-2"]))).toBe(targets); + expect(pruneDraftCustomGroupTargets(targets, new Set(["thread-2"]))).toEqual({ + "thread-2": "Leads", + }); + expect(pruneDraftCustomGroupTargets(targets, new Set())).toEqual({}); + }); + + it("names the group in the create input only for a draft that has one", () => { + const targets = { "thread-1": "Bugs" }; + expect(draftCustomGroupCreateFields(targets, "thread-1")).toEqual({ customGroup: "Bugs" }); + expect(draftCustomGroupCreateFields(targets, "thread-2")).toEqual({}); + expect(draftCustomGroupCreateFields(targets, undefined)).toEqual({}); + expect(draftCustomGroupCreateFields(targets, null)).toEqual({}); + }); + + it("keeps the choice across a reload", async () => { + useDraftCustomGroupStore.getState().setTarget("thread-1", "Bugs"); + const storage = useDraftCustomGroupStore.persist.getOptions().storage!; + const saved = (await storage.getItem(DRAFT_CUSTOM_GROUP_STORAGE_KEY)) as { + readonly state: { readonly targets?: unknown }; + } | null; + expect(saved?.state.targets).toEqual({ "thread-1": "Bugs" }); + await useDraftCustomGroupStore.persist.rehydrate(); + expect(useDraftCustomGroupStore.getState().targets).toEqual({ "thread-1": "Bugs" }); + }); +}); diff --git a/apps/web/src/fork/draftCustomGroupStore.ts b/apps/web/src/fork/draftCustomGroupStore.ts new file mode 100644 index 0000000000000..b52a50312ca5a --- /dev/null +++ b/apps/web/src/fork/draftCustomGroupStore.ts @@ -0,0 +1,123 @@ +// T3-CUSTOM(expbkt3): the custom group a new session lands in. +// +// A custom group header's "+" opens a draft like the New thread button does, +// but the session it becomes must be filed in that group from its first send. +// The draft does not exist on the server yet, so the choice waits here, keyed +// by the draft's thread id, until the send builds the thread's create input +// (`threadCreationForkFields`), which then names the group explicitly; an +// explicit group outranks the host's default group on the server. +// +// Persisted with the drafts themselves (both live in local storage), so a +// reload keeps the choice. The sidebar prunes entries whose draft is gone +// (sent or discarded) with `pruneDraftCustomGroupTargets`. +import type { ThreadId } from "@t3tools/contracts"; +import { create } from "zustand"; +import { createJSONStorage, persist } from "zustand/middleware"; + +import { resolveStorage } from "../lib/storage"; + +export const DRAFT_CUSTOM_GROUP_STORAGE_KEY = "t3code:draft-custom-groups:v1"; + +/** Group label by draft thread id. */ +export type DraftCustomGroupTargets = Readonly>; + +const NO_TARGETS: DraftCustomGroupTargets = {}; + +/** Files the draft under `label`; null forgets the choice (the session then joins no group). */ +export function setDraftCustomGroupTarget( + targets: DraftCustomGroupTargets, + threadId: string, + label: string | null, +): DraftCustomGroupTargets { + const trimmed = label?.trim() ?? ""; + if (trimmed.length === 0) { + if (!(threadId in targets)) return targets; + const rest: Record = { ...targets }; + delete rest[threadId]; + return Object.keys(rest).length === 0 ? NO_TARGETS : rest; + } + return targets[threadId] === trimmed ? targets : { ...targets, [threadId]: trimmed }; +} + +/** Drops every choice whose draft no longer exists. Unchanged input when nothing goes. */ +export function pruneDraftCustomGroupTargets( + targets: DraftCustomGroupTargets, + liveDraftThreadIds: ReadonlySet, +): DraftCustomGroupTargets { + const ids = Object.keys(targets); + if (ids.every((id) => liveDraftThreadIds.has(id))) return targets; + const kept: Record = {}; + for (const id of ids) { + const label = targets[id]; + if (label !== undefined && liveDraftThreadIds.has(id)) kept[id] = label; + } + return Object.keys(kept).length === 0 ? NO_TARGETS : kept; +} + +/** The create-input field for a draft: `{ customGroup }` when one was chosen, else nothing. */ +export function draftCustomGroupCreateFields( + targets: DraftCustomGroupTargets, + threadId: ThreadId | string | null | undefined, +): { readonly customGroup?: string } { + if (threadId === null || threadId === undefined) return {}; + const label = targets[threadId]; + return label === undefined ? {} : { customGroup: label }; +} + +function sanitizeTargets(value: unknown): DraftCustomGroupTargets { + if (value === null || typeof value !== "object" || Array.isArray(value)) return NO_TARGETS; + let targets = NO_TARGETS; + for (const [threadId, label] of Object.entries(value)) { + if (threadId.length > 0 && typeof label === "string") { + targets = setDraftCustomGroupTarget(targets, threadId, label); + } + } + return targets; +} + +interface DraftCustomGroupStoreState { + readonly targets: DraftCustomGroupTargets; + setTarget: (threadId: string, label: string | null) => void; + prune: (liveDraftThreadIds: ReadonlySet) => void; +} + +export const useDraftCustomGroupStore = create()( + persist( + (set) => ({ + targets: NO_TARGETS, + setTarget: (threadId, label) => + set((state) => { + const next = setDraftCustomGroupTarget(state.targets, threadId, label); + return next === state.targets ? state : { targets: next }; + }), + prune: (liveDraftThreadIds) => + set((state) => { + const next = pruneDraftCustomGroupTargets(state.targets, liveDraftThreadIds); + return next === state.targets ? state : { targets: next }; + }), + }), + { + name: DRAFT_CUSTOM_GROUP_STORAGE_KEY, + version: 1, + storage: createJSONStorage(() => + resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), + ), + partialize: (state) => ({ targets: state.targets }), + merge: (persisted, current) => ({ + ...current, + targets: sanitizeTargets( + persisted && typeof persisted === "object" + ? (persisted as { readonly targets?: unknown }).targets + : undefined, + ), + }), + }, + ), +); + +/** The group chosen for a draft, read when its first send builds the create input. */ +export function readDraftCustomGroupCreateFields(threadId: ThreadId | string | null | undefined): { + readonly customGroup?: string; +} { + return draftCustomGroupCreateFields(useDraftCustomGroupStore.getState().targets, threadId); +} diff --git a/apps/web/src/fork/threadCreationMetadata.test.ts b/apps/web/src/fork/threadCreationMetadata.test.ts index 8deff3146791c..942fcf99567d3 100644 --- a/apps/web/src/fork/threadCreationMetadata.test.ts +++ b/apps/web/src/fork/threadCreationMetadata.test.ts @@ -7,6 +7,7 @@ import { type SourceControlProfilesListResult, } from "@t3tools/contracts"; import { expect, it } from "vite-plus/test"; +import { useDraftCustomGroupStore } from "./draftCustomGroupStore"; import { resolveThreadCreationProfile, threadCreationForkFields } from "./threadCreationMetadata"; const profileId = SourceControlProfileId.make("owner-profile"); @@ -56,3 +57,19 @@ it("carries both parent identifiers for a draft started on another environment", sourceControlProfileId: null, }); }); + +it("creates a draft started from a group header's + in that group", () => { + const threadId = ThreadId.make("draft-thread"); + useDraftCustomGroupStore.getState().setTarget(threadId, "Sprint 42"); + try { + expect(threadCreationForkFields(null, { threadId })).toEqual({ + sourceControlProfileId: null, + customGroup: "Sprint 42", + }); + expect(threadCreationForkFields(null, { threadId: ThreadId.make("other") })).toEqual({ + sourceControlProfileId: null, + }); + } finally { + useDraftCustomGroupStore.getState().setTarget(threadId, null); + } +}); diff --git a/apps/web/src/fork/threadCreationMetadata.ts b/apps/web/src/fork/threadCreationMetadata.ts index cb4daaefe1674..687bf4ca8f5bd 100644 --- a/apps/web/src/fork/threadCreationMetadata.ts +++ b/apps/web/src/fork/threadCreationMetadata.ts @@ -6,6 +6,8 @@ import type { ThreadId, } from "@t3tools/contracts"; +import { readDraftCustomGroupCreateFields } from "./draftCustomGroupStore"; + export function resolveThreadCreationProfile( result: SourceControlProfilesListResult | null, ownerUserId: string | null, @@ -20,6 +22,7 @@ export function resolveThreadCreationProfile( export function threadCreationForkFields( sourceControlProfileId: SourceControlProfileId | null, draft: { + readonly threadId?: ThreadId; readonly parentThreadId?: ThreadId | null; readonly parentEnvironmentId?: EnvironmentId | null; } | null, @@ -30,5 +33,7 @@ export function threadCreationForkFields( ...(draft?.parentThreadId && draft.parentEnvironmentId ? { parentEnvironmentId: draft.parentEnvironmentId } : {}), + // A draft started from a custom group's "+" is created in that group. + ...readDraftCustomGroupCreateFields(draft?.threadId), }; } diff --git a/apps/web/src/phaseSidebarGroupingStore.test.ts b/apps/web/src/phaseSidebarGroupingStore.test.ts index 34874970148bf..8bd8f3896af23 100644 --- a/apps/web/src/phaseSidebarGroupingStore.test.ts +++ b/apps/web/src/phaseSidebarGroupingStore.test.ts @@ -110,4 +110,34 @@ describe("phase sidebar grouping store", () => { expect(collapsedKeys().has(readyKey)).toBe(false); }); + + // T3-CUSTOM(expbkt3): the group bell is this device's own setting, so a mute + // must survive a restart (a rehydrate from storage) without any host. + it("keeps a group mute across a restart, and moves or drops it with the group", async () => { + store().setGroupNotifications("bugs", "off"); + store().setGroupNotifications("ungrouped", "parents"); + expect((await readStoredGrouping())?.notificationOverrides).toEqual({ + bugs: "off", + ungrouped: "parents", + }); + + // A restart starts from the stored blob, never from component state. + await usePhaseSidebarGroupingStore.persist.rehydrate(); + expect(store().grouping.notificationOverrides).toEqual({ bugs: "off", ungrouped: "parents" }); + + store().renameGroup("bugs", "Defects"); + expect(store().grouping.notificationOverrides).toEqual({ + defects: "off", + ungrouped: "parents", + }); + store().forgetGroup("defects"); + expect(store().grouping.notificationOverrides).toEqual({ ungrouped: "parents" }); + }); + + it("reads a blob saved before the bell was local", async () => { + await writeFromAnotherTab({ ...DEFAULT_PHASE_SIDEBAR_GROUPING, groupBy: "custom" }); + await usePhaseSidebarGroupingStore.persist.rehydrate(); + expect(store().grouping.groupBy).toBe("custom"); + expect(store().grouping).not.toHaveProperty("notificationOverrides"); + }); }); diff --git a/apps/web/src/phaseSidebarGroupingStore.ts b/apps/web/src/phaseSidebarGroupingStore.ts index efd287d867c52..11b690f84c6d5 100644 --- a/apps/web/src/phaseSidebarGroupingStore.ts +++ b/apps/web/src/phaseSidebarGroupingStore.ts @@ -6,8 +6,10 @@ // operations, and keeping it here adds no hunks to an upstream-owned file. // Only presentation lives here — the manual section order, collapse state // (the lifecycle, project and custom groups, and the snoozed and settled -// shelves) and this device's legacy placements. Which group a session is IN is the thread's -// own `customGroup` label on the server, written through thread.meta.update. +// shelves), this device's legacy placements, and this device's notification +// mode per group (the header bell; it outranks the host's shared mode). Which +// group a session is IN is the thread's own `customGroup` label on the +// server, written through thread.meta.update. import { createPhaseSidebarCustomGroup, DEFAULT_PHASE_SIDEBAR_GROUPING, @@ -18,6 +20,7 @@ import { renamePhaseSidebarCustomGroup, sanitizePhaseSidebarGrouping, setPhaseSidebarGroupBy, + setPhaseSidebarGroupNotificationOverride, setPhaseSidebarGroupOrder, setPhaseSidebarRunningShelf, setPhaseSidebarSectionsCollapsed, @@ -26,6 +29,7 @@ import { type PhaseSidebarGroupOrder, type PhaseSidebarGroupingPreferences, } from "@t3tools/client-runtime/state/phase-sidebar-grouping"; +import type { ThreadCustomGroupNotificationMode } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; @@ -50,6 +54,8 @@ interface PhaseSidebarGroupingStoreState { /** `orderedIds` is the custom section order currently on screen. */ moveGroup: (orderedIds: ReadonlyArray, id: string, direction: "up" | "down") => void; toggleSectionCollapsed: (sectionKey: string) => void; + /** The header bell: this device's mode for a group id ("ungrouped" for the built-in section). */ + setGroupNotifications: (id: string, mode: ThreadCustomGroupNotificationMode) => void; /** The collapse-all button: every given section closed, or every one open. */ setSectionsCollapsed: ( sections: ReadonlyArray<{ readonly key: string; readonly collapsedByDefault: boolean }>, @@ -90,6 +96,11 @@ export const usePhaseSidebarGroupingStore = create ({ grouping: togglePhaseSidebarSectionCollapsed(state.grouping, sectionKey), })), + setGroupNotifications: (id, mode) => + set((state) => { + const next = setPhaseSidebarGroupNotificationOverride(state.grouping, id, mode); + return next === state.grouping ? state : { grouping: next }; + }), setSectionsCollapsed: (sections, collapsed) => set((state) => { const next = setPhaseSidebarSectionsCollapsed(state.grouping, sections, collapsed); diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 2f3408daf60e3..4d691f4bfd492 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -375,6 +375,13 @@ thread sees the same group, on every device. To file a thread, open its menu and choose **Move to group**, pick an existing group or **New group…**, or **Remove from group**. + + +On the web and desktop, in Custom mode, you can also drag a thread with the +mouse onto a group's header or threads to move it there, or onto **Ungrouped** +to remove it from its group. To start a thread in a group, hover its header +and click **+**; the thread joins that group when you send its first message. + In Custom mode, a session nested under a parent session stays under that @@ -410,11 +417,13 @@ position and whether it is collapsed stay on each device. The bell in a group's header sets which of its threads notify you on the web and desktop: every thread, **only parent threads** (threads with no parent session, so agent-created child sessions stay quiet), or none. A quieted group -shows its bell even when the header actions are hidden. The setting is shared -like the colour, and on iOS and Android it is under **Notifications** in the -group's header menu. **Ungrouped** has the same bell, for threads in no -group. Phone push notifications do not follow it yet. The desktop app shows -the bell once its own app update includes it. +shows its bell even when the header actions are hidden. On the web and desktop +the bell is a setting of that browser or app only: it is kept on the device, +survives restarts, follows the group when you rename it, and outranks the +group's shared setting. The shared setting, which other devices without their +own choice follow, is under **Notifications** in the group's header menu on +iOS and Android. **Ungrouped** has the same bell, for threads in no group. +Phone push notifications do not follow it yet. To stop new threads landing in **Ungrouped**, pick a **Default group for new sessions** for each environment under **Settings → BK Add-ons**. A new thread diff --git a/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.test.ts b/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.test.ts index e5b8aa0240af3..7014290434b37 100644 --- a/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.test.ts +++ b/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.test.ts @@ -18,6 +18,7 @@ import { planPhaseSidebarCustomGroupRecolor, planPhaseSidebarCustomGroupRename, resolvePhaseSidebarCustomGroupHome, + resolvePhaseSidebarGroupNotificationMode, resolvePhaseSidebarUngroupedNotifications, type PhaseSidebarCustomGroupRegistryConfig, } from "./phaseSidebarCustomGroupRegistry.ts"; @@ -479,3 +480,61 @@ describe("ungrouped notification mode", () => { expect(allows("Unregistered", true)).toBe(true); }); }); + +// T3-CUSTOM(expbkt3): this device's own mode per group, kept in local storage. +describe("device notification overrides", () => { + const registry = buildPhaseSidebarCustomGroupRegistry( + configs([ + [ + "primary", + config({ + loud: { label: "Loud" }, + quiet: { label: "Quiet", notifications: "off" }, + }), + ], + ]), + "primary", + ); + + it("outranks the shared mode, for registered, label-only and ungrouped sessions", () => { + const overrides = { + loud: "off", + quiet: "all", + "label only": "parents", + ungrouped: "off", + } as const; + expect(resolvePhaseSidebarGroupNotificationMode(registry, "loud", "all", overrides)).toBe( + "off", + ); + expect(resolvePhaseSidebarGroupNotificationMode(registry, "quiet", "all", overrides)).toBe( + "all", + ); + expect(resolvePhaseSidebarGroupNotificationMode(registry, "label only", "all", overrides)).toBe( + "parents", + ); + expect(resolvePhaseSidebarGroupNotificationMode(registry, "ungrouped", "all", overrides)).toBe( + "off", + ); + + const allows = (group: string | null, isChild: boolean) => + phaseSidebarCustomGroupAllowsNotification(registry, group, isChild, "all", overrides); + expect(allows("LOUD", false)).toBe(false); + expect(allows("Quiet", true)).toBe(true); + expect(allows("Label only", false)).toBe(true); + expect(allows("Label only", true)).toBe(false); + expect(allows(null, false)).toBe(false); + }); + + it("falls back to the shared mode where the device has none, as mobile does", () => { + expect(resolvePhaseSidebarGroupNotificationMode(registry, "quiet")).toBe("off"); + expect(resolvePhaseSidebarGroupNotificationMode(registry, "loud", "all", {})).toBe("all"); + expect(resolvePhaseSidebarGroupNotificationMode(registry, "ungrouped", "parents", {})).toBe( + "parents", + ); + expect(resolvePhaseSidebarGroupNotificationMode(registry, "unregistered")).toBe("all"); + expect(phaseSidebarCustomGroupAllowsNotification(registry, "Quiet", false)).toBe(false); + expect( + phaseSidebarCustomGroupAllowsNotification(registry, "Quiet", false, "all", undefined), + ).toBe(false); + }); +}); diff --git a/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.ts b/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.ts index 5619f4ce6d639..1e10d49cee849 100644 --- a/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.ts +++ b/packages/client-runtime/src/state/phaseSidebarCustomGroupRegistry.ts @@ -410,22 +410,52 @@ export function resolvePhaseSidebarUngroupedNotifications( return "all"; } +/** + * This device's own notification mode per group, keyed by the group id (the + * section id), with "Ungrouped" under `PHASE_SIDEBAR_UNGROUPED_ID`. Kept with + * the device's grouping preferences (phaseSidebarGrouping.ts), not on a host: + * a mute set here silences this device only, and outranks the shared mode. + */ +export type PhaseSidebarGroupNotificationOverrides = Readonly< + Record +>; + +/** + * The mode that applies to a group on this device: its local override, else + * the shared mode (the registry's for a custom group, `ungrouped` for the + * built-in section), else "all". `groupId` is a section id. + */ +export function resolvePhaseSidebarGroupNotificationMode( + registry: PhaseSidebarCustomGroupRegistry, + groupId: string, + ungrouped: ThreadCustomGroupNotificationMode = "all", + overrides?: PhaseSidebarGroupNotificationOverrides, +): ThreadCustomGroupNotificationMode { + const override = overrides?.[groupId]; + if (override !== undefined) return resolveThreadCustomGroupNotificationMode(override); + if (groupId === PHASE_SIDEBAR_UNGROUPED_ID) return ungrouped; + return registry.get(groupId)?.notifications ?? "all"; +} + /** * Whether a session may alert under its group's mode. `customGroup` is the * session's label; `isChild` is true when it has a parent session. A session * with no group follows `ungrouped`; one whose group has no registry entry - * always may. + * always may. `overrides` (this device's own modes) outrank both; mobile + * passes none, which keeps the shared behaviour. */ export function phaseSidebarCustomGroupAllowsNotification( registry: PhaseSidebarCustomGroupRegistry, customGroup: string | null | undefined, isChild: boolean, ungrouped: ThreadCustomGroupNotificationMode = "all", + overrides?: PhaseSidebarGroupNotificationOverrides, ): boolean { - const mode = + const groupId = customGroup === null || customGroup === undefined - ? ungrouped - : (registry.get(normalizeThreadCustomGroup(customGroup))?.notifications ?? "all"); + ? PHASE_SIDEBAR_UNGROUPED_ID + : normalizeThreadCustomGroup(customGroup); + const mode = resolvePhaseSidebarGroupNotificationMode(registry, groupId, ungrouped, overrides); return mode === "all" || (mode === "parents" && !isChild); } // T3-CUSTOM(expbkt3): END diff --git a/packages/client-runtime/src/state/phaseSidebarGrouping.test.ts b/packages/client-runtime/src/state/phaseSidebarGrouping.test.ts index 5d331cfb9863b..c4190b3db82c6 100644 --- a/packages/client-runtime/src/state/phaseSidebarGrouping.test.ts +++ b/packages/client-runtime/src/state/phaseSidebarGrouping.test.ts @@ -30,6 +30,7 @@ import { rememberPhaseSidebarCustomGroupOrder, renamePhaseSidebarCustomGroup, sanitizePhaseSidebarGrouping, + setPhaseSidebarGroupNotificationOverride, setPhaseSidebarRunningShelf, setPhaseSidebarSectionsCollapsed, togglePhaseSidebarSectionCollapsed, @@ -673,3 +674,117 @@ describe("custom groups from the shared registry", () => { expect(rememberPhaseSidebarCustomGroupOrder(first, "ungrouped")).toBe(first); }); }); + +// T3-CUSTOM(expbkt3): this device's own notification mode per group (the bell). +describe("device notification overrides", () => { + const custom: PhaseSidebarGroupingPreferences = { + ...DEFAULT_PHASE_SIDEBAR_GROUPING, + groupBy: "custom", + }; + + it("reads a stored blob without overrides, and drops unknown modes and blank ids", () => { + expect(sanitizePhaseSidebarGrouping({ groupBy: "custom" })).not.toHaveProperty( + "notificationOverrides", + ); + expect( + sanitizePhaseSidebarGrouping({ + groupBy: "custom", + notificationOverrides: { bugs: "off", ungrouped: "parents", "": "off", odd: "loud" }, + }).notificationOverrides, + ).toEqual({ bugs: "off", ungrouped: "parents" }); + expect(sanitizePhaseSidebarGrouping({ notificationOverrides: ["off"] })).not.toHaveProperty( + "notificationOverrides", + ); + }); + + it("sets a mode, keeps an explicit all, and returns the same object when nothing changes", () => { + const muted = setPhaseSidebarGroupNotificationOverride(custom, "bugs", "off"); + expect(muted.notificationOverrides).toEqual({ bugs: "off" }); + expect(setPhaseSidebarGroupNotificationOverride(muted, "bugs", "off")).toBe(muted); + // "all" is stored too: it must outrank a shared "off". + expect( + setPhaseSidebarGroupNotificationOverride(muted, "bugs", "all").notificationOverrides, + ).toEqual({ bugs: "all" }); + expect(sanitizePhaseSidebarGrouping(muted)).toEqual(muted); + }); + + it("moves the override with a rename, and keeps the target's own on a merge", () => { + const muted = setPhaseSidebarGroupNotificationOverride(custom, "bugs", "off"); + expect(renamePhaseSidebarCustomGroup(muted, "bugs", "Defects").notificationOverrides).toEqual({ + defects: "off", + }); + // A case-only rename keeps the same id. + expect(renamePhaseSidebarCustomGroup(muted, "bugs", "BUGS").notificationOverrides).toEqual({ + bugs: "off", + }); + const both = setPhaseSidebarGroupNotificationOverride(muted, "defects", "parents"); + expect(renamePhaseSidebarCustomGroup(both, "bugs", "Defects").notificationOverrides).toEqual({ + defects: "parents", + }); + }); + + it("drops the override with the group, and leaves other groups' alone", () => { + const muted = setPhaseSidebarGroupNotificationOverride( + setPhaseSidebarGroupNotificationOverride(custom, "bugs", "off"), + "ungrouped", + "parents", + ); + expect(deletePhaseSidebarCustomGroup(muted, "bugs").notificationOverrides).toEqual({ + ungrouped: "parents", + }); + expect( + deletePhaseSidebarCustomGroup( + setPhaseSidebarGroupNotificationOverride(custom, "bugs", "off"), + "bugs", + ), + ).not.toHaveProperty("notificationOverrides"); + }); + + it("shows the override on the section header over the shared mode", () => { + const registry = buildPhaseSidebarCustomGroupRegistry( + new Map([ + [ + "primary", + { + environment: { capabilities: { threadCustomGroupRegistry: true } }, + settings: { threadCustomGroups: { quiet: { label: "Quiet", notifications: "off" } } }, + }, + ], + ]), + "primary", + ); + const grouping = setPhaseSidebarGroupNotificationOverride( + setPhaseSidebarGroupNotificationOverride( + setPhaseSidebarGroupNotificationOverride(custom, "quiet", "all"), + "label only", + "parents", + ), + "ungrouped", + "off", + ); + const result = sections( + [ + makeRow("a", { customGroup: "Quiet" }), + makeRow("b", { customGroup: "Label only" }), + makeRow("c"), + ], + grouping, + { customGroupRegistry: registry, ungroupedNotifications: "parents" }, + ); + expect(result.map((section) => [section.id, section.notifications])).toEqual([ + ["label only", "parents"], + ["quiet", undefined], + ["ungrouped", "off"], + ]); + // Without overrides the shared modes show, as on mobile. + expect( + sections([makeRow("a", { customGroup: "Quiet" }), makeRow("c")], custom, { + customGroupRegistry: registry, + ungroupedNotifications: "parents", + }).map((section) => [section.id, section.notifications]), + ).toEqual([ + ["quiet", "off"], + ["ungrouped", "parents"], + ]); + }); +}); diff --git a/packages/client-runtime/src/state/phaseSidebarGrouping.ts b/packages/client-runtime/src/state/phaseSidebarGrouping.ts index 30928e8568ce3..a8636400fbae6 100644 --- a/packages/client-runtime/src/state/phaseSidebarGrouping.ts +++ b/packages/client-runtime/src/state/phaseSidebarGrouping.ts @@ -29,6 +29,7 @@ import { normalizeThreadCustomGroup, THREAD_CUSTOM_GROUP_MAX_LENGTH, + THREAD_CUSTOM_GROUP_NOTIFICATION_MODES, type ThreadCustomGroupNotificationMode, } from "@t3tools/contracts"; @@ -44,6 +45,7 @@ import { import { EMPTY_PHASE_SIDEBAR_CUSTOM_GROUP_REGISTRY, type PhaseSidebarCustomGroupRegistry, + type PhaseSidebarGroupNotificationOverrides, } from "./phaseSidebarCustomGroupRegistry.ts"; import { buildPhaseSidebarFilteredTree, @@ -108,6 +110,12 @@ export interface PhaseSidebarGroupingPreferences { * their group for the Running shelf. Absent means off. */ readonly runningShelf?: boolean; + /** + * This device's own notification mode per group id ("ungrouped" for the + * built-in section). It outranks the shared mode from the host registry and + * never leaves the device. Absent means no override anywhere. + */ + readonly notificationOverrides?: PhaseSidebarGroupNotificationOverrides; } export const DEFAULT_PHASE_SIDEBAR_GROUPING: PhaseSidebarGroupingPreferences = { @@ -169,6 +177,40 @@ function sanitizeCustomGroups(value: unknown): PhaseSidebarCustomGroup[] { return groups; } +function sanitizeNotificationOverrides( + value: unknown, +): PhaseSidebarGroupNotificationOverrides | undefined { + if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined; + const overrides: Record = {}; + for (const [id, mode] of Object.entries(value)) { + if (id.length === 0) continue; + const known = THREAD_CUSTOM_GROUP_NOTIFICATION_MODES.find((candidate) => candidate === mode); + if (known !== undefined) overrides[id] = known; + } + return Object.keys(overrides).length === 0 ? undefined : overrides; +} + +/** The device's notification overrides without the one for `id`. */ +function withoutNotificationOverride( + preferences: PhaseSidebarGroupingPreferences, + id: string, +): Record { + const overrides: Record = { + ...preferences.notificationOverrides, + }; + delete overrides[id]; + return overrides; +} + +/** Sets or replaces (`overrides` empty → absent) the device's notification overrides. */ +function withNotificationOverrides( + preferences: PhaseSidebarGroupingPreferences, + overrides: Readonly>, +): PhaseSidebarGroupingPreferences { + const { notificationOverrides: _previous, ...rest } = preferences; + return Object.keys(overrides).length === 0 ? rest : { ...rest, notificationOverrides: overrides }; +} + export function sanitizePhaseSidebarGrouping(value: unknown): PhaseSidebarGroupingPreferences { if (value === null || typeof value !== "object") return DEFAULT_PHASE_SIDEBAR_GROUPING; const candidate = value as { @@ -178,7 +220,9 @@ export function sanitizePhaseSidebarGrouping(value: unknown): PhaseSidebarGroupi readonly customGroupOrder?: unknown; readonly collapsedSectionKeys?: unknown; readonly runningShelf?: unknown; + readonly notificationOverrides?: unknown; }; + const notificationOverrides = sanitizeNotificationOverrides(candidate.notificationOverrides); const groupBy = PHASE_SIDEBAR_GROUP_BY_MODES.find((mode) => mode === candidate.groupBy); const groupOrder = PHASE_SIDEBAR_GROUP_ORDERS.find((order) => order === candidate.groupOrder); return { @@ -190,6 +234,7 @@ export function sanitizePhaseSidebarGrouping(value: unknown): PhaseSidebarGroupi ), collapsedSectionKeys: sanitizeStringList(candidate.collapsedSectionKeys), ...(candidate.runningShelf === true ? { runningShelf: true } : {}), + ...(notificationOverrides !== undefined ? { notificationOverrides } : {}), }; } @@ -220,6 +265,23 @@ export function setPhaseSidebarRunningShelf( return enabled ? { ...rest, runningShelf: true } : rest; } +/** + * This device's notification mode for a group (`id` is the section id; + * "ungrouped" for the built-in section). The shared registry is not touched: + * the override outranks it here only. + */ +export function setPhaseSidebarGroupNotificationOverride( + preferences: PhaseSidebarGroupingPreferences, + id: string, + mode: ThreadCustomGroupNotificationMode, +): PhaseSidebarGroupingPreferences { + if (id.length === 0 || preferences.notificationOverrides?.[id] === mode) return preferences; + return withNotificationOverrides(preferences, { + ...preferences.notificationOverrides, + [id]: mode, + }); +} + /** The section id a legacy local group renders under. */ function localGroupSectionId(group: PhaseSidebarCustomGroup): string { return phaseSidebarCustomGroupId(group.label); @@ -287,10 +349,12 @@ export function renamePhaseSidebarCustomGroup( const orderIndex = preferences.customGroupOrder.indexOf(id); const oldKey = phaseSidebarSectionKey("custom", id); const newKey = phaseSidebarSectionKey("custom", nextId); + const override = preferences.notificationOverrides?.[id]; if ( affected.length === 0 && orderIndex === -1 && - !preferences.collapsedSectionKeys.includes(oldKey) + !preferences.collapsedSectionKeys.includes(oldKey) && + (override === undefined || nextId === id) ) { return preferences; } @@ -317,7 +381,15 @@ export function renamePhaseSidebarCustomGroup( const collapsedSectionKeys = preferences.collapsedSectionKeys .map((key) => (key === oldKey ? newKey : key)) .filter((key, index, all) => all.indexOf(key) === index); - return { ...preferences, customGroups, customGroupOrder, collapsedSectionKeys }; + const renamed = { ...preferences, customGroups, customGroupOrder, collapsedSectionKeys }; + // The device's notification override follows the group. Renaming onto a + // group that has its own override keeps that one, as the registry keeps the + // target's shared mode. + if (override === undefined || nextId === id) return renamed; + return withNotificationOverrides(renamed, { + [nextId]: override, + ...withoutNotificationOverride(preferences, id), + }); } /** @@ -335,14 +407,18 @@ export function deletePhaseSidebarCustomGroup( ); const customGroupOrder = preferences.customGroupOrder.filter((entry) => entry !== id); const collapsedSectionKeys = preferences.collapsedSectionKeys.filter((key) => key !== sectionKey); + const hasOverride = preferences.notificationOverrides?.[id] !== undefined; if ( customGroups.length === preferences.customGroups.length && customGroupOrder.length === preferences.customGroupOrder.length && - collapsedSectionKeys.length === preferences.collapsedSectionKeys.length + collapsedSectionKeys.length === preferences.collapsedSectionKeys.length && + !hasOverride ) { return preferences; } - return { ...preferences, customGroups, customGroupOrder, collapsedSectionKeys }; + const next = { ...preferences, customGroups, customGroupOrder, collapsedSectionKeys }; + if (!hasOverride) return next; + return withNotificationOverrides(next, withoutNotificationOverride(preferences, id)); } /** @@ -445,7 +521,10 @@ export interface PhaseSidebarCustomGroupOption { /** The group's colour id and hex value; absent for the default look. */ readonly colorId?: string; readonly color?: string; - /** T3-CUSTOM(expbkt3): a shared group's mode when it is not "all"; absent means "all". */ + /** + * T3-CUSTOM(expbkt3): the group's mode when it is not "all" — this device's + * override, else the shared registry's; absent means "all". + */ readonly notifications?: ThreadCustomGroupNotificationMode; } @@ -490,7 +569,10 @@ export function listPhaseSidebarCustomGroups( } const options = [...byId.entries()].map(([id, entry]): PhaseSidebarCustomGroupOption => { const shared = registry.get(id); - if (shared === undefined) return { id, ...entry }; + // T3-CUSTOM(expbkt3): this device's override outranks the shared mode; absent means "all". + const notifications = preferences.notificationOverrides?.[id] ?? shared?.notifications ?? "all"; + const mode = notifications !== "all" ? { notifications } : {}; + if (shared === undefined) return { id, ...entry, ...mode }; return { id, ...entry, @@ -498,8 +580,7 @@ export function listPhaseSidebarCustomGroups( ...(shared.colorId !== null && shared.color !== null ? { colorId: shared.colorId, color: shared.color } : {}), - // T3-CUSTOM(expbkt3): absent means "all". - ...(shared.notifications !== "all" ? { notifications: shared.notifications } : {}), + ...mode, }; }); options.sort((left, right) => { @@ -795,6 +876,11 @@ export function buildPhaseSidebarSections( }); const allUngrouped = nodesById.get(PHASE_SIDEBAR_UNGROUPED_ID) ?? []; const ungrouped = placedNodes(allUngrouped); + // T3-CUSTOM(expbkt3): this device's override outranks the host setting. + const ungroupedNotifications = + grouping.notificationOverrides?.[PHASE_SIDEBAR_UNGROUPED_ID] ?? + input.ungroupedNotifications ?? + "all"; if (ungrouped.length > 0) { sections.push({ key: phaseSidebarSectionKey("custom", PHASE_SIDEBAR_UNGROUPED_ID), @@ -808,9 +894,7 @@ export function buildPhaseSidebarSections( isUngrouped: true, collapsedByDefault: false, // T3-CUSTOM(expbkt3) - ...(input.ungroupedNotifications !== undefined && input.ungroupedNotifications !== "all" - ? { notifications: input.ungroupedNotifications } - : {}), + ...(ungroupedNotifications !== "all" ? { notifications: ungroupedNotifications } : {}), }); } const manualIndex = new Map(registry.map((group, index) => [group.id, index])); From ce7f64f88538770671f975bbc4780b1fc9f20791 Mon Sep 17 00:00:00 2001 From: bk-agent-01 Date: Fri, 13 Nov 2026 08:35:49 +0000 Subject: [PATCH 02/15] feat(settings): reorganize BK Add-ons into Features, Connections, This device and Maintenance Co-Authored-By: Claude Opus 5.5 --- .../AgentPlanSubmissionSettingsRow.tsx | 8 +- .../settings/ExperimentsSettingsPanel.tsx | 200 +-------------- .../SessionArchiveSettingsSection.tsx | 18 +- apps/web/src/fork/BkAddonsFeaturesSection.tsx | 204 ++++++++++++++++ ...AddonsIntegrationsSection.browser.test.tsx | 26 +- .../src/fork/BkAddonsIntegrationsSection.tsx | 228 ++++++++++++------ apps/web/src/fork/BkAddonsServerSummary.tsx | 72 ++++++ ...ionWebhookSettingsSection.browser.test.tsx | 54 ++++- .../fork/SessionWebhookSettingsSection.tsx | 116 +++++---- apps/web/src/fork/SettingDescription.tsx | 27 +++ apps/web/src/fork/sessionWebhookSummary.ts | 44 ++++ 11 files changed, 687 insertions(+), 310 deletions(-) create mode 100644 apps/web/src/fork/BkAddonsFeaturesSection.tsx create mode 100644 apps/web/src/fork/BkAddonsServerSummary.tsx create mode 100644 apps/web/src/fork/SettingDescription.tsx create mode 100644 apps/web/src/fork/sessionWebhookSummary.ts diff --git a/apps/web/src/components/settings/AgentPlanSubmissionSettingsRow.tsx b/apps/web/src/components/settings/AgentPlanSubmissionSettingsRow.tsx index 600574e399f50..fdf4381d67c7b 100644 --- a/apps/web/src/components/settings/AgentPlanSubmissionSettingsRow.tsx +++ b/apps/web/src/components/settings/AgentPlanSubmissionSettingsRow.tsx @@ -4,6 +4,7 @@ import { usePrimarySettingsAvailable, useUpdatePrimarySettings, } from "../../hooks/useSettings"; +import { SettingDescription } from "../../fork/SettingDescription"; import { Switch } from "../ui/switch"; import { SettingsRow } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -17,7 +18,12 @@ export function AgentPlanSubmissionSettingsRow() { return ( + } control={ settings.phaseGroupedSidebarEnabled, - ); - // T3-CUSTOM(expbkt3): native plan review (moved here from the removed Beta panel). - const nativePlanReviewEnabled = useClientSettings((settings) => settings.nativePlanReviewEnabled); - // T3-CUSTOM(expbkt3): plan review takeover. - const planReviewAutoOpenEnabled = useClientSettings( - (settings) => settings.planReviewAutoOpenEnabled, - ); - // T3-CUSTOM(expbkt3): agent-rendered UI surfaces in chat. - const agentUiSurfacesEnabled = useClientSettings((settings) => settings.agentUiSurfacesEnabled); - // T3-CUSTOM(expbkt3): smart git button asks the agent. - const smartGitPromptsEnabled = useClientSettings((settings) => settings.smartGitPromptsEnabled); - // T3-CUSTOM(expbkt3): review comments on agent messages. - const chatCommentsEnabled = useClientSettings((settings) => settings.chatCommentsEnabled); - // T3-CUSTOM(expbkt3): upstream's pull request view. - const nativePullRequestViewEnabled = useClientSettings( - (settings) => settings.nativePullRequestViewEnabled, - ); - // T3-CUSTOM(expbkt3): every link opens in the integrated browser. - const openLinksInIntegratedBrowser = useClientSettings( - (settings) => settings.openLinksInIntegratedBrowser, - ); - return ( - {/* T3-CUSTOM(expbkt3): connections and callbacks remain in the Experiments route. */} + + {/* Toolyard, the default group and session callbacks, folded per server. */} - {/* T3-CUSTOM(expbkt3): renders only in the managed desktop build. */} + {/* This device: renders only in the managed desktop build. */} - - {/* T3-CUSTOM(expbkt3): BEGIN — native plan review. */} - - updateClientSettings({ nativePlanReviewEnabled: Boolean(checked) }) - } - aria-label="Native plan review" - /> - } - /> - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): independent from this device's native plan review display. */} - - {/* T3-CUSTOM(expbkt3): BEGIN — plan review takeover. */} - - updateClientSettings({ planReviewAutoOpenEnabled: Boolean(checked) }) - } - aria-label="Open a ready plan automatically" - /> - } - /> - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): BEGIN — agent-rendered UI surfaces in chat. */} - - updateClientSettings({ agentUiSurfacesEnabled: Boolean(checked) }) - } - aria-label="Agent views in chat" - /> - } - /> - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): BEGIN — smart git button asks the agent. */} - - updateClientSettings({ smartGitPromptsEnabled: Boolean(checked) }) - } - aria-label="Smart git button" - /> - } - /> - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): BEGIN — review comments on agent messages. */} - - updateClientSettings({ chatCommentsEnabled: Boolean(checked) }) - } - aria-label="Chat comments" - /> - } - /> - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): BEGIN — upstream's pull request view. */} - - updateClientSettings({ nativePullRequestViewEnabled: Boolean(checked) }) - } - aria-label="Native pull request view" - /> - } - /> - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): BEGIN — every link opens in the integrated browser. */} - - updateClientSettings({ openLinksInIntegratedBrowser: Boolean(checked) }) - } - aria-label="Open links in the integrated browser" - /> - } - /> - {/* T3-CUSTOM(expbkt3): END */} - - updateClientSettings({ - phaseGroupedSidebarEnabled: DEFAULT_UNIFIED_SETTINGS.phaseGroupedSidebarEnabled, - }) - } - /> - ) : null - } - control={ - - updateClientSettings({ phaseGroupedSidebarEnabled: Boolean(checked) }) - } - aria-label="Enable the BK sidebar" - /> - } - /> - - {/* T3-CUSTOM(expbkt3): BEGIN — experimental operator MCP settings seam. */} - {EXPERIMENTAL_CONTROL_CENTER_ENABLED ? : null} - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): BEGIN — archived-session worktree reclaim. */} - - {/* T3-CUSTOM(expbkt3): END */} - {/* T3-CUSTOM(expbkt3): BEGIN — log out (web and desktop). */} - {/* T3-CUSTOM(expbkt3): END */} + {/* Maintenance. */} + + {EXPERIMENTAL_CONTROL_CENTER_ENABLED ? : null} ); } diff --git a/apps/web/src/components/settings/SessionArchiveSettingsSection.tsx b/apps/web/src/components/settings/SessionArchiveSettingsSection.tsx index 5a2498c7978ba..07ee59ed2b646 100644 --- a/apps/web/src/components/settings/SessionArchiveSettingsSection.tsx +++ b/apps/web/src/components/settings/SessionArchiveSettingsSection.tsx @@ -20,7 +20,8 @@ import { NumberFieldIncrement, NumberFieldInput, } from "../ui/number-field"; -import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout"; +import { FoldedSettingsSection } from "./FoldedSettingsSection"; +import { SettingResetButton, SettingsRow } from "./settingsLayout"; const DEFAULTS = DEFAULT_UNIFIED_SETTINGS.experimental.sessionArchive; const MAX_RETENTION_DAYS = 365; @@ -50,8 +51,19 @@ export function SessionArchiveSettingsSection() { ? `Deletes regenerable directories from worktrees archived more than ${archive.autoSweep.minArchivedDays} days ago.` : `Removes worktrees archived more than ${archive.autoSweep.minArchivedDays} days ago, when they are clean and pushed.`; + // Folded: these rows are set once, so the page shows only where they stand. + const foldSummary = !archive.enabled + ? "Off" + : !archive.autoSweep.enabled + ? "On · reclaim by hand" + : `On · ${archive.autoSweep.mode === "slim" ? "slims" : "removes"} worktrees after ${archive.autoSweep.minArchivedDays} days`; + return ( - + } /> - + ); } diff --git a/apps/web/src/fork/BkAddonsFeaturesSection.tsx b/apps/web/src/fork/BkAddonsFeaturesSection.tsx new file mode 100644 index 0000000000000..3d52c9f16303b --- /dev/null +++ b/apps/web/src/fork/BkAddonsFeaturesSection.tsx @@ -0,0 +1,204 @@ +/** + * T3-CUSTOM(expbkt3): the BK Add-ons feature switches. Each row shows one sentence; the full + * explanation stays one click away behind "More". + */ +import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; + +import { AgentPlanSubmissionSettingsRow } from "../components/settings/AgentPlanSubmissionSettingsRow"; +import { + SettingResetButton, + SettingsRow, + SettingsSection, +} from "../components/settings/settingsLayout"; +import { searchableSetting } from "../components/settings/settingsSearch"; +import { Switch } from "../components/ui/switch"; +import { updateClientSettings, useClientSettings } from "../hooks/useSettings"; +import { SettingDescription } from "./SettingDescription"; + +function ClientSwitch({ + checked, + disabled = false, + label, + onChange, +}: { + readonly checked: boolean; + readonly disabled?: boolean; + readonly label: string; + readonly onChange: (checked: boolean) => void; +}) { + return ( + onChange(Boolean(value))} + aria-label={label} + /> + ); +} + +export function BkAddonsFeaturesSection() { + const phaseGroupedSidebarEnabled = useClientSettings( + (settings) => settings.phaseGroupedSidebarEnabled, + ); + const nativePlanReviewEnabled = useClientSettings((settings) => settings.nativePlanReviewEnabled); + const planReviewAutoOpenEnabled = useClientSettings( + (settings) => settings.planReviewAutoOpenEnabled, + ); + const agentUiSurfacesEnabled = useClientSettings((settings) => settings.agentUiSurfacesEnabled); + const smartGitPromptsEnabled = useClientSettings((settings) => settings.smartGitPromptsEnabled); + const chatCommentsEnabled = useClientSettings((settings) => settings.chatCommentsEnabled); + const nativePullRequestViewEnabled = useClientSettings( + (settings) => settings.nativePullRequestViewEnabled, + ); + const openLinksInIntegratedBrowser = useClientSettings( + (settings) => settings.openLinksInIntegratedBrowser, + ); + + return ( + + + } + resetAction={ + phaseGroupedSidebarEnabled !== DEFAULT_UNIFIED_SETTINGS.phaseGroupedSidebarEnabled ? ( + + updateClientSettings({ + phaseGroupedSidebarEnabled: DEFAULT_UNIFIED_SETTINGS.phaseGroupedSidebarEnabled, + }) + } + /> + ) : null + } + control={ + updateClientSettings({ phaseGroupedSidebarEnabled: checked })} + /> + } + /> + + } + control={ + updateClientSettings({ nativePlanReviewEnabled: checked })} + /> + } + /> + + } + control={ + updateClientSettings({ planReviewAutoOpenEnabled: checked })} + /> + } + /> + {/* Saved on the server for every session, independent of this device's plan review. */} + + + } + control={ + updateClientSettings({ agentUiSurfacesEnabled: checked })} + /> + } + /> + + } + control={ + updateClientSettings({ chatCommentsEnabled: checked })} + /> + } + /> + + } + control={ + updateClientSettings({ smartGitPromptsEnabled: checked })} + /> + } + /> + + } + control={ + updateClientSettings({ nativePullRequestViewEnabled: checked })} + /> + } + /> + + } + control={ + updateClientSettings({ openLinksInIntegratedBrowser: checked })} + /> + } + /> + + ); +} diff --git a/apps/web/src/fork/BkAddonsIntegrationsSection.browser.test.tsx b/apps/web/src/fork/BkAddonsIntegrationsSection.browser.test.tsx index 5b12ebbe37ca1..c9b2096556ebe 100644 --- a/apps/web/src/fork/BkAddonsIntegrationsSection.browser.test.tsx +++ b/apps/web/src/fork/BkAddonsIntegrationsSection.browser.test.tsx @@ -64,6 +64,11 @@ vi.mock(import("./SessionWebhookSettingsSection"), async (original) => ({ /> )) as never, })); +// The folded header's status line reads live server queries. +vi.mock(import("./BkAddonsServerSummary"), async (original) => ({ + ...(await original()), + BkAddonsServerSummary: (() => null) as never, +})); vi.mock(import("./DefaultCustomGroupSetting"), async (original) => ({ ...(await original()), EnvironmentDefaultCustomGroupSetting: (() => null) as never, @@ -78,10 +83,15 @@ vi.mock(import("../components/settings/settingsLayout"), async (original) => ({ import { BkAddonsIntegrationsSection } from "./BkAddonsIntegrationsSection"; const rowsIn = (root: ParentNode) => [...root.querySelectorAll("[data-kind]")]; +const serverGroups = (root: ParentNode) => [ + ...root.querySelectorAll('section[aria-label^="BK Add-ons for"]'), +]; +const foldKey = (environmentId: string) => `t3-bk-addons-server-open:${environmentId}`; it("groups only selected connected servers and retains the offline server", async () => { await using screen = await render(); - const groups = [...screen.container.querySelectorAll("section")]; + // Folded servers keep their cards mounted, so a Toolyard sign-in can finish while closed. + const groups = serverGroups(screen.container); expect(groups).toHaveLength(3); for (const [index, environmentId] of ["stage", "mac"].entries()) { const rows = rowsIn(groups[index]!); @@ -107,3 +117,17 @@ it("refreshes only the chosen server's connection and callbacks", async () => { "1", ]); }); + +it("folds each connected server until opened, and remembers it on this device", async () => { + for (const id of ["stage", "mac"]) window.localStorage.removeItem(foldKey(id)); + await using screen = await render(); + const stage = screen.getByRole("button", { name: /^Stage/ }); + await expect.element(stage).toHaveAttribute("aria-expanded", "false"); + await userEvent.click(stage); + await expect.element(stage).toHaveAttribute("aria-expanded", "true"); + await expect.poll(() => window.localStorage.getItem(foldKey("stage"))).toBe("1"); + await expect + .element(screen.getByRole("button", { name: /^Mac/ })) + .toHaveAttribute("aria-expanded", "false"); + window.localStorage.removeItem(foldKey("stage")); +}); diff --git a/apps/web/src/fork/BkAddonsIntegrationsSection.tsx b/apps/web/src/fork/BkAddonsIntegrationsSection.tsx index 4dd710a02fdaf..5ac7c36b002f0 100644 --- a/apps/web/src/fork/BkAddonsIntegrationsSection.tsx +++ b/apps/web/src/fork/BkAddonsIntegrationsSection.tsx @@ -1,16 +1,47 @@ /** T3-CUSTOM(expbkt3): group user-owned connections and callbacks by selected server. */ -import { useState } from "react"; -import { RefreshCwIcon } from "lucide-react"; +import { useEffect, useState } from "react"; +import { ChevronRightIcon, RefreshCwIcon } from "lucide-react"; import { Button } from "../components/ui/button"; import { Badge } from "../components/ui/badge"; +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../components/ui/collapsible"; import { useSettingsScope } from "../components/settings/SettingsScopeContext"; -import { SettingsSearchTarget } from "../components/settings/settingsLayout"; +import { SettingsGroup } from "../components/settings/SettingsGroup"; +import { + SettingsSearchTarget, + SettingsSection, + useSettingsSearchTargetId, +} from "../components/settings/settingsLayout"; import { EnvironmentToolyardSettings } from "../components/settings/ToolyardSettingsSection"; -import { EnvironmentSessionWebhookSettings } from "./SessionWebhookSettingsSection"; +import { cn } from "../lib/utils"; +import { BkAddonsServerSummary } from "./BkAddonsServerSummary"; import { EnvironmentDefaultCustomGroupSetting } from "./DefaultCustomGroupSetting"; +import { EnvironmentSessionWebhookSettings } from "./SessionWebhookSettingsSection"; +import { pendingToolyardSettingsContinuation } from "./toolyardSettingsContinuation"; type SelectedEnvironment = ReturnType["environments"][number]; +/** Search results that land inside the first server's fold. */ +const FIRST_SERVER_TARGETS: ReadonlyArray = [ + "toolyard", + "session-webhooks", + "default-custom-group", +]; + +/** A Toolyard browser sign-in returns to this page; its card must be visible to report back. */ +const toolyardReturnPending = () => + pendingToolyardSettingsContinuation() !== null || + window.location.hash.startsWith("#toolyard-settings="); + +const FOLD_STORAGE_PREFIX = "t3-bk-addons-server-open:"; + +function readRememberedOpen(environmentId: string): boolean { + try { + return window.localStorage.getItem(FOLD_STORAGE_PREFIX + environmentId) === "1"; + } catch { + return false; + } +} + function ServerAddons({ environment, first, @@ -19,70 +50,121 @@ function ServerAddons({ readonly first: boolean; }) { const [refreshVersion, setRefreshVersion] = useState(0); - const connected = environment.connection.phase === "connected" && environment.serverConfig; + const serverConfig = + environment.connection.phase === "connected" ? environment.serverConfig : null; const connecting = environment.connection.phase === "connecting" || environment.connection.phase === "reconnecting"; - return ( -
    -
    -
    -

    {environment.label}

    + // Closed by default; each server's fold is remembered on this device. + const [open, setOpen] = useState( + () => toolyardReturnPending() || readRememberedOpen(environment.environmentId), + ); + useEffect(() => { + try { + window.localStorage.setItem( + FOLD_STORAGE_PREFIX + environment.environmentId, + open ? "1" : "0", + ); + } catch { + // Storage can be blocked; the fold still works for this visit. + } + }, [environment.environmentId, open]); + // A search jump lands inside the first server's fold, so open it before its target mounts. + const searchTargetId = useSettingsSearchTargetId(); + const [seenSearchTargetId, setSeenSearchTargetId] = useState(null); + if (seenSearchTargetId !== searchTargetId) { + setSeenSearchTargetId(searchTargetId); + if (first && searchTargetId !== null && FIRST_SERVER_TARGETS.includes(searchTargetId)) + setOpen(true); + } + const sectionLabel = `BK Add-ons for ${environment.label}`; + + if (!serverConfig) { + return ( +
    +
    +

    {environment.label}

    - {connected - ? environment.serverConfig?.auth.clerk - ? "Team server" - : "Local profile" - : connecting - ? "Server connects" - : "Server disconnected"} + {connecting ? "Server connects" : "Server disconnected"}
    - {connected ? ( + +

    + {connecting + ? `Wait for ${environment.label} to connect.` + : `Reconnect ${environment.label} to inspect Toolyard and session callbacks.`} +

    +
    +
    + ); + } + + return ( +
    + +
    +

    + + + {environment.label} + + {serverConfig.auth.clerk ? "Team server" : "Local profile"} + + + + + +

    - ) : null} -
    - {connected && environment.serverConfig ? ( - <> - - - - - - + {/* Kept mounted: Toolyard finishes a browser sign-in and drafts even while folded. */} + +
    + + + + + + - - - ) : ( - -

    - {connecting - ? `Wait for ${environment.label} to connect.` - : `Reconnect ${environment.label} to inspect Toolyard and session callbacks.`} -

    -
    - )} + + + +
    +
    +
    ); } @@ -90,26 +172,28 @@ function ServerAddons({ export function BkAddonsIntegrationsSection() { const { environments } = useSettingsScope(); return ( - -

    - Connections are saved per server for your account. The project selection filters the server - list. -

    - {environments.length === 0 ? ( - -

    - Select a server to inspect Toolyard and session callbacks. -

    -
    - ) : ( - environments.map((environment, index) => ( - - )) - )} -
    + +
    +

    + Toolyard, session callbacks and the default group, saved per server for your account. + The project selection filters this list. +

    + {environments.length === 0 ? ( + +

    + Select a server to inspect Toolyard and session callbacks. +

    +
    + ) : ( + environments.map((environment, index) => ( + + )) + )} +
    +
    ); } diff --git a/apps/web/src/fork/BkAddonsServerSummary.tsx b/apps/web/src/fork/BkAddonsServerSummary.tsx new file mode 100644 index 0000000000000..801bfab1c0309 --- /dev/null +++ b/apps/web/src/fork/BkAddonsServerSummary.tsx @@ -0,0 +1,72 @@ +/** + * T3-CUSTOM(expbkt3): the one-line Toolyard and session-callback status shown on a folded + * server in BK Add-ons. It reads the same query atoms the open cards read, so a fold adds no + * extra request. + */ +import { useAtomValue } from "@effect/atom-react"; +import { toolyardConnectionPresentation } from "@t3tools/client-runtime/bk-toolyard-presentation"; +import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; +import type { EnvironmentId } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { AsyncResult } from "effect/reactivity"; +import { useMemo } from "react"; + +import { useEnvironmentSessionState } from "../state/session"; +import { serverEnvironment } from "../state/server"; +import { sessionWebhookAttentionText, summarizeSessionWebhooks } from "./sessionWebhookSummary"; + +export function BkAddonsServerSummary({ + environmentId, + serverConfig, +}: { + readonly environmentId: EnvironmentId; + readonly serverConfig: EnvironmentServerConfig; +}) { + const { data: session } = useEnvironmentSessionState(environmentId); + // The cards scope their queries the same way; another scope would be another request. + const userScope = session?.authenticated + ? (session.userId ?? (serverConfig.auth.clerk ? null : "local-user")) + : null; + if (!userScope) return Sign in to this server to see its connections; + return ; +} + +function ScopedSummary({ + environmentId, + userScope, +}: { + readonly environmentId: EnvironmentId; + readonly userScope: string; +}) { + const target = useMemo( + () => ({ environmentId, input: { userScope } }), + [environmentId, userScope], + ); + const toolyardAtom = useMemo(() => serverEnvironment.toolyardIntegrationStatus(target), [target]); + const webhooksAtom = useMemo(() => serverEnvironment.sessionWebhooksList(target), [target]); + const toolyardResult = useAtomValue(toolyardAtom); + const webhooksResult = useAtomValue(webhooksAtom); + const toolyard = toolyardConnectionPresentation( + Option.getOrNull(AsyncResult.value(toolyardResult)), + ); + const webhooks = Option.getOrNull(AsyncResult.value(webhooksResult)); + const callbacks = webhooks === null ? null : summarizeSessionWebhooks(webhooks); + const callbackAttention = callbacks === null ? null : sessionWebhookAttentionText(callbacks); + const toolyardNeedsYou = toolyard.tone === "warning" || toolyard.tone === "error"; + return ( + <> + + Toolyard: {toolyard.label} + + {callbacks === null ? null : ( + <> + {" · "} + + {callbackAttention ?? + (callbacks.total === 1 ? "1 callback" : `${callbacks.total} callbacks`)} + + + )} + + ); +} diff --git a/apps/web/src/fork/SessionWebhookSettingsSection.browser.test.tsx b/apps/web/src/fork/SessionWebhookSettingsSection.browser.test.tsx index 785f7a2055363..b7d8c6ab29243 100644 --- a/apps/web/src/fork/SessionWebhookSettingsSection.browser.test.tsx +++ b/apps/web/src/fork/SessionWebhookSettingsSection.browser.test.tsx @@ -168,13 +168,14 @@ const failure = (code: string) => Cause.fail(new PersonalMcpSettingsError({ operation: "Session webhook", message: code })), ); const serverConfig = (clerk: boolean) => ({ auth: clerk ? { clerk: {} } : {} }) as never; -function server(environmentId: string, clerk = true) { +function server(environmentId: string, clerk = true, expandRequested = false) { return ( ); } @@ -209,9 +210,45 @@ function setup() { mocks.webhooks.set("env_stage", [webhook()]); } +it("folds the webhook list and its callbacks behind a one-line summary", async () => { + setup(); + mocks.webhooks.set("env_stage", [ + webhook({ + deliveries: [ + { + eventId: "evt_done", + state: "delivered", + attempts: 1, + receivedAt: "2026-10-01T10:01:00.000Z", + updatedAt: "2026-10-01T10:01:01.000Z", + terminalReason: null, + }, + ], + }), + ]); + await using view = await mount(); + expect(view.text()).toContain("1 callback: 1 active"); + expect(view.text()).not.toContain("Fix login"); + expect(view.buttons("Earlier callbacks")).toHaveLength(0); + await view.press("Show"); + expect(view.text()).toContain("Fix login"); + expect(view.buttons("Earlier callbacks (1)")).toHaveLength(1); + await view.press("Hide"); + expect(view.text()).not.toContain("Fix login"); +}); + +it("opens the list when a settings search lands on it", async () => { + setup(); + await using view = await mount(); + expect(view.text()).not.toContain("Fix login"); + await view.rerender(<>{server("env_stage", true, true)}); + expect(view.text()).toContain("Fix login"); +}); + it("cancelling a confirmation sends no change", async () => { setup(); await using view = await mount(); + await view.press("Show"); await view.press("Disable"); expect(textOf(view.dialog()!)).toContain("Disable callbacks for Fix login?"); await view.press("Cancel", view.dialog()!); @@ -223,6 +260,7 @@ it("confirming sends the exact server, webhook and revision the user saw", async setup(); mocks.update.mockResolvedValue(AsyncResult.success({})); await using view = await mount(); + await view.press("Show"); await view.press("Remove"); await view.press("Remove", view.dialog()!); expect(mocks.update).toHaveBeenCalledTimes(1); @@ -238,6 +276,7 @@ it("shows a failed change inline on its card without leaking unknown text", asyn setup(); mocks.update.mockResolvedValueOnce(failure("webhook-revision-conflict")); await using view = await mount(); + await view.press("Show"); await view.press("Rotate secret"); await view.press("Rotate secret", view.dialog()!); expect(view.dialog()).toBeUndefined(); @@ -269,6 +308,7 @@ it("keys each server's list by its authenticated user and resets state on a user expect(view.text().match(/Authenticate with this server/g)).toHaveLength(2); mocks.update.mockResolvedValueOnce(failure("webhook-not-found")); + await view.press("Show"); await view.press("Disable"); await view.press("Disable", view.dialog()!); expect(view.alerts().join()).toContain("This webhook no longer exists for your account."); @@ -278,7 +318,10 @@ it("keys each server's list by its authenticated user and resets state on a user environmentId: "env_stage", input: { userScope: "user_b" }, }); - // Another user's error must not survive into this user's view. + // Another user's error must not survive into this user's view, folded or open. + expect(view.text()).not.toContain("no longer exists"); + await view.press("Show"); + expect(view.text()).toContain("Fix login"); expect(view.text()).not.toContain("no longer exists"); }); @@ -304,6 +347,11 @@ it("keeps sync failures visible, including removed webhooks outside their closed }), ]); await using view = await mount(); + // Folded, the summary still flags both webhooks; the details open on demand. + expect(view.text()).toContain("2 callbacks: 1 disabled · 1 removed"); + expect(view.text()).toContain("2 webhooks need attention"); + expect(view.alerts()).toEqual([]); + await view.press("Show"); const visible = view.alerts().join(); expect(visible).toContain( "Disable could not sync with Toolyard, and the server stopped retrying", @@ -338,6 +386,8 @@ it("leaves a deliberate Disable as history without an attention badge", async () }), ]); await using view = await mount(); + expect(view.text()).not.toMatch(/needs? attention/); + await view.press("Show"); expect(view.text()).not.toMatch(/\d+ events? needs? attention/); expect(view.alerts()).toEqual([]); expect(view.text()).toContain("No callbacks need attention."); diff --git a/apps/web/src/fork/SessionWebhookSettingsSection.tsx b/apps/web/src/fork/SessionWebhookSettingsSection.tsx index 821bf5140c182..9704545c4ea02 100644 --- a/apps/web/src/fork/SessionWebhookSettingsSection.tsx +++ b/apps/web/src/fork/SessionWebhookSettingsSection.tsx @@ -5,7 +5,6 @@ import { callbackDispatchLabel, callbackTransportLabel, sessionCallbackAttempts, - sessionCallbackAttentionCount, sessionCallbackEvents, sessionCallbackHistoryWarning, sessionCallbackOpen, @@ -35,7 +34,7 @@ import { MinusIcon, TriangleAlertIcon, } from "lucide-react"; -import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; import { useEnvironmentSessionState } from "../state/session"; import { useSettingsScope } from "../components/settings/SettingsScopeContext"; import { useThreadShell } from "../state/entities"; @@ -56,6 +55,11 @@ import { Button } from "../components/ui/button"; import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../components/ui/collapsible"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../components/ui/menu"; import { SettingsSection } from "../components/settings/settingsLayout"; +import { + sessionWebhookAttentionText, + sessionWebhookCountsText, + summarizeSessionWebhooks, +} from "./sessionWebhookSummary"; interface PendingChange { readonly webhook: SessionWebhookView; @@ -123,7 +127,9 @@ export function SessionWebhookSettingsSection() { /** * Session callbacks for one server. `compact` renders the card inside a per-server group whose - * Refresh bumps `refreshVersion`; the standalone form keeps its own Refresh. + * Refresh bumps `refreshVersion`; the standalone form keeps its own Refresh. The card shows a + * one-line summary; the webhook list and its delivery history open on demand, or when + * `expandRequested` turns true (a settings search jump). */ export function EnvironmentSessionWebhookSettings({ environmentId, @@ -131,12 +137,14 @@ export function EnvironmentSessionWebhookSettings({ serverConfig, compact = false, refreshVersion, + expandRequested = false, }: { readonly environmentId: EnvironmentId; readonly label: string; readonly serverConfig: EnvironmentServerConfig; readonly compact?: boolean; readonly refreshVersion?: number; + readonly expandRequested?: boolean; }) { const { data: session } = useEnvironmentSessionState(environmentId); const userScope = session?.authenticated @@ -150,6 +158,7 @@ export function EnvironmentSessionWebhookSettings({ userScope={userScope} compact={compact} refreshVersion={refreshVersion} + expandRequested={expandRequested} /> ) : ( @@ -166,12 +175,14 @@ function SessionWebhookSettingsContent({ userScope, compact, refreshVersion, + expandRequested, }: { readonly environmentId: EnvironmentId; readonly label: string; readonly userScope: string; readonly compact: boolean; readonly refreshVersion: number | undefined; + readonly expandRequested: boolean; }) { const atom = useMemo( () => serverEnvironment.sessionWebhooksList({ environmentId, input: { userScope } }), @@ -195,17 +206,22 @@ function SessionWebhookSettingsContent({ // A confirmed Remove moves the card into a closed section, unmounting the focus target. const listRef = useRef(null); const [focusList, setFocusList] = useState(false); + // The list, with every delivery and reply, stays folded behind the summary until asked for. + const [expanded, setExpanded] = useState(expandRequested); + const [seenExpandRequest, setSeenExpandRequest] = useState(expandRequested); + if (seenExpandRequest !== expandRequested) { + setSeenExpandRequest(expandRequested); + if (expandRequested) setExpanded(true); + } + const bodyId = useId(); + const summary = useMemo(() => summarizeSessionWebhooks(webhooks ?? []), [webhooks]); + const attentionText = sessionWebhookAttentionText(summary); const views = useMemo( () => (webhooks ?? []).map((webhook) => ({ webhook, events: sessionCallbackEvents(webhook) })), [webhooks], ); const current = views.filter(({ webhook }) => webhook.status !== "removed"); const removed = views.filter(({ webhook }) => webhook.status === "removed"); - // Removed webhooks surface their issues beside the section instead of in this badge. - const attentionCount = current.reduce( - (count, { events }) => count + sessionCallbackAttentionCount(events), - 0, - ); const change = async ({ webhook, action }: PendingChange) => { setBusy(webhook.id); setFocusList(false); @@ -259,50 +275,64 @@ function SessionWebhookSettingsContent({ - {attentionCount > 0 ? ( - - - {attentionCount === 1 - ? "1 event needs attention" - : `${attentionCount} events need attention`} - - ) : null} - {compact ? null : ( + compact ? null : ( + + ) + } + > +
    +
    + {webhooks === null ? ( +

    + {refreshFailed + ? "Callback status is unavailable. Check the server connection, then refresh." + : "Loading callback status…"} +

    + ) : views.length === 0 ? ( +

    + None yet. Agents create these for a session. +

    + ) : ( +

    + {sessionWebhookCountsText(summary)} + {attentionText ? ( + · {attentionText} + ) : null} +

    + )} + {views.length > 0 ? ( - )} + ) : null}
    - } - > -
    -

    - Agents create a callback for one session. Toolyard decisions queue after the active turn. - Callbacks report decisions; they do not grant permission. Only recent events are listed. -

    {refreshFailed && webhooks !== null ? ( The last refresh failed. Showing the status loaded earlier. ) : null} - {webhooks === null ? ( -

    - {refreshFailed - ? "Callback status is unavailable. Check the server connection, then refresh." - : "Loading callback status…"} -

    - ) : views.length === 0 ? ( -

    - None yet. Agents create these for a session. -

    - ) : ( - <> + {expanded && views.length > 0 ? ( +
    +

    + Agents create a callback for one session. Toolyard decisions queue after the active + turn. Callbacks report decisions; they do not grant permission. Only recent events are + listed. +

    {current.map(card)} {removed.length > 0 ? ( <> @@ -319,8 +349,8 @@ function SessionWebhookSettingsContent({ ) : null} - - )} +
    + ) : null}
    ` allows only phrasing content). */ +export function SettingDescription({ + summary, + details, +}: { + readonly summary: string; + readonly details: string; +}) { + const [open, setOpen] = useState(false); + return ( + <> + {summary} + {open ? ` ${details}` : null}{" "} + + + ); +} diff --git a/apps/web/src/fork/sessionWebhookSummary.ts b/apps/web/src/fork/sessionWebhookSummary.ts new file mode 100644 index 0000000000000..d7a54e701f887 --- /dev/null +++ b/apps/web/src/fork/sessionWebhookSummary.ts @@ -0,0 +1,44 @@ +/** T3-CUSTOM(expbkt3): one-line summary of a server's session callbacks for BK Add-ons. */ +import { + sessionCallbackEvents, + sessionWebhookRemovedIssues, +} from "@t3tools/client-runtime/bk-session-callback-presentation"; +import type { SessionWebhookView } from "@t3tools/contracts"; + +export interface SessionWebhookSummary { + readonly total: number; + readonly counts: Readonly>; + /** Webhooks with a sync failure, missing Toolyard history, or a failed or stopped event. */ + readonly needsAttention: number; +} + +export function summarizeSessionWebhooks( + webhooks: ReadonlyArray, +): SessionWebhookSummary { + const counts = { registering: 0, active: 0, disabled: 0, removed: 0 }; + let needsAttention = 0; + for (const webhook of webhooks) { + counts[webhook.status] += 1; + // The removed-webhook issue list is the same three checks the cards show for any webhook. + if (sessionWebhookRemovedIssues(webhook, sessionCallbackEvents(webhook)).length > 0) + needsAttention += 1; + } + return { total: webhooks.length, counts, needsAttention }; +} + +/** "2 active · 1 removed", or a plain sentence when there are none. */ +export function sessionWebhookCountsText(summary: SessionWebhookSummary): string { + if (summary.total === 0) return "No session callbacks yet"; + const parts = (["active", "registering", "disabled", "removed"] as const) + .filter((status) => summary.counts[status] > 0) + .map((status) => `${summary.counts[status]} ${status}`); + const total = summary.total === 1 ? "1 callback" : `${summary.total} callbacks`; + return `${total}: ${parts.join(" · ")}`; +} + +export function sessionWebhookAttentionText(summary: SessionWebhookSummary): string | null { + if (summary.needsAttention === 0) return null; + return summary.needsAttention === 1 + ? "1 webhook needs attention" + : `${summary.needsAttention} webhooks need attention`; +} From 8b70f4c001fecdff74717221a1509a6c45a3f651 Mon Sep 17 00:00:00 2001 From: bk-agent-01 Date: Fri, 13 Nov 2026 08:35:49 +0000 Subject: [PATCH 03/15] feat(toolyard): default to toolyard.beknown.live, T3_TOOLYARD_URL override, smoother team sign-in Co-Authored-By: Claude Opus 5.5 --- .../settings/ToolyardSettingsSection.tsx | 87 +++++++++-- apps/server/src/mcp/McpUpstreamProxy.ts | 6 +- apps/server/src/mcp/ToolyardConnect.test.ts | 2 +- apps/server/src/mcp/UserMcpProfileStore.ts | 12 +- .../toolyard/ToolyardConnectionCore.test.ts | 137 +++++++++++++++++- .../src/toolyard/ToolyardConnectionCore.ts | 105 +++++++++++++- .../src/toolyard/ToolyardIntegration.test.ts | 33 +++++ .../src/toolyard/ToolyardIntegration.ts | 39 ++++- .../src/toolyard/toolyardDefaultUrl.test.ts | 65 +++++++++ .../server/src/toolyard/toolyardDefaultUrl.ts | 77 ++++++++++ .../ToolyardSettingsSection.browser.test.tsx | 56 ++++++- .../settings/ToolyardSettingsSection.tsx | 103 +++++++++++-- docs/operations/expbkt3-customizations.md | 130 ++++++++--------- docs/user/t3-mcp-control.md | 12 +- .../toolyardConnectionPresentation.test.ts | 47 ++++++ .../fork/toolyardConnectionPresentation.ts | 58 ++++++++ packages/contracts/src/personalMcp.ts | 36 ++++- packages/contracts/src/toolyardIntegration.ts | 8 + 18 files changed, 907 insertions(+), 106 deletions(-) create mode 100644 apps/server/src/toolyard/toolyardDefaultUrl.test.ts create mode 100644 apps/server/src/toolyard/toolyardDefaultUrl.ts diff --git a/apps/mobile/src/features/settings/ToolyardSettingsSection.tsx b/apps/mobile/src/features/settings/ToolyardSettingsSection.tsx index 691a8232c314a..68ffa3b87f4f6 100644 --- a/apps/mobile/src/features/settings/ToolyardSettingsSection.tsx +++ b/apps/mobile/src/features/settings/ToolyardSettingsSection.tsx @@ -7,7 +7,10 @@ import * as Option from "effect/Option"; import { AsyncResult, type Atom } from "effect/reactivity"; import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { + canReconnectToolyardTeam, toolyardConnectionPresentation, + toolyardConnectionProblem, + toolyardInstanceHost, toolyardMethodLabel, } from "@t3tools/client-runtime/bk-toolyard-presentation"; import { @@ -18,7 +21,7 @@ import { toolyardSettingsOrigin, type ToolyardSettingsDraft, } from "@t3tools/client-runtime/toolyard-trust-setup"; -import type { ToolyardIntegrationStatus } from "@t3tools/contracts"; +import { DEFAULT_TOOLYARD_BASE_URL, type ToolyardIntegrationStatus } from "@t3tools/contracts"; import { Alert, Linking, Pressable, Switch, View } from "react-native"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text, AppTextInput } from "../../components/ui/AppText"; @@ -302,12 +305,19 @@ function EnvironmentToolyardContent({ setBrowserDraft(null); setError(null); } + // The server names its default instance; an unconfigured server starts from it. + const defaultBaseUrl = status?.defaultBaseUrl ?? DEFAULT_TOOLYARD_BASE_URL; + const unconfigured = status !== null && (!status.baseUrl || status.removed); const current = draft ?? { - baseUrl: status?.baseUrl ?? "", - enabled: status?.enabled ?? false, + baseUrl: unconfigured ? defaultBaseUrl : (status?.baseUrl ?? ""), + enabled: unconfigured ? true : (status?.enabled ?? false), revision: status?.revision ?? 0, }; const mode = current.mode ?? status?.mode ?? "team"; + const setupReady = Boolean(status?.administrator && unconfigured && mode === "team"); + const canReconnect = mode === "team" && canReconnectToolyardTeam(status); + const problem = toolyardConnectionProblem(status); + const instanceHost = toolyardInstanceHost(status?.baseUrl); const modeChange = status?.connection === "connected" && mode !== (status.mode ?? "team"); const canDisconnect = status?.connection === "connected" && @@ -417,6 +427,39 @@ function EnvironmentToolyardContent({ const timer = setInterval(() => appAtomRegistry.refresh(atom), 3000); return () => clearInterval(timer); }, [status?.pendingConnection?.status, atom]); + // The request runs outside the try: the React Compiler cannot lower a conditional inside one. + const submitReconnect = async () => { + if (!status) return; + const saved = await configure({ + environmentId: target.environmentId, + input: { + expectedRevision: status.revision, + baseUrl: status.baseUrl ?? "", + origin: status.origin ?? "", + enabled: true, + mode: "team", + reconnect: true, + }, + }); + appAtomRegistry.refresh(atom); + if (!AsyncResult.isSuccess(saved)) + setError(toolyardSettingsFailureMessage(toolyardSettingsFailureCode(saved.cause))); + else if (saved.value.connection !== "connected") + setError( + toolyardConnectionProblem(saved.value) ?? + "Toolyard did not restore the connection. Select Refresh, then try again.", + ); + }; + const reconnect = async () => { + setBusy(true); + setError(null); + try { + await submitReconnect(); + } catch { + setError("The reconnect request failed. Select Refresh, then try again."); + } + setBusy(false); + }; const consentAction = async (cancel: boolean) => { if (!status?.pendingConnection || !status.baseUrl) return; setError(null); @@ -493,7 +536,7 @@ function EnvironmentToolyardContent({ modeChange || (mode === "team" && status.teamAvailable === false) || (mode === "host" && status.pendingConnection?.status === "pending") || - (!draft && !apiKey && !status.removed && mode !== "host") || + (!draft && !apiKey && !status.removed && !setupReady && mode !== "host") || ((mode === "api-key" || mode === "host") && !status.baseUrl && !status.administrator); const saveLabel = mode === "host" && current.enabled @@ -512,6 +555,7 @@ function EnvironmentToolyardContent({ : bkAddonTone(presentation.label, presentation.tone); const summary = connected ? [ + instanceHost ? `Toolyard ${instanceHost}` : null, presentation.host ?? target.label, presentation.method, status?.expiresAt ? `Access expires ${bkAddonTime(status.expiresAt)}` : null, @@ -540,16 +584,26 @@ function EnvironmentToolyardContent({ {summary ? {summary} : null} - Toolyard Inbox asks you to decide on restricted calls. + {status.mode === "team" + ? "T3 signed you in automatically with your account on this server. Toolyard Inbox asks you to decide on restricted calls." + : "Toolyard Inbox asks you to decide on restricted calls."} ) : ( <> {presentation.description} - {status?.mode === "team" && presentation.phase === "revoked" ? ( + {presentation.phase === "not_configured" ? ( + + {status.administrator + ? "Open Server setup, check the Toolyard URL, then select Save and verify trust. T3 then signs in every user of this server automatically." + : "Ask an administrator of this server to set up Toolyard. T3 then signs you in automatically."} + + ) : null} + {problem ? {problem} : null} + {canReconnect ? ( - Select an available method under Connect your account to authorize access. A settings - save does not restore revoked access. + Select Reconnect to ask Toolyard again. Toolyard decides, so access it revoked stays + revoked. ) : null} @@ -600,6 +654,15 @@ function EnvironmentToolyardContent({ ) : null} + {canReconnect ? ( + void reconnect()} + /> + ) : null} {status === null || status.connection === "unavailable" ? ( setDraft({ ...current, baseUrl })} /> + + Server default: {defaultBaseUrl} + {status.defaultBaseUrlSource === "environment" + ? " (set by T3_TOOLYARD_URL)." + : ". Set T3_TOOLYARD_URL on the server to change it."} + Enable integration describe("personalMcp.connectToolyard", () => { it("derives the connect endpoint from the MCP URL's origin", () => { - expect(toolyardConnectUrl()).toBe("https://toolyard.dev.beknown.live/v1/connect/t3"); + expect(toolyardConnectUrl()).toBe("https://toolyard.beknown.live/v1/connect/t3"); expect(toolyardConnectUrl("https://toolyard.example/mcp")).toBe( "https://toolyard.example/v1/connect/t3", ); diff --git a/apps/server/src/mcp/UserMcpProfileStore.ts b/apps/server/src/mcp/UserMcpProfileStore.ts index 4e098472be599..a67ba53edaab9 100644 --- a/apps/server/src/mcp/UserMcpProfileStore.ts +++ b/apps/server/src/mcp/UserMcpProfileStore.ts @@ -35,8 +35,9 @@ import { makePerUserLock } from "./PerUserLock.ts"; import { managedToolyardIntegration, managedToolyardCredential, - managedToolyardBaseUrl, hasManagedToolyardRuntime, + managedToolyardMcpUrls, + managedToolyardOwnedMcpUrls, } from "../toolyard/ToolyardIntegration.ts"; const textEncoder = new TextEncoder(); @@ -109,7 +110,9 @@ export const builtInToolyardIntegration = (): PersonalMcpIntegration => ({ export const isLegacyToolyardIntegration = (integration: { readonly url: string; readonly authMode: string; -}): boolean => integration.authMode === "x-bf-vk" && isToolyardGatewayUrl(integration.url); +}): boolean => + integration.authMode === "x-bf-vk" && + isToolyardGatewayUrl(integration.url, managedToolyardMcpUrls()); /** * Pins what a client may not change. The built-in `toolyard` integration keeps @@ -207,7 +210,7 @@ const validateIntegration = (integration: PersonalMcpProfileUpdate["integrations if ( hasManagedToolyardRuntime() && integration.id !== TOOLYARD_MCP_INTEGRATION_ID && - (isToolyardGatewayUrl(integration.url) || integration.url === `${managedToolyardBaseUrl()}/mcp`) + isToolyardGatewayUrl(integration.url, managedToolyardOwnedMcpUrls()) ) { throw new Error( "Toolyard uses the environment's server-owned connection. Remove the manual Toolyard integration.", @@ -342,8 +345,7 @@ export const layer = Layer.effect( ...presentIntegrations(stored.integrations).filter( (entry) => entry.id !== TOOLYARD_MCP_INTEGRATION_ID && - !isToolyardGatewayUrl(entry.url) && - entry.url !== `${managedToolyardBaseUrl()}/mcp`, + !isToolyardGatewayUrl(entry.url, managedToolyardOwnedMcpUrls()), ), ], ), diff --git a/apps/server/src/toolyard/ToolyardConnectionCore.test.ts b/apps/server/src/toolyard/ToolyardConnectionCore.test.ts index ffbbe7ff2dee9..3a167d4e2f05b 100644 --- a/apps/server/src/toolyard/ToolyardConnectionCore.test.ts +++ b/apps/server/src/toolyard/ToolyardConnectionCore.test.ts @@ -3,10 +3,18 @@ import { describe, it, expect } from "@effect/vitest"; import * as NodeCrypto from "node:crypto"; import * as DateTime from "effect/DateTime"; -import { ToolyardConnectionCore, canonicalToolyardUrl } from "./ToolyardConnectionCore.ts"; +import { + ToolyardConnectionCore, + canonicalToolyardUrl, + type CoreOptions, +} from "./ToolyardConnectionCore.ts"; import { toolyardManagedProfile } from "./ToolyardManagedProfile.ts"; -function fixture(environmentId = "environment-one", storage = { value: null as string | null }) { +function fixture( + environmentId = "environment-one", + storage = { value: null as string | null }, + options: Partial = {}, +) { let now = DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-04T00:00:00Z")); let connects = 0; let failNextWrite = false; @@ -124,6 +132,7 @@ function fixture(environmentId = "environment-one", storage = { value: null as s if (id === "user_blocked") throw new Error("blocked"); return { email: `${id}@beknown.work`, admin: id === "user_admin" }; }, + ...options, }); const configure = (expectedRevision = 0, extras = {}) => core.configure("user_admin", { @@ -656,3 +665,127 @@ describe("server-owned Toolyard federation", () => { }); }); }); + +describe("seamless team sign-in", () => { + const teamReconnect = (core: ToolyardConnectionCore, userId: string, expectedRevision: number) => + core.configure(userId, { + expectedRevision, + baseUrl: "", + origin: "", + enabled: true, + mode: "team", + reconnect: true, + }); + + it("offers the server default and uses it, or the saved instance, for an empty base URL", async () => { + const builtIn = fixture(); + await builtIn.core.initialize(); + expect(await builtIn.core.status("user_admin")).toMatchObject({ + baseUrl: null, + defaultBaseUrl: "https://toolyard.beknown.live", + defaultBaseUrlSource: "built-in", + }); + const f = fixture( + "environment-one", + { value: null }, + { + defaultBaseUrl: "https://toolyard.test", + defaultBaseUrlSource: "environment", + }, + ); + await f.core.initialize(); + expect(await f.core.status("user_admin")).toMatchObject({ + defaultBaseUrl: "https://toolyard.test", + defaultBaseUrlSource: "environment", + }); + await f.configure(0, { baseUrl: "" }); + expect(f.core.baseUrl()).toBe("https://toolyard.test"); + const generation = f.core.binding()?.trustGeneration; + // A later save without a URL keeps the saved instance and its trust. + await f.configure(1, { baseUrl: " " }); + expect(f.core.baseUrl()).toBe("https://toolyard.test"); + expect(f.core.binding()?.trustGeneration).toBe(generation); + }); + + it("reconnects every team user after an administrator disables and re-enables the instance", async () => { + const f = fixture(); + await f.core.initialize(); + await f.configure(); + expect((await f.core.status("user_a")).connection).toBe("connected"); + const revoked = await f.core.credential("user_b"); + expect(await f.core.retire("user_b", revoked!.token!)).toBe(true); + await f.configure(1, { enabled: false }); + expect((await f.core.status("user_a")).connection).toBe("disabled"); + await f.configure(2); + // Toolyard marks the environment's connections reconnectable on re-registration. + expect(await f.core.status("user_a")).toMatchObject({ + connection: "connected", + connectionError: null, + }); + // An access T3 retired stays retired; only its owner asks again. + expect((await f.core.status("user_b")).connection).toBe("revoked"); + }); + + it("lets a team user reconnect their own retired connection while Toolyard decides", async () => { + const f = fixture(); + await f.core.initialize(); + await f.configure(); + const first = await f.core.credential("user_a"); + expect(await f.core.retire("user_a", first!.token!)).toBe(true); + expect(await f.core.status("user_a")).toMatchObject({ + connection: "revoked", + connectionError: "credential_rejected", + }); + const connects = f.connects; + const reconnected = await teamReconnect(f.core, "user_a", 1); + expect(reconnected).toMatchObject({ connection: "connected", connectionError: null }); + expect(f.connects).toBe(connects + 1); + // Toolyard still holds the same credential, so nothing rotated. + expect((await f.core.credential("user_a"))?.token).toBe(first!.token); + // The server settings and trust stay as they were. + expect(f.core.binding()?.trustGeneration).toBe(1); + expect((await f.core.status("user_admin")).revision).toBe(1); + + expect(await f.core.retire("user_a", first!.token!)).toBe(true); + f.setRevoked(); + expect(await teamReconnect(f.core, "user_a", 1)).toMatchObject({ + connection: "revoked", + connectionError: "connection_revoked", + }); + await expect(teamReconnect(f.core, "user_a", 0)).rejects.toMatchObject({ + code: "settings_revision_conflict", + }); + await expect(teamReconnect(f.core, "local-user", 1)).rejects.toMatchObject({ + code: "team_identity_required", + }); + }); + + it("refuses a team reconnect while the instance is disabled", async () => { + const f = fixture(); + await f.core.initialize(); + await f.configure(); + await f.configure(1, { enabled: false }); + await expect(teamReconnect(f.core, "user_a", 2)).rejects.toMatchObject({ + code: "integration_disabled", + }); + }); + + it("recovers a team connection after an outage in the background, without a status read", async () => { + const f = fixture(); + await f.core.initialize(); + await f.configure(); + f.setOutage(true); + expect(await f.core.credential("user_a")).toBeNull(); + expect(await f.core.status("user_a", false)).toMatchObject({ + connection: "unavailable", + connectionError: "instance_unavailable", + }); + f.advance(31_000); + f.setOutage(false); + await f.core.reconcileCredentials(); + expect(await f.core.status("user_a", false)).toMatchObject({ + connection: "connected", + connectionError: null, + }); + }); +}); diff --git a/apps/server/src/toolyard/ToolyardConnectionCore.ts b/apps/server/src/toolyard/ToolyardConnectionCore.ts index f267f3c37e29d..20c4fecc81419 100644 --- a/apps/server/src/toolyard/ToolyardConnectionCore.ts +++ b/apps/server/src/toolyard/ToolyardConnectionCore.ts @@ -2,8 +2,10 @@ /** T3-CUSTOM(expbkt3): Environment/instance/user-isolated, server-owned federation. */ import * as NodeCrypto from "node:crypto"; import * as NodeOS from "node:os"; +import { DEFAULT_TOOLYARD_BASE_URL } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DateTime from "effect/DateTime"; +import type { ToolyardDefaultUrlSource } from "./toolyardDefaultUrl.ts"; const REQUIRED_INSTANCE_CAPABILITIES = [ "inbox.batch.v1", @@ -33,6 +35,8 @@ interface Connection { version: number; state: ConnectionState; retryAfter?: number; + /** Toolyard's code for the last failed attempt; cleared by the next success. Never a secret. */ + lastError?: string; } interface PendingHostConnection { requestId: string; @@ -81,6 +85,9 @@ export interface CoreOptions { now?: () => number; hostName?: string; platform?: string; + /** The instance offered before an administrator saves one (`T3_TOOLYARD_URL` or the built-in). */ + defaultBaseUrl?: string; + defaultBaseUrlSource?: ToolyardDefaultUrlSource; } const digest = (value: string) => NodeCrypto.createHash("sha256").update(value).digest("hex"); export function canonicalToolyardUrl(value: string): string { @@ -235,6 +242,15 @@ export class ToolyardConnectionCore { baseUrl() { return this.state.settings.baseUrl; } + defaultBaseUrl() { + return this.options.defaultBaseUrl ?? DEFAULT_TOOLYARD_BASE_URL; + } + /** An empty base URL on save means the saved instance, or else the server default. */ + private requestedBaseUrl(value: string) { + if (value.trim() !== "") return value; + const settings = this.state.settings; + return settings.baseUrl && !settings.removed ? settings.baseUrl : this.defaultBaseUrl(); + } binding() { const settings = this.state.settings; return settings.enabled && !settings.removed && settings.instanceId && settings.origin @@ -347,10 +363,13 @@ export class ToolyardConnectionCore { apiKey?: string | undefined; disconnect?: boolean | undefined; hostAction?: "begin" | "poll" | "cancel" | undefined; + reconnect?: boolean | undefined; }, ) { const user = await this.options.verifyUser(userId); if (input.disconnect) return this.disconnect(userId, input.expectedRevision); + if (input.reconnect) return this.reconnectTeam(userId, input.expectedRevision); + input = { ...input, baseUrl: this.requestedBaseUrl(input.baseUrl) }; if (input.mode === "host" && input.enabled && !input.remove) return this.configureHost(userId, input, user.admin); if (input.mode === "team" && !input.remove && input.enabled) { @@ -399,10 +418,14 @@ export class ToolyardConnectionCore { await this.persistSettingsChange((candidate) => { if (old.enabled) this.advanceTrustGeneration(candidate); candidate.settings = { ...old, enabled: false, revision: old.revision + 1 }; + // A user's own revoked access stays revoked; re-enabling reopens only "disabled". candidate.connections = Object.fromEntries( Object.entries(this.state.connections).map(([key, connection]) => [ key, - this.connectionTombstone(connection, "disabled"), + this.connectionTombstone( + connection, + connection.state === "revoked" ? "revoked" : "disabled", + ), ]), ); if (old.enabled) this.enqueueRevocation(old, userId, candidate); @@ -475,6 +498,9 @@ export class ToolyardConnectionCore { if (changed || old.enabled !== input.enabled) this.advanceTrustGeneration(candidate); // Never transmit old credentials to a replacement URL or trust binding. if (changed || !input.enabled) candidate.connections = {}; + // Re-registering a disabled instance reopens team access: Toolyard marks the + // environment's connections reconnectable, so T3 asks again for each team user. + else if (!old.enabled) candidate.connections = this.reopenTeamConnections(candidate); candidate.settings = { revision: old.revision + 1, enabled: input.enabled, @@ -928,6 +954,63 @@ export class ToolyardConnectionCore { : {}), }; } + private reopenTeamConnections(state: Persisted): Record { + return Object.fromEntries( + Object.entries(state.connections).map(([key, connection]) => [ + key, + (connection.mode ?? "team") === "team" && connection.state === "disabled" + ? { ...this.connectionTombstone(connection, "disabled"), state: "unavailable" as const } + : connection, + ]), + ); + } + /** + * The user's own request to use their team connection again after T3 stopped + * using it (a rejected credential, a refusal, an outage). T3 asks Toolyard once + * more; Toolyard alone decides, so access it revoked stays revoked. + */ + private async reconnectTeam(userId: string, expectedRevision: number) { + if (!userId.startsWith("user_")) + throw new ToolyardIntegrationFailure("team_identity_required", 403); + await this.serialized(async () => { + const settings = this.state.settings; + if (expectedRevision !== settings.revision) + throw new ToolyardIntegrationFailure("settings_revision_conflict", 409); + if (!settings.enabled || settings.removed || !settings.baseUrl || !settings.instanceId) + throw new ToolyardIntegrationFailure("integration_disabled", 403); + if (settings.origin === settings.baseUrl) + throw new ToolyardIntegrationFailure("team_connection_unavailable", 409); + const key = this.key(userId); + const prior = this.state.connections[key]; + if (prior?.mode !== undefined && prior.mode !== "team") + throw new ToolyardIntegrationFailure("disconnect_before_mode_change", 409); + if (this.state.pendingConnections[key]?.status === "pending") + throw new ToolyardIntegrationFailure("cancel_host_request_before_mode_change", 409); + if (!prior || (prior.state === "connected" && prior.token)) return; + // A revocation still queued for this user would end the new connection. + const blocks = (job: Persisted["pendingRevocations"][number]) => + job.userId === userId && job.settings.instanceId === settings.instanceId; + if (this.state.pendingRevocations.some(blocks)) { + await this.flushRevocationsUnlocked(); + if (this.state.pendingRevocations.some(blocks)) + throw new ToolyardIntegrationFailure("revocation_cleanup_pending", 409); + } + // Keep the credential version: Toolyard compares it before it issues or reuses a token. + await this.persistSettingsChange((candidate) => { + candidate.connections = { + ...candidate.connections, + [key]: { + ...this.connectionTombstone(prior, "revoked"), + mode: "team", + userId, + state: "unavailable", + }, + }; + }); + }); + await this.credential(userId); + return this.status(userId, false); + } private async disconnect(userId: string, expectedRevision: number) { return this.serialized(async () => { if (expectedRevision !== this.state.settings.revision) @@ -1054,8 +1137,16 @@ export class ToolyardConnectionCore { return this.serialized(() => this.flushRevocationsUnlocked()); } async reconcileCredentials() { + // Team connections lost to an outage hold no token; retry them too so users + // recover without opening Settings or starting a session. const userIds = Object.values(this.state.connections) - .filter((c) => c.token && c.userId && c.state !== "revoked" && c.state !== "disabled") + .filter( + (c) => + c.userId && + c.state !== "revoked" && + c.state !== "disabled" && + (c.token || (c.state === "unavailable" && (c.mode ?? "team") === "team")), + ) .map((c) => c.userId!); for (const userId of userIds) { try { @@ -1176,6 +1267,7 @@ export class ToolyardConnectionCore { version: prior?.version ?? 0, state, retryAfter: this.now + 30_000, + lastError: failure.code, }, }; }); @@ -1198,7 +1290,11 @@ export class ToolyardConnectionCore { await this.persistSettingsChange((candidate) => { candidate.connections = { ...candidate.connections, - [key]: { ...this.connectionTombstone(prior, "revoked"), userId }, + [key]: { + ...this.connectionTombstone(prior, "revoked"), + userId, + lastError: "credential_rejected", + }, }; }); return true; @@ -1224,8 +1320,11 @@ export class ToolyardConnectionCore { callbackTransport: this.connectionMode(userId) !== "team" ? ("pull" as const) : ("push" as const), connection: connection?.state ?? ("not_connected" as const), + connectionError: connection?.lastError ?? null, email: connection?.email ?? null, expiresAt: connection?.expiresAt ?? null, + defaultBaseUrl: this.defaultBaseUrl(), + defaultBaseUrlSource: this.options.defaultBaseUrlSource ?? ("built-in" as const), }; } async handoff(userId: string) { diff --git a/apps/server/src/toolyard/ToolyardIntegration.test.ts b/apps/server/src/toolyard/ToolyardIntegration.test.ts index a870a49261eb8..26b8a5b0ec7fc 100644 --- a/apps/server/src/toolyard/ToolyardIntegration.test.ts +++ b/apps/server/src/toolyard/ToolyardIntegration.test.ts @@ -1,5 +1,6 @@ /** T3-CUSTOM(expbkt3): Callback history is bounded, typed, and excludes credentials/results. */ import { expect, it } from "@effect/vitest"; +import * as ConfigProvider from "effect/ConfigProvider"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as Layer from "effect/Layer"; @@ -121,6 +122,38 @@ it.effect("permits the authenticated local profile only when Clerk team mode is ).toBe("Failure"); }).pipe(Effect.provide(integrationTestLayer(false))), ); +const defaultUrlCases: ReadonlyArray<{ + readonly env: Record; + readonly url: string; + readonly source: "environment" | "built-in"; +}> = [ + { env: {}, url: "https://toolyard.beknown.live", source: "built-in" }, + { + env: { T3_TOOLYARD_URL: "https://toolyard.example.test/mcp" }, + url: "https://toolyard.example.test", + source: "environment", + }, + { + env: { T3_TOOLYARD_URL: "http://insecure.example.test" }, + url: "https://toolyard.beknown.live", + source: "built-in", + }, +]; +it.effect.each(defaultUrlCases)( + "offers the default Toolyard URL before an administrator saves one ($url, $source)", + ({ env, url, source }) => + Effect.gen(function* () { + const service = yield* ToolyardIntegration; + expect(yield* service.status(UserId.make("local-user"))).toMatchObject({ + baseUrl: null, + defaultBaseUrl: url, + defaultBaseUrlSource: source, + }); + }).pipe( + Effect.provide(integrationTestLayer(false)), + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))), + ), +); it.effect("never converts an anonymous team transport into the local owner", () => Effect.gen(function* () { const service = yield* ToolyardIntegration; diff --git a/apps/server/src/toolyard/ToolyardIntegration.ts b/apps/server/src/toolyard/ToolyardIntegration.ts index 3138a8c838954..cb20bc6defc6e 100644 --- a/apps/server/src/toolyard/ToolyardIntegration.ts +++ b/apps/server/src/toolyard/ToolyardIntegration.ts @@ -1,11 +1,13 @@ /** T3-CUSTOM(expbkt3): Server-owned Toolyard trust and credentials. No browser token renewal. */ import { EnvironmentUserId, + LEGACY_TOOLYARD_MCP_URLS, PersonalMcpSettingsError, UserId, type PersonalMcpIntegration, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -18,6 +20,11 @@ import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; import { EnvironmentUserRepository } from "../persistence/EnvironmentUsers.ts"; import { toolyardManagedProfile } from "./ToolyardManagedProfile.ts"; import { ToolyardConnectionCore, ToolyardIntegrationFailure } from "./ToolyardConnectionCore.ts"; +import { + resolveToolyardDefaultUrl, + TOOLYARD_URL_ENV, + toolyardMcpUrlCandidates, +} from "./toolyardDefaultUrl.ts"; export type ToolyardStatus = Awaited>; export type ToolyardConfigureInput = Parameters[1]; @@ -162,9 +169,24 @@ export const toolyardIntegrationLayer = Layer.effect( const environmentId = yield* environment.getEnvironmentId; const secretName = `toolyard-federation-${environmentId}`; const platform = yield* HostProcess.Platform; + const defaultUrl = resolveToolyardDefaultUrl( + Option.getOrUndefined( + yield* Config.String(TOOLYARD_URL_ENV).pipe( + Config.option, + Effect.orElseSucceed(() => Option.none()), + ), + ), + ); + if (defaultUrl.rejected !== undefined) + yield* Effect.logWarning( + `${TOOLYARD_URL_ENV} must be an https origin; using the built-in Toolyard URL`, + { value: defaultUrl.rejected, url: defaultUrl.url }, + ); const core = new ToolyardConnectionCore({ environmentId, platform, + defaultBaseUrl: defaultUrl.url, + defaultBaseUrlSource: defaultUrl.source, read: () => Effect.runPromise(secrets.get(secretName)).then((value) => Option.isSome(value) ? new TextDecoder().decode(value.value) : null, @@ -301,4 +323,19 @@ export const managedToolyardCredentialForUrl = (userId: UserId, url: string) => ) : Effect.succeed(undefined); -export const managedToolyardBaseUrl = () => activeCore?.baseUrl() ?? null; +/** + * Every MCP endpoint this server treats as Toolyard's: the saved instance, the + * server default and the endpoints every build recognises. Used where being + * broad is the safe side (never re-point a Toolyard key, tag Toolyard calls). + */ +export const managedToolyardMcpUrls = () => + toolyardMcpUrlCandidates([activeCore?.baseUrl(), activeCore?.defaultBaseUrl()]); + +/** + * The endpoints the server-owned connection stands in for: the saved instance + * and earlier builds' built-in endpoint. A manual integration at one of them is + * hidden and refused; a manual entry at another Toolyard instance stays the + * user's own. + */ +export const managedToolyardOwnedMcpUrls = () => + toolyardMcpUrlCandidates([activeCore?.baseUrl()], LEGACY_TOOLYARD_MCP_URLS); diff --git a/apps/server/src/toolyard/toolyardDefaultUrl.test.ts b/apps/server/src/toolyard/toolyardDefaultUrl.test.ts new file mode 100644 index 0000000000000..e0696226f81d2 --- /dev/null +++ b/apps/server/src/toolyard/toolyardDefaultUrl.test.ts @@ -0,0 +1,65 @@ +/** T3-CUSTOM(expbkt3): The Toolyard default URL and the endpoints the server treats as Toolyard's. */ +import { describe, expect, it } from "@effect/vitest"; +import { isToolyardGatewayUrl } from "@t3tools/contracts"; +import { + resolveToolyardDefaultUrl, + toolyardMcpUrlCandidates, + toolyardOriginFromConfig, +} from "./toolyardDefaultUrl.ts"; + +describe("toolyard default URL", () => { + it("uses the production instance when the environment names none", () => { + for (const raw of [undefined, "", " "]) + expect(resolveToolyardDefaultUrl(raw)).toEqual({ + url: "https://toolyard.beknown.live", + source: "built-in", + }); + }); + + it("accepts an https origin, with or without the /mcp endpoint", () => { + for (const raw of [ + "https://toolyard.dev.beknown.live", + "https://toolyard.dev.beknown.live/", + " https://toolyard.dev.beknown.live/mcp ", + "https://TOOLYARD.dev.beknown.live/MCP/", + ]) + expect(resolveToolyardDefaultUrl(raw)).toEqual({ + url: "https://toolyard.dev.beknown.live", + source: "environment", + }); + }); + + it("falls back to the built-in URL for a value the server cannot use", () => { + for (const raw of [ + "http://toolyard.test", + "https://user:pass@toolyard.test", + "https://toolyard.test/other", + "https://toolyard.test/?x=1", + "not a url", + ]) { + expect(toolyardOriginFromConfig(raw)).toBeNull(); + expect(resolveToolyardDefaultUrl(raw)).toEqual({ + url: "https://toolyard.beknown.live", + source: "built-in", + rejected: raw.trim(), + }); + } + }); + + it("treats the configured, default and earlier endpoints as Toolyard's, and nothing else", () => { + const urls = toolyardMcpUrlCandidates(["https://toolyard.example.test", null, undefined]); + for (const url of [ + "https://toolyard.example.test/mcp", + "https://toolyard.beknown.live/mcp/", + "https://toolyard.dev.beknown.live/mcp", + ]) + expect(isToolyardGatewayUrl(url, urls)).toBe(true); + for (const url of [ + "https://toolyard.example.test.evil.com/mcp", + "https://evil.com/mcp?host=toolyard.beknown.live", + "https://toolyard.example.test/other", + ]) + expect(isToolyardGatewayUrl(url, urls)).toBe(false); + expect(new Set(urls).size).toBe(urls.length); + }); +}); diff --git a/apps/server/src/toolyard/toolyardDefaultUrl.ts b/apps/server/src/toolyard/toolyardDefaultUrl.ts new file mode 100644 index 0000000000000..25566fee24068 --- /dev/null +++ b/apps/server/src/toolyard/toolyardDefaultUrl.ts @@ -0,0 +1,77 @@ +/** + * T3-CUSTOM(expbkt3): The Toolyard instance a server offers when an + * administrator has not saved one. + * + * Precedence, highest first: + * 1. The instance an administrator saved and verified (persisted with the + * server trust; changing it needs a new trust registration). + * 2. `T3_TOOLYARD_URL` in the server environment. + * 3. `DEFAULT_TOOLYARD_BASE_URL` (https://toolyard.beknown.live). + * + * The default only pre-fills setup and answers an empty base URL on save; it + * never connects anyone by itself, because registering trust still needs an + * administrator. + */ +import { DEFAULT_TOOLYARD_BASE_URL, KNOWN_TOOLYARD_MCP_URLS } from "@t3tools/contracts"; + +export const TOOLYARD_URL_ENV = "T3_TOOLYARD_URL"; + +export type ToolyardDefaultUrlSource = "environment" | "built-in"; + +export interface ToolyardDefaultUrl { + /** An https origin, no path. */ + readonly url: string; + readonly source: ToolyardDefaultUrlSource; + /** The environment named a value this server cannot use; `url` is the built-in default. */ + readonly rejected?: string; +} + +/** + * The https origin of an operator-supplied Toolyard URL. A trailing `/mcp` + * (the endpoint people copy) and trailing slashes are accepted; anything else + * beyond the origin is refused. + */ +export function toolyardOriginFromConfig(value: string): string | null { + let url: URL; + try { + url = new URL(value.trim()); + } catch { + return null; + } + const path = url.pathname.replace(/\/+$/, ""); + if ( + url.protocol !== "https:" || + url.username || + url.password || + url.search || + url.hash || + (path !== "" && path.toLowerCase() !== "/mcp") + ) + return null; + return url.origin; +} + +export function resolveToolyardDefaultUrl(raw: string | undefined): ToolyardDefaultUrl { + const trimmed = raw?.trim() ?? ""; + if (trimmed === "") return { url: DEFAULT_TOOLYARD_BASE_URL, source: "built-in" }; + const origin = toolyardOriginFromConfig(trimmed); + return origin === null + ? { url: DEFAULT_TOOLYARD_BASE_URL, source: "built-in", rejected: trimmed } + : { url: origin, source: "environment" }; +} + +/** + * The MCP endpoints of the given instance origins plus `known` endpoints + * (by default every endpoint a client recognises, earlier builds' included). + */ +export function toolyardMcpUrlCandidates( + origins: ReadonlyArray, + known: ReadonlyArray = KNOWN_TOOLYARD_MCP_URLS, +): ReadonlyArray { + return [ + ...new Set([ + ...origins.filter((origin): origin is string => !!origin).map((origin) => `${origin}/mcp`), + ...known, + ]), + ]; +} diff --git a/apps/web/src/components/settings/ToolyardSettingsSection.browser.test.tsx b/apps/web/src/components/settings/ToolyardSettingsSection.browser.test.tsx index a2c1d29de5c2c..2d4793c1609e8 100644 --- a/apps/web/src/components/settings/ToolyardSettingsSection.browser.test.tsx +++ b/apps/web/src/components/settings/ToolyardSettingsSection.browser.test.tsx @@ -32,8 +32,11 @@ const mocks = vi.hoisted(() => ({ origin: null as string | null, administrator: true, connection: "not_connected", + connectionError: null as string | null, email: null as string | null, expiresAt: null as string | null, + defaultBaseUrl: undefined as string | undefined, + defaultBaseUrlSource: undefined as "environment" | "built-in" | undefined, }, // The page origin the component compares a continuation against. A browser test cannot // change its real origin, so the continuation reader sees this one instead. @@ -379,8 +382,11 @@ function setup(): Disposable { baseUrl: null, removed: false, connection: "not_connected", + connectionError: null, email: null, expiresAt: null, + defaultBaseUrl: undefined, + defaultBaseUrlSource: undefined, }; mocks.userId = "user_admin"; mocks.clerkUserId = "user_admin"; @@ -428,7 +434,9 @@ async function mount(ui: ReactNode = ) { } async function edit() { await type("Toolyard base URL", "https://toolyard.test"); - await click(only('[data-testid="switch"]')); + // An unconfigured server starts enabled; the edit always ends with the integration on. + const toggle = only('[data-testid="switch"]'); + if (toggle.getAttribute("aria-checked") !== "true") await click(toggle); } return Object.assign(screen, { only, @@ -1096,19 +1104,61 @@ it("clears the consent instruction after a pending request becomes connected", a expect(view.text()).not.toContain("Review the account and host"); expect(view.button("Connect my Toolyard account")).toBeUndefined(); }); -it("does not offer an ineffective team reconnect through a settings save", async () => { +it("offers a team Reconnect instead of a settings save, and reports Toolyard's answer", async () => { using _setup = setup(); mocks.status = { ...mocks.status, mode: "team", + administrator: false, enabled: true, baseUrl: "https://toolyard.test", + origin: "https://stage.test", connection: "revoked", + connectionError: "credential_rejected", revision: 4, }; + mocks.configure.mockResolvedValue( + AsyncResult.success({ + ...mocks.status, + connection: "revoked", + connectionError: "connection_revoked", + }), + ); await using view = await mount(); expect(view.button("Save and verify trust")).toBeUndefined(); - expect(view.text()).toContain("A settings save does not restore revoked access"); + expect(view.text()).toContain("Toolyard rejected the stored credential"); expect(view.method("host")).toBeDefined(); expect(mocks.configure).not.toHaveBeenCalled(); + await click(view.button("Reconnect")); + expect(mocks.configure).toHaveBeenCalledOnce(); + expect(mocks.configure.mock.calls[0]![0].input).toMatchObject({ + reconnect: true, + mode: "team", + enabled: true, + expectedRevision: 4, + }); + expect(mocks.configure.mock.calls[0]![0].input).not.toHaveProperty("adminToken"); + expect(mocks.token).not.toHaveBeenCalled(); + expect(view.text()).toContain("Ask a Toolyard administrator to restore your access"); +}); +it("starts an unconfigured server from the server default and saves it in one step", async () => { + using _setup = setup(); + mocks.status = { + ...mocks.status, + defaultBaseUrl: "https://toolyard.example.test", + defaultBaseUrlSource: "environment", + }; + mocks.token.mockResolvedValue("fresh-browser-token"); + mocks.configure.mockResolvedValue(AsyncResult.success({ ...mocks.status, revision: 1 })); + await using view = await mount(); + expect(view.input("Toolyard base URL").value).toBe("https://toolyard.example.test"); + expect(view.text()).toContain("set by T3_TOOLYARD_URL"); + expect(view.text()).toContain("T3 then signs in every user of this server automatically"); + await click(view.button("Save and verify trust")); + expect(mocks.configure.mock.calls[0]![0].input).toMatchObject({ + baseUrl: "https://toolyard.example.test", + enabled: true, + mode: "team", + adminToken: "fresh-browser-token", + }); }); diff --git a/apps/web/src/components/settings/ToolyardSettingsSection.tsx b/apps/web/src/components/settings/ToolyardSettingsSection.tsx index 6ef3951ae4f33..ca12518a14076 100644 --- a/apps/web/src/components/settings/ToolyardSettingsSection.tsx +++ b/apps/web/src/components/settings/ToolyardSettingsSection.tsx @@ -1,7 +1,7 @@ /** T3-CUSTOM(expbkt3): Server-owned Toolyard connection and browser handoff. */ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; -import type { EnvironmentId } from "@t3tools/contracts"; +import { DEFAULT_TOOLYARD_BASE_URL, type EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import * as Option from "effect/Option"; import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -48,8 +48,11 @@ import { toolyardSettingsOrigin, } from "@t3tools/client-runtime/toolyard-trust-setup"; import { + canReconnectToolyardTeam, shortToolyardId, toolyardConnectionPresentation, + toolyardConnectionProblem, + toolyardInstanceHost, type ToolyardConnectionTone, } from "@t3tools/client-runtime/bk-toolyard-presentation"; import { @@ -239,9 +242,12 @@ function ToolyardSettingsContent({ target: "Toolyard identifier", }); const [copiedField, setCopiedField] = useState(null); + // The server names its default instance; an unconfigured server starts from it. + const defaultBaseUrl = status?.defaultBaseUrl ?? DEFAULT_TOOLYARD_BASE_URL; + const unconfigured = status !== null && (!status.baseUrl || status.removed); const current = draft ?? { - baseUrl: status?.baseUrl ?? "", - enabled: status?.enabled ?? false, + baseUrl: unconfigured ? defaultBaseUrl : (status?.baseUrl ?? ""), + enabled: unconfigured ? true : (status?.enabled ?? false), revision: status?.revision ?? 0, }; const mode = current.mode ?? status?.mode ?? "team"; @@ -250,6 +256,11 @@ function ToolyardSettingsContent({ status?.connection === "connected" && (status.mode === "api-key" || status.mode === "host" || modeChange); const view = toolyardConnectionPresentation(status); + const problem = toolyardConnectionProblem(status); + const canReconnect = mode === "team" && canReconnectToolyardTeam(status); + const instanceHost = toolyardInstanceHost(status?.baseUrl); + // An administrator can save the server default without editing the field first. + const setupReady = Boolean(status?.administrator && unconfigured && mode === "team"); const pendingRequest = status?.pendingConnection?.status === "pending" ? status.pendingConnection : null; const revisionConflict = draft !== null && status !== null && status.revision !== draft.revision; @@ -490,6 +501,41 @@ function ToolyardSettingsContent({ setBusy(false); }); }; + const reconnect = async () => { + if (!status) return; + setBusy(true); + setError(null); + setNotice(null); + try { + const saved = await configure({ + environmentId, + input: { + expectedRevision: status.revision, + baseUrl: status.baseUrl ?? "", + origin: status.origin ?? "", + enabled: true, + mode: "team", + reconnect: true, + }, + }); + refresh(); + if (AsyncResult.isSuccess(saved)) { + if (saved.value.connection === "connected") + setNotice( + saved.value.email ? `Reconnected as ${saved.value.email}.` : "Reconnected to Toolyard.", + ); + else + setError( + toolyardConnectionProblem(saved.value) ?? + "Toolyard did not restore the connection. Select Refresh, then try again.", + ); + } else if (AsyncResult.isFailure(saved)) + setError(toolyardSettingsFailureMessage(toolyardSettingsFailureCode(saved.cause))); + } catch { + setError("The reconnect request failed. Select Refresh, then try again."); + } + setBusy(false); + }; const cancelConsent = async () => { if (!status?.baseUrl) return; setBusy(true); @@ -566,6 +612,7 @@ function ToolyardSettingsContent({ status !== null && (draft !== null || apiKey !== "" || + setupReady || ((view.phase === "not_connected" || view.phase === "request_ended" || view.phase === "revoked") && @@ -581,6 +628,7 @@ function ToolyardSettingsContent({ ? "Save and connect" : "Save and verify trust"; const meta = [ + ...(instanceHost ? [`Toolyard ${instanceHost}`] : []), view.host ?? `${label} (host name not reported)`, view.method ?? "Method not reported", ...(view.connected @@ -749,13 +797,27 @@ function ToolyardSettingsContent({ {status ?

    {meta}

    : null}

    {view.connected - ? "Toolyard Inbox asks you to decide on restricted calls." + ? status?.mode === "team" + ? "T3 signed you in automatically with your account on this server. Toolyard Inbox asks you to decide on restricted calls." + : "Toolyard Inbox asks you to decide on restricted calls." : view.description}

    - {status?.mode === "team" && view.phase === "revoked" ? ( + {view.phase === "not_configured" ? (

    - Select an available connection method below to authorize access. A settings save does - not restore revoked access. + {status?.administrator + ? "Open Server setup, check the Toolyard URL, then select Save and verify trust. T3 then signs in every user of this server automatically." + : "Ask an administrator of this server to set up Toolyard. T3 then signs you in automatically."} +

    + ) : null} + {problem ? ( +

    + {problem} +

    + ) : null} + {canReconnect ? ( +

    + Select Reconnect to ask Toolyard again. Toolyard decides, so access it revoked stays + revoked.

    ) : null} {userScope === "local-user" ? ( @@ -852,6 +914,17 @@ function ToolyardSettingsContent({ ) : null} + {canReconnect ? ( + + ) : null} {retryable ? (