diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 05d965d95d067..c3f11b0d43558 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -38,6 +38,7 @@ import { SidebarChromeHeader } from "./sidebar/SidebarChrome"; import { MainAppLocationTracker } from "./sidebar/mainAppLocation"; import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop"; import { useProjects } from "../state/entities"; +import { ProfileAwareSidebar } from "../profileScope/ProfileAwareSidebar"; import { resolveInitialThreadSidebarWidth, resolveThreadSidebarMaximumWidth, @@ -316,16 +317,18 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { onResize: setSidebarWidth, }} > - {isOnSettings ? ( - <> - - - - ) : legacySidebarEnabled ? ( - - ) : ( - - )} + + {isOnSettings ? ( + <> + + + + ) : legacySidebarEnabled ? ( + + ) : ( + + )} + {children} diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 0a1a91c70e0ea..8cfb4a394f786 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -138,6 +138,9 @@ import { useThreadShells, } from "../state/entities"; import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server"; +import { intersectProjectKeys } from "@t3tools/client-runtime/state/profile-scope"; +import { ProfileSwitcher } from "../profileScope/ProfileSwitcher"; +import { useProfileScopedProjectKeys } from "../profileScope/useProfileScope"; import { vcsEnvironment } from "../state/vcs"; import { threadEnvironment } from "../state/threads"; import { useEnvironmentQuery } from "../state/query"; @@ -2350,10 +2353,24 @@ export default function Sidebar() { sidebarProjectSortOrder, ], ); - const projectGroups = useMemo( + const allProjectGroups = useMemo( () => sortLogicalProjectsForSidebar(unsortedProjectGroups, threads, sidebarProjectSortOrder), [sidebarProjectSortOrder, threads, unsortedProjectGroups], ); + // Fork (profiles): the active provider profile narrows everything below to its projects; + // null shows all. + const profileProjectKeys = useProfileScopedProjectKeys(); + const projectGroups = useMemo( + () => + profileProjectKeys === null + ? allProjectGroups + : allProjectGroups.filter((group) => + group.memberProjectRefs.some((ref) => + profileProjectKeys.has(`${ref.environmentId}:${ref.projectId}`), + ), + ), + [allProjectGroups, profileProjectKeys], + ); const projectGroupsRef = useRef(projectGroups); projectGroupsRef.current = projectGroups; const serverConfigs = useAtomValue(environmentServerConfigsAtom); @@ -2461,14 +2478,19 @@ export default function Sidebar() { ); const scopedProjectKeys = useMemo( () => - scopedProjectGroup === null - ? null - : new Set( - scopedProjectGroup.memberProjectRefs.map( - (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, + // Fork (profiles): a project group can span environments whose members use different + // profiles, so a chosen project only keeps its members in the active profile. + intersectProjectKeys( + scopedProjectGroup === null + ? null + : new Set( + scopedProjectGroup.memberProjectRefs.map( + (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, + ), ), - ), - [scopedProjectGroup], + profileProjectKeys, + ), + [profileProjectKeys, scopedProjectGroup], ); // A persisted scope whose project is gone falls back to all projects, but // only after every catalog environment has a live project snapshot. Cached @@ -4451,6 +4473,8 @@ export default function Sidebar() { // Lifted above the stage backdrop, whose fade bleeds below the // header and would otherwise paint across the search row's outline. + {/* Fork (profiles) */} + { + const target = resolveThreadRouteTarget(params); + if (target === null) return null; + return target.kind === "server" + ? `thread:${scopedThreadKey(target.threadRef)}` + : `draft:${target.draftId}`; + }, + }); + const { activeDraftThread, activeThread } = useHandleNewThread(); + const thread = activeThread ?? activeDraftThread; + const projectKey = thread ? profileScopeProjectKey(thread.environmentId, thread.projectId) : null; + const { scope, setScope, projectProfiles } = useProfileScopeState(); + const followedRef = useRef(null); + useEffect(() => { + if (routeKey === null || projectKey === null) return; + const current = { routeKey, projectKey }; + const outcome = followNavigation({ + followed: followedRef.current, + current, + scope, + projectProfiles, + }); + // Until the project's snapshot lands its profile is unknown, not "none": try again then. + if (outcome.kind === "pending") return; + followedRef.current = current; + if (outcome.kind === "switch") setScope(outcome.scope); + }, [projectKey, projectProfiles, routeKey, scope, setScope]); + return null; +} + +/** Wraps the app sidebar's content with the profile shortcuts and the follow-the-project rule. */ +export function ProfileAwareSidebar({ children }: { children: ReactNode }) { + return ( + <> + + + {children} + + ); +} diff --git a/apps/web/src/profileScope/ProfileSwitcher.tsx b/apps/web/src/profileScope/ProfileSwitcher.tsx new file mode 100644 index 0000000000000..3055d6e0371c3 --- /dev/null +++ b/apps/web/src/profileScope/ProfileSwitcher.tsx @@ -0,0 +1,241 @@ +import { useAtomValue } from "@effect/atom-react"; +import { PROFILE_SCOPE_KEYBINDING_COMMANDS } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { ChevronsUpDownIcon, LayersIcon, PlusIcon } from "lucide-react"; +import { useEffect } from "react"; + +import { Badge } from "../components/ui/badge"; +import { + Menu, + MenuGroup, + MenuGroupLabel, + MenuItem, + MenuPopup, + MenuRadioGroup, + MenuRadioItem, + MenuSeparator, + MenuShortcut, + MenuTrigger, +} from "../components/ui/menu"; +import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../components/ui/sidebar"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../components/ui/tooltip"; +import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; +import { cn } from "../lib/utils"; +import { primaryServerKeybindingsAtom } from "../state/server"; +import { + profileMonogram, + profileScopeForId, + type ProfileScope, + type ProfileScopeProfile, +} from "@t3tools/client-runtime/state/profile-scope"; +import { useProfileAttentionCounts, useProfileScopeState } from "./useProfileScope"; + +interface ScopeOption { + readonly scope: ProfileScope; + readonly label: string; + readonly profile: ProfileScopeProfile | null; + readonly attention: number; +} + +/** + * The profile's color square with its initials. "All profiles" is a plain icon, like the nav rows + * beside it. The small square overhangs its 16px icon slot by 2px per side, so its center lines up + * with the icons of neighboring rows. + */ +function ProfileAvatar({ + option, + size, +}: { + option: Pick; + size: "sm" | "md"; +}) { + const boxClass = + size === "sm" ? "-mx-0.5 size-5 rounded-sm text-3xs" : "size-7 rounded-md text-xs"; + if (option.profile) { + return ( + + {profileMonogram(option.profile.name)} + + ); + } + if (option.scope === "unassigned") { + return ( + + ? + + ); + } + return ; +} + +function useScopeOptions() { + const state = useProfileScopeState(); + const attention = useProfileAttentionCounts(state.projectProfiles); + const options: ScopeOption[] = [ + { scope: "all", label: "All profiles", profile: null, attention: 0 }, + ...state.profiles.map((profile) => ({ + scope: profileScopeForId(profile.id), + label: profile.name, + profile, + attention: attention.get(profile.id) ?? 0, + })), + ...(state.hasUnassignedProjects + ? [ + { + scope: "unassigned" as const, + label: "Unassigned", + profile: null, + attention: attention.get(null) ?? 0, + }, + ] + : []), + ]; + const current = options.find((option) => option.scope === state.scope) ?? options[0]!; + // What the user is missing while looking at one profile: work waiting in the others. + const attentionElsewhere = + state.scope === "all" + ? 0 + : options.reduce( + (total, option) => (option.scope === state.scope ? total : total + option.attention), + 0, + ); + return { ...state, options, current, attentionElsewhere }; +} + +/** Runs the `profile.*` keybindings: index 0 shows every profile, 1-9 pick one in menu order. */ +export function ProfileScopeShortcuts() { + const { options, setScope, profiles } = useScopeOptions(); + const keybindings = useAtomValue(primaryServerKeybindingsAtom); + useEffect(() => { + if (profiles.length === 0) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.defaultPrevented) return; + const command = resolveShortcutCommand(event, keybindings); + const index = + command === null ? -1 : PROFILE_SCOPE_KEYBINDING_COMMANDS.indexOf(command as never); + const option = options[index]; + if (!option) return; + event.preventDefault(); + setScope(option.scope); + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [keybindings, options, profiles.length, setScope]); + return null; +} + +function ScopeShortcut({ index }: { index: number }) { + const keybindings = useAtomValue(primaryServerKeybindingsAtom); + const label = shortcutLabelForCommand( + keybindings, + PROFILE_SCOPE_KEYBINDING_COMMANDS[index] ?? null, + ); + return label ? {label} : null; +} + +function AttentionCount({ count }: { count: number }) { + if (count === 0) return null; + return ( + + {count} + + ); +} + +function ProfileScopeMenuPopup({ + options, + current, + onSelect, + side, +}: { + options: ReadonlyArray; + current: ScopeOption; + onSelect: (scope: ProfileScope) => void; + side: "bottom" | "right"; +}) { + const navigate = useNavigate(); + return ( + + + Profiles + onSelect(value)} + > + {options.map((option, index) => ( + + + + {option.label} + + + + + ))} + + + + void navigate({ to: "/settings/providers" })}> + + Add profile + + + ); +} + +/** Picks the company the sidebar shows: a row above the thread list. */ +export function ProfileSwitcher() { + const { options, current, setScope, profiles, attentionElsewhere } = useScopeOptions(); + if (profiles.length === 0) return null; + const elsewhereLabel = + attentionElsewhere > 0 ? `${attentionElsewhere} waiting in other profiles` : null; + + return ( + <> + + + + }> + + + {current.label} + + {elsewhereLabel ? ( + + + } + /> + {elsewhereLabel} + + ) : null} + + + + + + + {/* Separates what the profile scopes (below) from the control that picks it. */} +
+ + ); +} diff --git a/apps/web/src/profileScope/profileScope.logic.test.ts b/apps/web/src/profileScope/profileScope.logic.test.ts new file mode 100644 index 0000000000000..81f8aea85811c --- /dev/null +++ b/apps/web/src/profileScope/profileScope.logic.test.ts @@ -0,0 +1,82 @@ +import { EnvironmentId, ProjectId, ProviderProfileId, ThreadId, TurnId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + countAttentionByProfile, + threadNeedsAttention, + type AttentionThread, +} from "./profileScope.logic"; + +const environmentId = EnvironmentId.make("env-1"); +const acmeProject = ProjectId.make("project-acme"); +const looseProject = ProjectId.make("project-loose"); +const acme = ProviderProfileId.make("acme"); + +function thread(overrides: Partial = {}): AttentionThread { + return { + id: ThreadId.make("thread-1"), + environmentId, + projectId: acmeProject, + archivedAt: null, + settledOverride: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + interactionMode: "default", + session: null, + backgroundLiveness: null, + latestTurn: null, + ...overrides, + }; +} + +const completed = { + turnId: TurnId.make("turn-1"), + state: "completed", + requestedAt: "2026-09-01T10:00:00.000Z", + startedAt: "2026-09-01T10:00:00.000Z", + completedAt: "2026-09-01T10:05:00.000Z", + assistantMessageId: null, +} as const satisfies AttentionThread["latestTurn"]; + +describe("threadNeedsAttention", () => { + it("counts approvals, questions and unread completions, not idle or settled work", () => { + expect(threadNeedsAttention(thread({ hasPendingApprovals: true }), undefined)).toBe(true); + expect(threadNeedsAttention(thread({ hasPendingUserInput: true }), undefined)).toBe(true); + expect( + threadNeedsAttention(thread({ latestTurn: completed }), "2026-09-01T09:00:00.000Z"), + ).toBe(true); + // Seen after it finished, never visited, and settled threads wait on nobody. + expect( + threadNeedsAttention(thread({ latestTurn: completed }), "2026-09-01T11:00:00.000Z"), + ).toBe(false); + expect(threadNeedsAttention(thread({ latestTurn: completed }), undefined)).toBe(false); + expect( + threadNeedsAttention( + thread({ hasPendingApprovals: true, settledOverride: "settled" }), + undefined, + ), + ).toBe(false); + }); +}); + +describe("countAttentionByProfile", () => { + it("groups waiting threads by their project's profile, with null for no profile", () => { + const counts = countAttentionByProfile({ + threads: [ + thread({ id: ThreadId.make("a"), hasPendingApprovals: true }), + thread({ id: ThreadId.make("b"), hasPendingUserInput: true }), + thread({ id: ThreadId.make("c"), projectId: looseProject, hasPendingApprovals: true }), + thread({ id: ThreadId.make("d") }), + ], + projectProfiles: new Map([ + [`${environmentId}:${acmeProject}`, acme], + [`${environmentId}:${looseProject}`, null], + ]), + lastVisitedAtByThreadKey: {}, + threadKey: (entry) => `${entry.environmentId}:${entry.id}`, + }); + expect(counts.get(acme)).toBe(2); + expect(counts.get(null)).toBe(1); + }); +}); diff --git a/apps/web/src/profileScope/profileScope.logic.ts b/apps/web/src/profileScope/profileScope.logic.ts new file mode 100644 index 0000000000000..fce4f894493ee --- /dev/null +++ b/apps/web/src/profileScope/profileScope.logic.ts @@ -0,0 +1,56 @@ +import type { ProviderProfileId } from "@t3tools/contracts"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { profileScopeProjectKey } from "@t3tools/client-runtime/state/profile-scope"; + +import { hasUnseenCompletion, resolveSidebarThreadStatus } from "../components/Sidebar.logic"; + +/** The thread fields that decide whether it waits on the user and which profile it counts for. */ +export type AttentionThread = Pick< + EnvironmentThreadShell, + | "id" + | "environmentId" + | "projectId" + | "archivedAt" + | "settledOverride" + | "hasPendingApprovals" + | "hasPendingUserInput" + | "hasActionableProposedPlan" + | "interactionMode" + | "session" + | "backgroundLiveness" + | "latestTurn" +>; + +/** + * Whether a thread is waiting on the user: an approval, a question, a failure, or a completion + * they have not seen. Working threads do not count; they need no action yet. + */ +export function threadNeedsAttention( + thread: AttentionThread, + lastVisitedAt: string | undefined, +): boolean { + if (thread.archivedAt !== null || thread.settledOverride === "settled") return false; + const status = resolveSidebarThreadStatus(thread); + if (status === "approval" || status === "input" || status === "failed") return true; + return status === "ready" && hasUnseenCompletion({ ...thread, lastVisitedAt }); +} + +/** Threads waiting on the user, per profile id (null for projects without a profile). */ +export function countAttentionByProfile(input: { + readonly threads: ReadonlyArray; + readonly projectProfiles: ReadonlyMap; + readonly lastVisitedAtByThreadKey: Readonly>; + readonly threadKey: (thread: AttentionThread) => string; +}): ReadonlyMap { + const counts = new Map(); + for (const thread of input.threads) { + if (!threadNeedsAttention(thread, input.lastVisitedAtByThreadKey[input.threadKey(thread)])) { + continue; + } + const profileId = + input.projectProfiles.get(profileScopeProjectKey(thread.environmentId, thread.projectId)) ?? + null; + counts.set(profileId, (counts.get(profileId) ?? 0) + 1); + } + return counts; +} diff --git a/apps/web/src/profileScope/useProfileScope.ts b/apps/web/src/profileScope/useProfileScope.ts new file mode 100644 index 0000000000000..571792278c58b --- /dev/null +++ b/apps/web/src/profileScope/useProfileScope.ts @@ -0,0 +1,93 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; +import type { ProviderProfileId } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { useCallback, useMemo } from "react"; + +import { useLocalStorage } from "../hooks/useLocalStorage"; +import { useProjects, useThreadShells } from "../state/entities"; +import { usePrimaryEnvironmentId } from "../state/environments"; +import { environmentServerConfigsAtom } from "../state/server"; +import { useUiStateStore } from "../uiStateStore"; +import { + buildProjectProfileMap, + collectProfiles, + profileIdOfScope, + resolveProfileScope, + scopedProjectKeysForProfile, + type ProfileScope, + type ProfileScopeProfile, +} from "@t3tools/client-runtime/state/profile-scope"; +import { countAttentionByProfile } from "./profileScope.logic"; + +// Device-local like the project filter: each client picks the company it is looking at. +// v2 tags profile values (`profile:`); a v1 value could be a profile id equal to a special scope. +const PROFILE_SCOPE_STORAGE_KEY = "t3code:profile-scope:v2"; + +/** Profiles, each project's profile, and the scope the sidebar is showing. */ +export function useProfileScopeState() { + const projects = useProjects(); + const serverConfigs = useAtomValue(environmentServerConfigsAtom); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const settingsByEnvironment = useMemo( + () => new Map([...serverConfigs].map(([id, config]) => [id, config.settings] as const)), + [serverConfigs], + ); + const profiles = useMemo( + () => collectProfiles([...settingsByEnvironment], primaryEnvironmentId), + [primaryEnvironmentId, settingsByEnvironment], + ); + const projectProfiles = useMemo( + () => buildProjectProfileMap(projects, settingsByEnvironment), + [projects, settingsByEnvironment], + ); + const [storedScope, setStoredScope] = useLocalStorage( + PROFILE_SCOPE_STORAGE_KEY, + "all", + Schema.String, + ); + const hasUnassignedProjects = useMemo( + () => [...projectProfiles.values()].some((profileId) => profileId === null), + [projectProfiles], + ); + const scope = resolveProfileScope(storedScope, profiles, hasUnassignedProjects); + const setScope = useCallback((next: ProfileScope) => setStoredScope(next), [setStoredScope]); + const activeProfileId = profileIdOfScope(scope); + const activeProfile: ProfileScopeProfile | null = + profiles.find((profile) => profile.id === activeProfileId) ?? null; + return { + profiles, + projectProfiles, + scope, + setScope, + activeProfile, + hasUnassignedProjects, + }; +} + +/** Project keys the sidebar shows for the active profile, or null when it shows everything. */ +export function useProfileScopedProjectKeys(): ReadonlySet | null { + const { scope, projectProfiles } = useProfileScopeState(); + return useMemo( + () => scopedProjectKeysForProfile(scope, projectProfiles), + [projectProfiles, scope], + ); +} + +/** Threads waiting on the user per profile id; `null` counts projects without a profile. */ +export function useProfileAttentionCounts( + projectProfiles: ReadonlyMap, +): ReadonlyMap { + const threads = useThreadShells(); + const lastVisitedAtByThreadKey = useUiStateStore((store) => store.threadLastVisitedAtById); + return useMemo( + () => + countAttentionByProfile({ + threads, + projectProfiles, + lastVisitedAtByThreadKey, + threadKey: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + }), + [lastVisitedAtByThreadKey, projectProfiles, threads], + ); +} diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 4a19bac401b98..4390b712e85e3 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -125,6 +125,20 @@ On web and desktop, right-click a pull request link in a thread and choose same link to return to the branch PR, if one exists. The linked pull request participates in automatic settlement. +## Work across companies + +Once you have [provider profiles](./project-settings.md#provider-profiles), web and desktop show a +profile switcher at the top of the sidebar. Pick a profile to show only its projects' threads and +drafts, or **All profiles** to see everything. A number beside a profile counts its threads waiting +on you: approvals, questions, failures, and finished work you have not read. A dot on the switcher +means another profile has something waiting. `Cmd+Option+0` on macOS or `Ctrl+Alt+0` on Windows +and Linux shows all profiles, and `1` to `9` pick one in menu order; change them in +[Keybindings](./keybindings.md). **Unassigned** appears when some projects have no profile. + +The sidebar follows the thread you open. Opening a thread from another profile, from a +notification, search, or link, switches to that profile, and so does picking another project for a +new thread. Choosing a profile yourself while a thread is open keeps your choice. + ## Find and reference work On web and desktop, open the command palette with `Cmd/Ctrl+K` to search threads diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 28e52075ccc4a..e07bdd3249128 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -235,6 +235,10 @@ "types": "./src/state/threadSort.ts", "default": "./src/state/threadSort.ts" }, + "./state/profile-scope": { + "types": "./src/state/profileScope.ts", + "default": "./src/state/profileScope.ts" + }, "./state/thread-settled": { "types": "./src/state/threadSettled.ts", "default": "./src/state/threadSettled.ts" diff --git a/packages/client-runtime/src/state/profileScope.test.ts b/packages/client-runtime/src/state/profileScope.test.ts new file mode 100644 index 0000000000000..bdfbe20136a27 --- /dev/null +++ b/packages/client-runtime/src/state/profileScope.test.ts @@ -0,0 +1,236 @@ +import { + EnvironmentId, + ProjectId, + ProviderProfileId, + type ServerSettings, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + buildProjectProfileMap, + collectProfiles, + followNavigation, + intersectProjectKeys, + profileMonogram, + profileScopeForId, + resolveProfileScope, + resolveProjectProfileId, + scopedProjectKeysForProfile, + type ProfileNavigation, + type ProfileScope, +} from "./profileScope.ts"; + +const primary = EnvironmentId.make("env-primary"); +const remote = EnvironmentId.make("env-remote"); +const acme = ProviderProfileId.make("acme"); +const globex = ProviderProfileId.make("globex"); +const api = ProjectId.make("project-api"); +const web = ProjectId.make("project-web"); +const dotfiles = ProjectId.make("project-dotfiles"); + +type ProfileSettings = Pick< + ServerSettings, + "providerProfileId" | "providerProfiles" | "projectSettingsOverrides" +>; + +function settings(overrides: Partial = {}): ProfileSettings { + return { + providerProfileId: null, + providerProfiles: { + [acme]: { name: "Acme", color: "#2563eb", instanceIds: [], defaultModelSelection: null }, + [globex]: { name: "Globex", instanceIds: [], defaultModelSelection: null }, + }, + projectSettingsOverrides: {}, + ...overrides, + }; +} + +describe("resolveProjectProfileId", () => { + it("prefers the project's override, including an explicit no-profile", () => { + const base = settings({ + providerProfileId: acme, + projectSettingsOverrides: { + [api]: { providerProfileId: globex }, + [web]: { providerProfileId: null }, + }, + }); + expect(resolveProjectProfileId(base, api)).toBe(globex); + expect(resolveProjectProfileId(base, web)).toBeNull(); + expect(resolveProjectProfileId(base, dotfiles)).toBe(acme); + }); + + it("treats a deleted profile as no profile", () => { + const base = settings({ + projectSettingsOverrides: { [api]: { providerProfileId: ProviderProfileId.make("gone") } }, + }); + expect(resolveProjectProfileId(base, api)).toBeNull(); + }); +}); + +describe("collectProfiles", () => { + it("merges profiles by id, named by the primary environment, sorted by name", () => { + const renamed = settings(); + const remoteSettings: Pick = { + providerProfiles: { + [acme]: { name: "Acme (old name)", instanceIds: [], defaultModelSelection: null }, + [ProviderProfileId.make("initech")]: { + name: "Initech", + instanceIds: [], + defaultModelSelection: null, + }, + }, + }; + const profiles = collectProfiles( + [ + [remote, remoteSettings], + [primary, renamed], + ], + primary, + ); + expect(profiles.map((profile) => profile.name)).toEqual(["Acme", "Globex", "Initech"]); + expect(profiles[0]?.color).toBe("#2563eb"); + expect(profiles[1]?.color).toBeNull(); + }); +}); + +describe("profile scopes", () => { + const projectProfiles = buildProjectProfileMap( + [ + { environmentId: primary, id: api }, + { environmentId: primary, id: dotfiles }, + { environmentId: remote, id: web }, + ], + new Map([ + [primary, settings({ projectSettingsOverrides: { [api]: { providerProfileId: acme } } })], + [remote, settings({ providerProfileId: acme })], + ]), + ); + + it("filters projects to a profile, to the unassigned bucket, or not at all", () => { + expect(scopedProjectKeysForProfile("all", projectProfiles)).toBeNull(); + expect([ + ...(scopedProjectKeysForProfile(profileScopeForId(acme), projectProfiles) ?? []), + ]).toEqual([`${primary}:${api}`, `${remote}:${web}`]); + expect([...(scopedProjectKeysForProfile("unassigned", projectProfiles) ?? [])]).toEqual([ + `${primary}:${dotfiles}`, + ]); + }); + + it("falls back to every project while a stored profile is not defined anywhere", () => { + const profiles = collectProfiles([[primary, settings()]], primary); + expect(resolveProfileScope("profile:acme", profiles, true)).toBe("profile:acme"); + expect(resolveProfileScope("profile:initech", profiles, true)).toBe("all"); + expect(resolveProfileScope("profile:acme", [], true)).toBe("all"); + // A bare id, as stored before profile values were tagged, is not a profile choice. + expect(resolveProfileScope("acme", profiles, true)).toBe("all"); + }); + + it("shows everything once the last unassigned project gets a profile, keeping the choice", () => { + const profiles = collectProfiles([[primary, settings()]], primary); + expect(resolveProfileScope("unassigned", profiles, true)).toBe("unassigned"); + expect(resolveProfileScope("unassigned", profiles, false)).toBe("all"); + }); + + it("keeps profiles named All and Unassigned apart from the special scopes", () => { + const named = ProviderProfileId.make("all"); + const unassignedNamed = ProviderProfileId.make("unassigned"); + const namedSettings = settings({ + providerProfiles: { + [named]: { name: "All", instanceIds: [], defaultModelSelection: null }, + [unassignedNamed]: { name: "Unassigned", instanceIds: [], defaultModelSelection: null }, + }, + projectSettingsOverrides: { + [api]: { providerProfileId: named }, + [web]: { providerProfileId: unassignedNamed }, + }, + }); + const profiles = collectProfiles([[primary, namedSettings]], primary); + const map = buildProjectProfileMap( + [ + { environmentId: primary, id: api }, + { environmentId: primary, id: web }, + { environmentId: primary, id: dotfiles }, + ], + new Map([[primary, namedSettings]]), + ); + const allScope = resolveProfileScope(profileScopeForId(named), profiles, true); + const unassignedScope = resolveProfileScope(profileScopeForId(unassignedNamed), profiles, true); + expect(allScope).toBe("profile:all"); + expect(unassignedScope).toBe("profile:unassigned"); + expect([...(scopedProjectKeysForProfile(allScope, map) ?? [])]).toEqual([`${primary}:${api}`]); + expect([...(scopedProjectKeysForProfile(unassignedScope, map) ?? [])]).toEqual([ + `${primary}:${web}`, + ]); + expect([...(scopedProjectKeysForProfile("unassigned", map) ?? [])]).toEqual([ + `${primary}:${dotfiles}`, + ]); + }); + + it("keeps only the profile's members of a project grouped across environments", () => { + // One repository checked out on two machines, each assigned to a different profile. + const group = new Set([`${primary}:${api}`, `${remote}:${web}`]); + const map = buildProjectProfileMap( + [ + { environmentId: primary, id: api }, + { environmentId: remote, id: web }, + ], + new Map([ + [primary, settings({ projectSettingsOverrides: { [api]: { providerProfileId: acme } } })], + [remote, settings({ projectSettingsOverrides: { [web]: { providerProfileId: globex } } })], + ]), + ); + const acmeKeys = scopedProjectKeysForProfile(profileScopeForId(acme), map); + expect([...(intersectProjectKeys(group, acmeKeys) ?? [])]).toEqual([`${primary}:${api}`]); + expect(intersectProjectKeys(group, null)).toBe(group); + expect(intersectProjectKeys(null, acmeKeys)).toBe(acmeKeys); + }); +}); + +describe("profileMonogram", () => { + it("uses word initials, else the first two letters", () => { + expect(profileMonogram("Silver Orchard")).toBe("SO"); + expect(profileMonogram("spendle")).toBe("SP"); + expect(profileMonogram(" ")).toBe("?"); + }); +}); + +describe("followNavigation", () => { + const projectProfiles = new Map([ + [`${primary}:${api}`, acme], + [`${primary}:${web}`, globex], + ]); + const at = (routeKey: string, projectId: ProjectId): ProfileNavigation => ({ + routeKey, + projectKey: `${primary}:${projectId}`, + }); + const step = ( + followed: ProfileNavigation | null, + current: ProfileNavigation, + scope: ProfileScope, + ) => followNavigation({ followed, current, scope, projectProfiles }); + + it("switches on navigation and keeps a manual choice until the next one", () => { + const acmeScope = profileScopeForId(acme); + const globexScope = profileScopeForId(globex); + const firstThread = at("thread-a1", api); + // Opening an Acme thread while Globex shows switches to Acme. + expect(step(null, firstThread, globexScope)).toEqual({ kind: "switch", scope: acmeScope }); + // Picking Globex by hand on the same thread holds. + expect(step(firstThread, firstThread, globexScope)).toEqual({ kind: "stay" }); + // Opening another thread of the same Acme project from search or a notification switches back. + expect(step(firstThread, at("thread-a2", api), globexScope)).toEqual({ + kind: "switch", + scope: acmeScope, + }); + // Moving a draft to a Globex project follows it too. + expect(step(at("draft-1", api), at("draft-1", web), acmeScope)).toEqual({ + kind: "switch", + scope: globexScope, + }); + }); + + it("stays when the scope already shows the project, and waits for unknown projects", () => { + expect(step(null, at("thread-a1", api), "all")).toEqual({ kind: "stay" }); + expect(step(null, at("thread-x", dotfiles), "all")).toEqual({ kind: "pending" }); + }); +}); diff --git a/packages/client-runtime/src/state/profileScope.ts b/packages/client-runtime/src/state/profileScope.ts new file mode 100644 index 0000000000000..7fb4ab363162e --- /dev/null +++ b/packages/client-runtime/src/state/profileScope.ts @@ -0,0 +1,208 @@ +import type { + EnvironmentId, + ProjectId, + ProviderProfileId, + ServerSettings, +} from "@t3tools/contracts"; + +/** + * What a client's thread list shows: every project, one profile's projects, or those without one. + * Profile ids are slugs of user-chosen names, so a profile named "All" has the id `all`; tagging + * profile values keeps them from ever meaning a special scope. + */ +export type ProfileScope = "all" | "unassigned" | `profile:${ProviderProfileId}`; + +const PROFILE_SCOPE_PREFIX = "profile:"; + +export function profileScopeForId(id: ProviderProfileId): `profile:${ProviderProfileId}` { + return `${PROFILE_SCOPE_PREFIX}${id}`; +} + +/** The profile a scope selects, or null for "all" and "unassigned". */ +export function profileIdOfScope(scope: ProfileScope): ProviderProfileId | null { + return scope.startsWith(PROFILE_SCOPE_PREFIX) + ? (scope.slice(PROFILE_SCOPE_PREFIX.length) as ProviderProfileId) + : null; +} + +export interface ProfileScopeProfile { + readonly id: ProviderProfileId; + readonly name: string; + readonly color: string | null; +} + +type ProfileSettings = Pick< + ServerSettings, + "providerProfileId" | "providerProfiles" | "projectSettingsOverrides" +>; + +/** `${environmentId}:${projectId}`, the key thread lists filter threads and drafts by. */ +export function profileScopeProjectKey(environmentId: EnvironmentId, projectId: string): string { + return `${environmentId}:${projectId}`; +} + +/** + * The profile a project uses on its own environment: its override, including an explicit + * "no profile", else the environment default. + */ +function resolveProjectProviderProfileId( + settings: Pick, + projectId: ProjectId, +): ProviderProfileId | null { + const entry = settings.projectSettingsOverrides[projectId]; + return entry !== undefined && Object.hasOwn(entry, "providerProfileId") + ? (entry.providerProfileId ?? null) + : settings.providerProfileId; +} + +/** Like `resolveProjectProviderProfileId`, but an id whose profile was deleted means none. */ +export function resolveProjectProfileId( + settings: ProfileSettings, + projectId: ProjectId, +): ProviderProfileId | null { + const id = resolveProjectProviderProfileId(settings, projectId); + return id !== null && settings.providerProfiles[id] !== undefined ? id : null; +} + +/** + * Profiles across environments, merged by id and sorted by name. Profiles are stored per + * environment, so one id is treated as one company everywhere; the primary environment names it. + */ +export function collectProfiles( + settingsByEnvironment: ReadonlyArray< + readonly [EnvironmentId, Pick] + >, + primaryEnvironmentId: EnvironmentId | null, +): ReadonlyArray { + const ordered = [...settingsByEnvironment].sort( + ([left], [right]) => + Number(right === primaryEnvironmentId) - Number(left === primaryEnvironmentId), + ); + const byId = new Map(); + for (const [, settings] of ordered) { + for (const [id, profile] of Object.entries(settings.providerProfiles) as Array< + [ProviderProfileId, ServerSettings["providerProfiles"][ProviderProfileId]] + >) { + if (!byId.has(id)) byId.set(id, { id, name: profile.name, color: profile.color ?? null }); + } + } + return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name)); +} + +/** Each project's profile, keyed by `profileScopeProjectKey`. */ +export function buildProjectProfileMap( + projects: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly id: ProjectId }>, + settingsByEnvironment: ReadonlyMap, +): ReadonlyMap { + const map = new Map(); + for (const project of projects) { + const settings = settingsByEnvironment.get(project.environmentId); + map.set( + profileScopeProjectKey(project.environmentId, project.id), + settings ? resolveProjectProfileId(settings, project.id) : null, + ); + } + return map; +} + +/** + * The scope to show for a stored choice. A choice that has nothing to show, a profile no + * connected environment defines or "unassigned" once every project has a profile, shows + * everything without forgetting the choice, so it returns when that changes back. + */ +export function resolveProfileScope( + stored: string, + profiles: ReadonlyArray, + hasUnassignedProjects: boolean, +): ProfileScope { + if (profiles.length === 0) return "all"; + if (stored === "unassigned") return hasUnassignedProjects ? "unassigned" : "all"; + if (!stored.startsWith(PROFILE_SCOPE_PREFIX)) return "all"; + const id = stored.slice(PROFILE_SCOPE_PREFIX.length); + const profile = profiles.find((candidate) => candidate.id === id); + return profile ? profileScopeForId(profile.id) : "all"; +} + +/** The scope that contains a project: its profile, or the unassigned bucket. */ +function profileScopeOfProject(profileId: ProviderProfileId | null | undefined): ProfileScope { + return profileId == null ? "unassigned" : profileScopeForId(profileId); +} + +function projectMatchesScope( + scope: ProfileScope, + profileId: ProviderProfileId | null | undefined, +): boolean { + if (scope === "all") return true; + if (scope === "unassigned") return profileId == null; + return profileId === profileIdOfScope(scope); +} + +/** Project keys visible in a scope, or null when nothing is filtered. */ +export function scopedProjectKeysForProfile( + scope: ProfileScope, + projectProfiles: ReadonlyMap, +): ReadonlySet | null { + if (scope === "all") return null; + const keys = new Set(); + for (const [key, profileId] of projectProfiles) { + if (projectMatchesScope(scope, profileId)) keys.add(key); + } + return keys; +} + +/** + * Keys allowed by both filters, where null allows everything. A project group can span + * environments whose members use different profiles, so choosing a project inside a profile keeps + * only the members in that profile. + */ +export function intersectProjectKeys( + left: ReadonlySet | null, + right: ReadonlySet | null, +): ReadonlySet | null { + if (left === null) return right; + if (right === null) return left; + return new Set([...left].filter((key) => right.has(key))); +} + +/** Where the user is: the thread or draft the route shows, and the project it belongs to. */ +export interface ProfileNavigation { + /** Identifies the thread or draft, so opening another thread of the same project counts. */ + readonly routeKey: string; + readonly projectKey: string; +} + +export type ProfileNavigationOutcome = + /** The project's profile is not known yet; ask again when projects load. */ + | { readonly kind: "pending" } + /** Nothing new, or the scope already shows the project. */ + | { readonly kind: "stay" } + | { readonly kind: "switch"; readonly scope: ProfileScope }; + +/** + * Follows navigation, not the scope: opening a thread or draft, or moving a draft to another + * project, shows that project's profile. A profile picked by hand holds until the next navigation. + */ +export function followNavigation(input: { + readonly followed: ProfileNavigation | null; + readonly current: ProfileNavigation; + readonly scope: ProfileScope; + readonly projectProfiles: ReadonlyMap; +}): ProfileNavigationOutcome { + const { followed, current } = input; + if (followed?.routeKey === current.routeKey && followed.projectKey === current.projectKey) { + return { kind: "stay" }; + } + if (!input.projectProfiles.has(current.projectKey)) return { kind: "pending" }; + const profileId = input.projectProfiles.get(current.projectKey); + return projectMatchesScope(input.scope, profileId) + ? { kind: "stay" } + : { kind: "switch", scope: profileScopeOfProject(profileId) }; +} + +/** Two letters for a profile avatar: initials of the first two words, else the first two letters. */ +export function profileMonogram(name: string): string { + const words = name.trim().split(/\s+/).filter(Boolean); + const letters = + words.length >= 2 ? `${words[0]![0]}${words[1]![0]}` : (words[0] ?? "?").slice(0, 2); + return letters.toUpperCase(); +} diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 239f9905c534e..ed86745c8d6b7 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -34,6 +34,21 @@ export const MODEL_PICKER_JUMP_KEYBINDING_COMMANDS = [ export type ModelPickerJumpKeybindingCommand = (typeof MODEL_PICKER_JUMP_KEYBINDING_COMMANDS)[number]; +/** Choose which provider profile's projects the sidebar shows; index 0 shows every profile. */ +export const PROFILE_SCOPE_KEYBINDING_COMMANDS = [ + "profile.showAll", + "profile.select.1", + "profile.select.2", + "profile.select.3", + "profile.select.4", + "profile.select.5", + "profile.select.6", + "profile.select.7", + "profile.select.8", + "profile.select.9", +] as const; +export type ProfileScopeKeybindingCommand = (typeof PROFILE_SCOPE_KEYBINDING_COMMANDS)[number]; + const THREAD_KEYBINDING_COMMANDS = [ "thread.stop", "thread.steerQueuedMessage", @@ -101,6 +116,7 @@ export const STATIC_KEYBINDING_COMMANDS = [ "usage.period.quarter", ...MODEL_PICKER_KEYBINDING_COMMANDS, ...THREAD_KEYBINDING_COMMANDS, + ...PROFILE_SCOPE_KEYBINDING_COMMANDS, ] as const; export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([ diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 8029be96f939e..14fa770c4a654 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -5,6 +5,7 @@ import { MAX_KEYBINDINGS_COUNT, MAX_WHEN_EXPRESSION_DEPTH, MODEL_PICKER_JUMP_KEYBINDING_COMMANDS, + PROFILE_SCOPE_KEYBINDING_COMMANDS, type ResolvedKeybindingRule, type ResolvedKeybindingsConfig, THREAD_JUMP_KEYBINDING_COMMANDS, @@ -83,6 +84,10 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+2", command: "usage.period.week", when: "usagePageOpen" }, { key: "mod+shift+3", command: "usage.period.month", when: "usagePageOpen" }, { key: "mod+shift+4", command: "usage.period.quarter", when: "usagePageOpen" }, + ...PROFILE_SCOPE_KEYBINDING_COMMANDS.map((command, index) => ({ + key: `mod+alt+${index}`, + command, + })), ]; function normalizeKeyToken(token: string): string {