diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 02455cd0172e3..3d507828afe78 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -94,6 +94,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope, [WS_METHODS.peerLinksList]: AuthAccessReadScope, [WS_METHODS.peerLinksEnvironments]: AuthAccessReadScope, + [WS_METHODS.peerLinksLinkedSidebar]: AuthOrchestrationReadScope, [WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope, [WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope, [WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 7602662e73d1e..30d3c2f575f26 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -71,6 +71,7 @@ const RPC_AGGREGATES = { [WS_METHODS.peerLinksUnlink]: "peerLinks", [WS_METHODS.peerLinksAddToApp]: "peerLinks", [WS_METHODS.peerLinksEnvironments]: "peerLinks", + [WS_METHODS.peerLinksLinkedSidebar]: "peerLinks", [WS_METHODS.peerLinksReportAppConnections]: "peerLinks", [WS_METHODS.peerLinksAnswerRequest]: "peerLinks", [WS_METHODS.serverGetSettings]: "server", diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index 5ad397558de1a..b205262619394 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -1,5 +1,6 @@ import { type EnvironmentId, + type LinkedSidebarResult, OrchestratorMcpFailure, type OrchestratorMcpEnvironmentLinksResult, OrchestratorMcpLinkAppPairingResult, @@ -29,6 +30,7 @@ import { assertNotLinked } from "../mcp/linkOrigin.ts"; import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import { type CallerLimits, readCaller, unavailable } from "../mcp/threadAccess.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import { readLinkedSidebar } from "./linkedSidebar.ts"; import * as PeerLinks from "./PeerLinks.ts"; import * as PeerMcpClient from "./PeerMcpClient.ts"; @@ -122,6 +124,9 @@ export class PeerForwarding extends Context.Service< readonly links: ( scope: Scope, ) => Effect.Effect; + readonly linkedSidebar: (input: { + readonly catalogEnvironmentIds?: ReadonlyArray | undefined; + }) => Effect.Effect; } >()("t3/peer/PeerForwarding") {} @@ -442,6 +447,9 @@ const make = Effect.gen(function* () { }, ); + const linkedSidebar: PeerForwarding["Service"]["linkedSidebar"] = (input) => + readLinkedSidebar({ links, peers, catalogEnvironmentIds: input.catalogEnvironmentIds }); + return PeerForwarding.of({ addToApp, call, @@ -450,6 +458,7 @@ const make = Effect.gen(function* () { interruptThread, waitForThread, links: listLinks, + linkedSidebar, }); }); diff --git a/apps/server/src/peer/linkedSidebar.test.ts b/apps/server/src/peer/linkedSidebar.test.ts new file mode 100644 index 0000000000000..9235a20ab8768 --- /dev/null +++ b/apps/server/src/peer/linkedSidebar.test.ts @@ -0,0 +1,107 @@ +import { + EnvironmentId, + makeThreadInbox, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { collectLinkedSidebar } from "./linkedSidebar.ts"; + +const laptop = EnvironmentId.make("primary-mac-laptop"); +const omarcy = EnvironmentId.make("omarcy-desktop"); +const air = EnvironmentId.make("js-macbook-air"); +const at = (iso: string) => Option.getOrThrow(DateTime.make(iso)); + +it.effect("reads a reachable server-only link and skips catalog and unreachable links", () => + Effect.gen(function* () { + const seen: Array = []; + const now = at("2026-11-20T05:00:00.000Z"); + const result = yield* collectLinkedSidebar({ + now, + catalogEnvironmentIds: [laptop], + links: [ + { + environmentId: laptop, + label: "primary-mac-laptop", + status: "reachable", + expiresAt: at("2026-12-19T00:00:00.000Z"), + }, + { + environmentId: air, + label: "JS MacBook Air", + status: "unreachable", + expiresAt: at("2026-12-19T00:00:00.000Z"), + }, + { + environmentId: omarcy, + label: "omarcy-desktop", + status: "reachable", + expiresAt: at("2026-12-19T00:00:00.000Z"), + }, + ], + read: (environmentId, tool) => { + seen.push(`${environmentId}:${tool}`); + if (tool === "t3_project_list") { + return Effect.succeed({ + projects: [ + { + id: ProjectId.make("project-eval"), + title: "t3code", + workspaceRoot: "/src/t3code", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-20T00:00:00.000Z", + deletedAt: null, + }, + ], + nextCursor: null, + }); + } + return Effect.succeed({ + projectId: null, + currentThreadId: null, + nextCursor: null, + total: 1, + threads: [ + { + inbox: makeThreadInbox({ actor: { kind: "human", id: "jeff" } }), + threadId: ThreadId.make("thread-eval"), + projectId: ProjectId.make("project-eval"), + title: "10-model copy eval", + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + runtimeMode: "full-access", + interactionMode: "default", + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 4, + createdAt: "2026-11-19T12:00:00.000Z", + updatedAt: "2026-11-20T04:00:00.000Z", + }, + ], + }); + }, + }); + expect(seen).toEqual([`${omarcy}:t3_project_list`, `${omarcy}:t3_thread_list`]); + expect(result.environments.map((environment) => environment.label)).toEqual(["omarcy-desktop"]); + expect(result.environments[0]?.threads.map((thread) => thread.title)).toEqual([ + "10-model copy eval", + ]); + expect(result.environments[0]?.threads[0]?.inbox?.owner).toBe("jeff"); + }), +); diff --git a/apps/server/src/peer/linkedSidebar.ts b/apps/server/src/peer/linkedSidebar.ts new file mode 100644 index 0000000000000..ff643d9e3aaa4 --- /dev/null +++ b/apps/server/src/peer/linkedSidebar.ts @@ -0,0 +1,185 @@ +import { + type EnvironmentId, + type LinkedSidebarEnvironment, + type LinkedSidebarResult, + type LinkedSidebarThread, + NonNegativeInt, + OrchestratorMcpFailure, + OrchestratorMcpThreadListResult, + type PeerLinkSummary, + Project, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; + +const THREAD_PAGE_LIMIT = 100; +const MAX_THREAD_PAGES = 8; +const PROJECT_PAGE_LIMIT = 100; +const MAX_PROJECT_PAGES = 3; +const PAGE_BUDGET = Duration.seconds(3); + +const READ_LIMITS = { + runtimeMode: "approval-required", + interactionMode: "default", +} as const; + +const ProjectPage = Schema.Struct({ + projects: Schema.Array(Project), + nextCursor: Schema.NullOr(NonNegativeInt), +}); + +const decodeProjectPage = Schema.decodeUnknownEffect(ProjectPage); +const decodeThreadPage = Schema.decodeUnknownEffect(OrchestratorMcpThreadListResult); + +export interface LinkedSidebarSourceLink { + readonly environmentId: EnvironmentId; + readonly label: string; + readonly status: PeerLinkSummary["status"]; + readonly expiresAt: DateTime.Utc; +} + +interface Page { + readonly items: ReadonlyArray; + readonly nextCursor: number | null; +} + +type PageError = Schema.SchemaError | OrchestratorMcpFailure; + +const pageAll = Effect.fn("linkedSidebar.pageAll")(function* ( + load: (cursor: number) => Effect.Effect, PageError>, + maxPages: number, +) { + const items: Array = []; + let cursor = 0; + for (let page = 0; page < maxPages; page++) { + const result = yield* Effect.timeoutOption(load(cursor), PAGE_BUDGET).pipe( + Effect.orElseSucceed(() => Option.none>()), + ); + if (Option.isNone(result)) return items; + items.push(...result.value.items); + if (result.value.nextCursor === null) return items; + cursor = result.value.nextCursor; + } + return items; +}); + +const slimThread = ( + thread: (typeof OrchestratorMcpThreadListResult.Type.threads)[number], +): LinkedSidebarThread => ({ + ...(thread.inbox === undefined ? {} : { inbox: thread.inbox }), + threadId: thread.threadId, + projectId: thread.projectId, + title: thread.title, + createdBy: thread.createdBy, + creationSource: thread.creationSource, + status: thread.status, + latestRunId: thread.latestRunId, + providerInstanceId: thread.providerInstanceId, + model: thread.model, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + settled: thread.settled, + settledAt: thread.settledAt, + snoozed: thread.snoozed, + snoozedUntil: thread.snoozedUntil, + ...(thread.pinned === undefined ? {} : { pinned: thread.pinned }), + parentThreadId: thread.parentThreadId, + relationshipToParent: thread.relationshipToParent, + itemCount: thread.itemCount, + createdAt: thread.createdAt, + updatedAt: thread.updatedAt, +}); + +export const collectLinkedSidebar = Effect.fn("linkedSidebar.collect")(function* (input: { + readonly links: ReadonlyArray; + readonly now: DateTime.Utc; + readonly catalogEnvironmentIds: ReadonlyArray; + readonly read: ( + environmentId: EnvironmentId, + tool: "t3_project_list" | "t3_thread_list", + args: Record, + ) => Effect.Effect; +}) { + const skip = new Set(input.catalogEnvironmentIds); + const selected = input.links.filter( + (link) => + link.status === "reachable" && + !DateTime.isLessThanOrEqualTo(link.expiresAt, input.now) && + !skip.has(link.environmentId), + ); + const environments: Array = yield* Effect.forEach( + selected, + (link) => + Effect.gen(function* () { + const projects = yield* pageAll( + (cursor) => + input + .read(link.environmentId, "t3_project_list", { + cursor, + limit: PROJECT_PAGE_LIMIT, + }) + .pipe( + Effect.flatMap(decodeProjectPage), + Effect.map((page) => ({ + items: page.projects.filter((project) => project.deletedAt === null), + nextCursor: page.nextCursor, + })), + ), + MAX_PROJECT_PAGES, + ); + const threads = yield* pageAll( + (cursor) => + input + .read(link.environmentId, "t3_thread_list", { + allProjects: true, + includeSubagents: false, + cursor, + limit: THREAD_PAGE_LIMIT, + }) + .pipe( + Effect.flatMap(decodeThreadPage), + Effect.map((page) => ({ + items: page.threads.map(slimThread), + nextCursor: page.nextCursor, + })), + ), + MAX_THREAD_PAGES, + ); + return { + environmentId: link.environmentId, + label: link.label, + projects, + threads, + } satisfies LinkedSidebarEnvironment; + }), + { concurrency: 2 }, + ); + return { environments } satisfies LinkedSidebarResult; +}); + +export const readLinkedSidebar = Effect.fn("linkedSidebar.read")(function* (input: { + readonly links: PeerLinks.PeerLinks["Service"]; + readonly peers: PeerMcpClient.PeerMcpClient["Service"]; + readonly catalogEnvironmentIds?: ReadonlyArray | undefined; +}) { + const listed = yield* input.links.list; + return yield* collectLinkedSidebar({ + links: listed, + now: yield* DateTime.now, + catalogEnvironmentIds: input.catalogEnvironmentIds ?? [], + read: (environmentId, tool, args) => + input.peers.call({ + environmentId, + tool, + arguments: args, + limits: READ_LIMITS, + success: Schema.Unknown, + }), + }); +}); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 0a621e39cd31a..acea7d4d502a9 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2774,6 +2774,10 @@ export const layerWsRpc = ( peerForwarding.addToApp(environmentId), [WS_METHODS.peerLinksEnvironments]: (_input) => peerLinks.environments.pipe(Effect.map((environments) => ({ environments }))), + [WS_METHODS.peerLinksLinkedSidebar]: (input) => + peerForwarding.linkedSidebar({ + catalogEnvironmentIds: input.catalogEnvironmentIds, + }), [WS_METHODS.peerLinksReportAppConnections]: ({ connections }) => peerLinks.reportAppConnections(currentSessionId, connections), [WS_METHODS.peerLinksAnswerRequest]: (input) => diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 405a2b7749bca..fc47b59ee670b 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -159,7 +159,6 @@ import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useNowMinute } from "../hooks/useNowMinute"; import { - useEnvironmentIdentities, useConnectedEnvironmentIds, useEnvironmentMachines, usePrimaryEnvironmentId, @@ -168,10 +167,13 @@ import { readThreadShell, useAllEnvironmentProjectSnapshotsReady, useDelegatedUnderParent, - useProjects, useServerConfigs, - useQuietThreadShells, } from "../state/entities"; +import { + useSidebarEnvironmentIdentities, + useSidebarProjects, + useSidebarThreadShells, +} from "../state/linkedSidebar"; import { environmentPresentations } from "../state/presentation"; import { primaryServerKeybindingsAtom } from "../state/server"; import { environmentProjects } from "../state/projects"; @@ -868,8 +870,8 @@ function isOptimisticDropReleased(input: { // Build maps in a hook so the compiler can prove they are frozen and cache them. function useSidebarLookups() { - const projects = useProjects(); - const environments = useEnvironmentIdentities(); + const projects = useSidebarProjects(); + const environments = useSidebarEnvironmentIdentities(); const serverConfigs = useServerConfigs(); const providerEntriesByEnvironment = useAtomValue(sidebarProviderEntriesAtom); const projectGroups = useSidebarProjectGroups(); @@ -1159,7 +1161,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), ), ); - const threads = useQuietThreadShells(); + const threads = useSidebarThreadShells(); const promotingDraftThreadKeys = usePromotingDraftThreadKeys(); const threadListFilter = useClientSettings(threadListFilterOf); const founderByEnvironmentId = useClientSettings((settings) => settings.founderByEnvironmentId); diff --git a/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx b/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx index 89bd5c89aab81..ac4716755cb33 100644 --- a/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadFilterMenu.tsx @@ -14,7 +14,8 @@ import type { ReactNode } from "react"; import { updateClientSettings, useClientSettings } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; -import { useConnectedEnvironmentIds, useEnvironmentIdentities } from "../../state/environments"; +import { useConnectedEnvironmentIds } from "../../state/environments"; +import { useSidebarEnvironmentIdentities } from "../../state/linkedSidebar"; import { Menu, MenuCheckboxItem, @@ -59,7 +60,7 @@ export function SidebarThreadFilterMenu({ }) { const filter = useClientSettings(threadListFilterOf); const owner = useClientSettings((settings) => settings.founderInboxOwner); - const environments = useEnvironmentIdentities(); + const environments = useSidebarEnvironmentIdentities(); const environmentIds = environments.map((environment) => environment.environmentId); const changed = changedThreadListFilters(filter, owner, environmentIds); const hiddenCount = environmentIds.filter((id) => diff --git a/apps/web/src/hooks/useSidebarProjectGroups.ts b/apps/web/src/hooks/useSidebarProjectGroups.ts index 88210360d2a7f..dea7617b7d717 100644 --- a/apps/web/src/hooks/useSidebarProjectGroups.ts +++ b/apps/web/src/hooks/useSidebarProjectGroups.ts @@ -4,21 +4,26 @@ import { selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping"; -import { useEnvironmentIdentities, usePrimaryEnvironmentId } from "../state/environments"; -import { useDelegatedUnderParent, useProjects, useQuietThreadShells } from "../state/entities"; +import { usePrimaryEnvironmentId } from "../state/environments"; +import { useDelegatedUnderParent } from "../state/entities"; +import { + useSidebarEnvironmentIdentities, + useSidebarProjects, + useSidebarThreadShells, +} from "../state/linkedSidebar"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; import { useClientSettings } from "./useSettings"; export function useSidebarProjectGroups() { - const projects = useProjects(); + const projects = useSidebarProjects(); // Activity order lags a running thread's streaming ticks until its next // real change; reading every tick re-rendered the whole sidebar with it. - const threads = useQuietThreadShells(); + const threads = useSidebarThreadShells(); const delegatedUnderParent = useDelegatedUnderParent(); const projectOrder = useUiStateStore((store) => store.projectOrder); const sortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); const groupingSettings = useClientSettings(selectProjectGroupingSettings); - const environments = useEnvironmentIdentities(); + const environments = useSidebarEnvironmentIdentities(); const primaryEnvironmentId = usePrimaryEnvironmentId(); const orderedProjects = orderItemsByPreferredIds({ items: projects, diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 5b8f3044d6ab0..378795a105ee8 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -63,6 +63,7 @@ import { isChunkLoadError } from "../lib/chunkReloadGuard"; import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume"; import { AppConnectionReporter, LinkOnConnectCoordinator } from "../state/peerLinks"; import { AutoAddLinkedEnvironments } from "../state/knownEnvironments"; +import { LinkedSidebarFromHosts } from "../state/linkedSidebarHost"; export const Route = createRootRoute({ beforeLoad: async ({ location }) => { @@ -201,6 +202,7 @@ function RootRouteBranch() { + {import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null} diff --git a/apps/web/src/state/linkedSidebar.ts b/apps/web/src/state/linkedSidebar.ts new file mode 100644 index 0000000000000..b71b290a39b9f --- /dev/null +++ b/apps/web/src/state/linkedSidebar.ts @@ -0,0 +1,118 @@ +import { sidebarFromServerLinks } from "@t3tools/client-runtime/state/linked-sidebar"; +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId, LinkedSidebarResult } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/reactivity"; + +import { environmentSummaries } from "./presentation"; +import { environmentProjects } from "./projects"; +import { environmentThreadShells } from "./threads"; + +export const linkedSidebarByHostAtom = Atom.make>( + new Map(), +).pipe(Atom.keepAlive, Atom.withLabel("linked-sidebar:by-host")); + +const sameIdentity = ( + left: { readonly environmentId: EnvironmentId; readonly label: string }, + right: { readonly environmentId: EnvironmentId; readonly label: string }, +) => left.environmentId === right.environmentId && left.label === right.label; + +const sameProject = (left: EnvironmentProject, right: EnvironmentProject) => + left.environmentId === right.environmentId && + left.id === right.id && + left.title === right.title && + left.updatedAt === right.updatedAt; + +const sameThread = (left: EnvironmentThreadShell, right: EnvironmentThreadShell) => + left.environmentId === right.environmentId && + left.id === right.id && + left.title === right.title && + left.updatedAt === right.updatedAt && + left.projectId === right.projectId && + left.settledOverride === right.settledOverride && + left.snoozedUntil === right.snoozedUntil && + left.runtime?.status === right.runtime?.status && + left.source.inbox?.owner === right.source.inbox?.owner && + left.source.inbox?.audience === right.source.inbox?.audience && + left.source.inbox?.attentionKind === right.source.inbox?.attentionKind; + +const linkedSidebarSupplementAtom = Atom.make((get) => { + const catalog = get(environmentSummaries.identitiesAtom).map( + (identity) => identity.environmentId, + ); + const environments = [...get(linkedSidebarByHostAtom).values()].flatMap( + (result) => result.environments, + ); + const next = sidebarFromServerLinks({ catalogEnvironmentIds: catalog, environments }); + const previous = Option.getOrNull(get.self>()); + if ( + previous !== null && + previous.identities.length === next.identities.length && + previous.projects.length === next.projects.length && + previous.threads.length === next.threads.length && + previous.identities.every((identity, index) => + sameIdentity(identity, next.identities[index]!), + ) && + previous.projects.every((project, index) => sameProject(project, next.projects[index]!)) && + previous.threads.every((thread, index) => sameThread(thread, next.threads[index]!)) + ) { + return previous; + } + return next; +}).pipe(Atom.keepAlive, Atom.withLabel("linked-sidebar:supplement")); + +export const sidebarEnvironmentIdentitiesAtom = Atom.make((get) => { + const catalog = get(environmentSummaries.identitiesAtom); + const extra = get(linkedSidebarSupplementAtom).identities; + const next = extra.length === 0 ? catalog : [...catalog, ...extra]; + const previous = Option.getOrNull( + get.self>(), + ); + return previous !== null && + previous.length === next.length && + next.every((identity, index) => sameIdentity(identity, previous[index]!)) + ? previous + : next; +}).pipe(Atom.withLabel("linked-sidebar:identities")); + +export const sidebarProjectsAtom = Atom.make((get) => { + const local = get(environmentProjects.projectsAtom); + const extra = get(linkedSidebarSupplementAtom).projects; + if (extra.length === 0) return local; + const next = [...local, ...extra]; + const previous = Option.getOrNull(get.self>()); + return previous !== null && + previous.length === next.length && + next.every((project, index) => project === previous[index]) + ? previous + : next; +}).pipe(Atom.withLabel("linked-sidebar:projects")); + +export const sidebarThreadShellsAtom = Atom.make((get) => { + const local = get(environmentThreadShells.quietThreadShellsAtom); + const extra = get(linkedSidebarSupplementAtom).threads; + if (extra.length === 0) return local; + const next = [...local, ...extra]; + const previous = Option.getOrNull(get.self>()); + return previous !== null && + previous.length === next.length && + next.every((thread, index) => thread === previous[index]) + ? previous + : next; +}).pipe(Atom.withLabel("linked-sidebar:threads")); + +export function useSidebarEnvironmentIdentities() { + return useAtomValue(sidebarEnvironmentIdentitiesAtom); +} + +export function useSidebarProjects() { + return useAtomValue(sidebarProjectsAtom); +} + +export function useSidebarThreadShells() { + return useAtomValue(sidebarThreadShellsAtom); +} diff --git a/apps/web/src/state/linkedSidebarHost.tsx b/apps/web/src/state/linkedSidebarHost.tsx new file mode 100644 index 0000000000000..76a5c2b094737 --- /dev/null +++ b/apps/web/src/state/linkedSidebarHost.tsx @@ -0,0 +1,55 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId, LinkedSidebarResult } from "@t3tools/contracts"; +import { useEffect, useEffectEvent } from "react"; + +import { useLiveRefresh } from "../hooks/useLiveRefresh"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { linkedSidebarByHostAtom } from "./linkedSidebar"; +import { peerLinkEnvironment, usePeerLinkHosts } from "./peerLinks"; +import { environmentSummaries } from "./presentation"; +import { useEnvironmentQuery } from "./query"; + +export function LinkedSidebarFromHosts() { + const hosts = usePeerLinkHosts(); + return hosts.map((host) => ( + + )); +} + +function LinkedSidebarFromHost({ hostId }: { readonly hostId: EnvironmentId }) { + const catalog = useAtomValue(environmentSummaries.identitiesAtom); + const known = useEnvironmentQuery( + peerLinkEnvironment.linkedSidebar({ + environmentId: hostId, + input: { catalogEnvironmentIds: catalog.map((identity) => identity.environmentId) }, + }), + ); + useLiveRefresh( + () => { + if (!known.isPending) known.refresh(); + }, + { key: `linked-sidebar:${hostId}`, refreshOnReconnect: true }, + ); + const publish = useEffectEvent((data: LinkedSidebarResult | null) => { + const current = appAtomRegistry.get(linkedSidebarByHostAtom); + if (data === null) { + if (!current.has(hostId)) return; + const next = new Map(current); + next.delete(hostId); + appAtomRegistry.set(linkedSidebarByHostAtom, next); + return; + } + if (current.get(hostId) === data) return; + const next = new Map(current); + next.set(hostId, data); + appAtomRegistry.set(linkedSidebarByHostAtom, next); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this host's server-side links into the sidebar when its list changes + useEffect(() => { + if (known.data === undefined) return; + publish(known.data); + }, [known.data]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops this host's server-side links when it disconnects + useEffect(() => () => publish(null), []); + return null; +} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 3fa0378ea3dc8..ee38ec5918f0e 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -255,6 +255,10 @@ "types": "./src/state/peerLinks.ts", "default": "./src/state/peerLinks.ts" }, + "./state/linked-sidebar": { + "types": "./src/state/linkedSidebar.ts", + "default": "./src/state/linkedSidebar.ts" + }, "./state/environmentHttpAuth": { "types": "./src/state/environmentHttpAuth.ts", "default": "./src/state/environmentHttpAuth.ts" diff --git a/packages/client-runtime/src/state/linkedSidebar.test.ts b/packages/client-runtime/src/state/linkedSidebar.test.ts new file mode 100644 index 0000000000000..aa379a2818523 --- /dev/null +++ b/packages/client-runtime/src/state/linkedSidebar.test.ts @@ -0,0 +1,104 @@ +import { + EnvironmentId, + makeThreadInbox, + ProjectId, + ProviderInstanceId, + ThreadId, + type LinkedSidebarThread, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { sidebarFromServerLinks } from "./linkedSidebar.ts"; +import { matchesThreadListFilter, threadListFilterOf } from "./threadListFilter.ts"; + +const laptop = EnvironmentId.make("primary-mac-laptop"); +const omarcy = EnvironmentId.make("omarcy-desktop"); +const projectId = ProjectId.make("project-eval"); +const threadId = ThreadId.make("thread-eval"); + +const jeffThread = { + inbox: makeThreadInbox({ actor: { kind: "human", id: "jeff" } }), + threadId, + projectId, + title: "10-model copy eval", + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + runtimeMode: "full-access", + interactionMode: "default", + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 4, + createdAt: "2026-11-19T12:00:00.000Z", + updatedAt: "2026-11-20T04:00:00.000Z", +} satisfies LinkedSidebarThread; + +describe("sidebarFromServerLinks", () => { + it("lists a thread owned by another founder on a server-only link", () => { + const listed = sidebarFromServerLinks({ + catalogEnvironmentIds: [laptop], + environments: [ + { + environmentId: laptop, + label: "primary-mac-laptop", + projects: [], + threads: [{ ...jeffThread, threadId: ThreadId.make("thread-local-jeff") }], + }, + { + environmentId: omarcy, + label: "omarcy-desktop", + projects: [ + { + id: projectId, + title: "t3code", + workspaceRoot: "/src/t3code", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-20T00:00:00.000Z", + deletedAt: null, + }, + ], + threads: [jeffThread], + }, + ], + }); + expect(listed.identities).toEqual([{ environmentId: omarcy, label: "omarcy-desktop" }]); + expect(listed.projects.map((project) => project.environmentId)).toEqual([omarcy]); + expect(listed.threads.map((thread) => thread.id)).toEqual([threadId]); + const filter = threadListFilterOf({ founderInboxOwner: "kameron" }); + const linked = listed.threads[0]!; + expect(matchesThreadListFilter(linked, filter)).toBe(false); + expect(matchesThreadListFilter(linked, { ...filter, inboxes: ["jeff"] })).toBe(true); + }); + + it("lists one copy when two hosts report the same server-only link", () => { + const listed = sidebarFromServerLinks({ + catalogEnvironmentIds: [laptop], + environments: [ + { + environmentId: omarcy, + label: "omarcy-desktop", + projects: [], + threads: [jeffThread], + }, + { + environmentId: omarcy, + label: "omarcy-desktop", + projects: [], + threads: [jeffThread], + }, + ], + }); + expect(listed.identities).toEqual([{ environmentId: omarcy, label: "omarcy-desktop" }]); + expect(listed.threads.map((thread) => thread.id)).toEqual([threadId]); + expect(listed.projects).toHaveLength(1); + }); +}); diff --git a/packages/client-runtime/src/state/linkedSidebar.ts b/packages/client-runtime/src/state/linkedSidebar.ts new file mode 100644 index 0000000000000..c6b181634200d --- /dev/null +++ b/packages/client-runtime/src/state/linkedSidebar.ts @@ -0,0 +1,191 @@ +import { + type EnvironmentId, + type LinkedSidebarEnvironment, + type LinkedSidebarThread, + type ModelSelection, + OrchestrationV2ThreadShell, + type Project, + type ProjectId, + type ProjectScript, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { + type EnvironmentProject, + type EnvironmentThreadShell, + presentThreadShell, +} from "./models.ts"; + +const decodeShell = Schema.decodeUnknownSync(OrchestrationV2ThreadShell); + +const utc = (value: string) => { + const parsed = DateTime.make(value); + if (Option.isNone(parsed)) throw new Error("bad date"); + return parsed.value; +}; +const utcOrNull = (value: string | null) => (value === null ? null : utc(value)); + +const ACTIVE_STATUS = new Set(["preparing", "starting", "running", "waiting"]); + +function threadShellFromLinkedThread( + environmentId: EnvironmentId, + thread: LinkedSidebarThread, +): EnvironmentThreadShell | null { + if (thread.relationshipToParent === "subagent") return null; + const active = ACTIVE_STATUS.has(thread.status); + try { + const shell = decodeShell({ + ...(thread.inbox === undefined ? {} : { inbox: thread.inbox }), + createdBy: thread.createdBy, + creationSource: thread.creationSource, + id: thread.threadId, + projectId: thread.projectId, + title: thread.title, + providerInstanceId: thread.providerInstanceId, + modelSelection: { instanceId: thread.providerInstanceId, model: thread.model }, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + branch: null, + worktreePath: null, + lineage: { + parentThreadId: thread.parentThreadId, + relationshipToParent: thread.relationshipToParent, + rootThreadId: thread.parentThreadId ?? thread.threadId, + }, + forkedFrom: null, + activeProviderThreadId: null, + latestRunId: thread.latestRunId, + activeRunId: active ? thread.latestRunId : null, + ...(active ? { activityRunStatus: thread.status } : {}), + status: thread.status, + pendingRuntimeRequest: null, + latestVisibleMessage: null, + latestUserMessageAt: utc(thread.updatedAt), + hasActionableProposedPlan: false, + pendingBackgroundTasks: [], + providerInstanceHistory: [], + itemCount: thread.itemCount, + visibleItemCount: thread.itemCount, + createdAt: utc(thread.createdAt), + updatedAt: utc(thread.updatedAt), + archivedAt: null, + settledOverride: thread.settled ? "settled" : null, + settledAt: utcOrNull(thread.settledAt), + snoozedUntil: thread.snoozed ? utcOrNull(thread.snoozedUntil) : null, + pinnedAt: thread.pinned === true ? utc(thread.updatedAt) : null, + deletedAt: null, + }); + return presentThreadShell(environmentId, shell); + } catch { + return null; + } +} + +interface SidebarProjectInput { + readonly id: ProjectId; + readonly title: string; + readonly hasCustomTitle?: boolean | undefined; + readonly workspaceRoot: string; + readonly repositoryIdentity?: Project["repositoryIdentity"] | undefined; + readonly defaultModelSelection: ModelSelection | null; + readonly defaultThreadEnvMode?: Project["defaultThreadEnvMode"] | undefined; + readonly autoPull?: boolean | undefined; + readonly faviconPath?: Project["faviconPath"] | undefined; + readonly projectIcon?: Project["projectIcon"] | undefined; + readonly scripts: ReadonlyArray; + readonly pinnedAt?: string | null | undefined; + readonly archivedAt?: string | null | undefined; + readonly createdAt: string; + readonly updatedAt: string; + readonly deletedAt: string | null; +} + +const projectShell = ( + environmentId: EnvironmentId, + project: SidebarProjectInput, +): EnvironmentProject | null => + project.deletedAt !== null + ? null + : { + id: project.id, + title: project.title, + ...(project.hasCustomTitle === undefined ? {} : { hasCustomTitle: project.hasCustomTitle }), + workspaceRoot: project.workspaceRoot, + ...(project.repositoryIdentity === undefined + ? {} + : { repositoryIdentity: project.repositoryIdentity }), + defaultModelSelection: project.defaultModelSelection, + ...(project.defaultThreadEnvMode === undefined + ? {} + : { defaultThreadEnvMode: project.defaultThreadEnvMode }), + ...(project.autoPull === undefined ? {} : { autoPull: project.autoPull }), + ...(project.faviconPath === undefined ? {} : { faviconPath: project.faviconPath }), + ...(project.projectIcon === undefined ? {} : { projectIcon: project.projectIcon }), + scripts: project.scripts, + ...(project.pinnedAt === undefined ? {} : { pinnedAt: project.pinnedAt }), + ...(project.archivedAt === undefined ? {} : { archivedAt: project.archivedAt }), + createdAt: project.createdAt, + updatedAt: project.updatedAt, + environmentId, + }; + +export function sidebarFromServerLinks(input: { + readonly catalogEnvironmentIds: ReadonlySet | ReadonlyArray; + readonly environments: ReadonlyArray; +}): { + readonly identities: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly label: string; + }>; + readonly projects: ReadonlyArray; + readonly threads: ReadonlyArray; +} { + const catalog = new Set(input.catalogEnvironmentIds); + const identities: Array<{ readonly environmentId: EnvironmentId; readonly label: string }> = []; + const projects: Array = []; + const threads: Array = []; + const seenProjects = new Set(); + const seenEnvironments = new Set(); + const seenThreads = new Set(); + for (const environment of input.environments) { + if (catalog.has(environment.environmentId)) continue; + if (!seenEnvironments.has(environment.environmentId)) { + seenEnvironments.add(environment.environmentId); + identities.push({ environmentId: environment.environmentId, label: environment.label }); + } + for (const project of environment.projects) { + const projectKey = `${environment.environmentId}\0${project.id}`; + if (seenProjects.has(projectKey)) continue; + const shell = projectShell(environment.environmentId, project); + if (shell === null) continue; + projects.push(shell); + seenProjects.add(projectKey); + } + for (const thread of environment.threads) { + const threadKey = `${environment.environmentId}\0${thread.threadId}`; + if (seenThreads.has(threadKey)) continue; + const shell = threadShellFromLinkedThread(environment.environmentId, thread); + if (shell === null) continue; + seenThreads.add(threadKey); + threads.push(shell); + const key = `${environment.environmentId}\0${thread.projectId}`; + if (seenProjects.has(key)) continue; + seenProjects.add(key); + projects.push( + projectShell(environment.environmentId, { + id: thread.projectId, + title: "Untitled project", + workspaceRoot: ".", + defaultModelSelection: null, + scripts: [], + createdAt: thread.createdAt, + updatedAt: thread.updatedAt, + deletedAt: null, + })!, + ); + } + } + return { identities, projects, threads }; +} diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 472582de568cf..4c1b625989898 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -22,6 +22,11 @@ export function createPeerLinkEnvironmentAtoms( tag: WS_METHODS.peerLinksEnvironments, staleTimeMs: 10_000, }); + const linkedSidebar = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:peer-links:linked-sidebar", + tag: WS_METHODS.peerLinksLinkedSidebar, + staleTimeMs: 10_000, + }); const refreshLists = (environmentId: EnvironmentId, registry: AtomRegistry.AtomRegistry) => Effect.sync(() => { registry.refresh(list({ environmentId, input: {} })); @@ -30,6 +35,7 @@ export function createPeerLinkEnvironmentAtoms( return { list, environments, + linkedSidebar, link: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:link", tag: WS_METHODS.peerLinksLink, diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 392b256b6e4b2..9dacb77c54884 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -44,6 +44,7 @@ export * from "./guestStream.ts"; export * from "./applicationEvent.ts"; export * from "./orchestratorMcp.ts"; export * from "./peerLink.ts"; +export * from "./linkedSidebar.ts"; export * from "./threadMetadataMcp.ts"; export * from "./threadPullRequest.ts"; export * from "./threadSearch.ts"; diff --git a/packages/contracts/src/linkedSidebar.ts b/packages/contracts/src/linkedSidebar.ts new file mode 100644 index 0000000000000..f0fa4587d96fe --- /dev/null +++ b/packages/contracts/src/linkedSidebar.ts @@ -0,0 +1,60 @@ +import * as Schema from "effect/Schema"; + +import { + EnvironmentId, + IsoDateTime, + NonNegativeInt, + ProjectId, + RunId, + ThreadId, +} from "./baseSchemas.ts"; +import { Project } from "./project.ts"; +import { ProviderInstanceId } from "./providerInstance.ts"; +import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts"; +import { OrchestratorMcpThreadStatus } from "./orchestratorMcp.ts"; +import { OrchestrationV2Actor, OrchestrationV2CreationSource } from "./orchestrationV2.ts"; +import { ThreadInbox } from "./threadInbox.ts"; + +export const LinkedSidebarInput = Schema.Struct({ + catalogEnvironmentIds: Schema.optionalKey(Schema.Array(EnvironmentId)), +}); +export type LinkedSidebarInput = typeof LinkedSidebarInput.Type; + +export const LinkedSidebarThread = Schema.Struct({ + inbox: Schema.optionalKey(ThreadInbox), + threadId: ThreadId, + projectId: ProjectId, + title: Schema.String, + createdBy: OrchestrationV2Actor, + creationSource: OrchestrationV2CreationSource, + status: OrchestratorMcpThreadStatus, + latestRunId: Schema.NullOr(RunId), + providerInstanceId: ProviderInstanceId, + model: Schema.String, + runtimeMode: RuntimeMode, + interactionMode: ProviderInteractionMode, + settled: Schema.Boolean, + settledAt: Schema.NullOr(IsoDateTime), + snoozed: Schema.Boolean, + snoozedUntil: Schema.NullOr(IsoDateTime), + pinned: Schema.optional(Schema.Boolean), + parentThreadId: Schema.NullOr(ThreadId), + relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])), + itemCount: NonNegativeInt, + createdAt: IsoDateTime, + updatedAt: IsoDateTime, +}); +export type LinkedSidebarThread = typeof LinkedSidebarThread.Type; + +export const LinkedSidebarEnvironment = Schema.Struct({ + environmentId: EnvironmentId, + label: Schema.String, + projects: Schema.Array(Project), + threads: Schema.Array(LinkedSidebarThread), +}); +export type LinkedSidebarEnvironment = typeof LinkedSidebarEnvironment.Type; + +export const LinkedSidebarResult = Schema.Struct({ + environments: Schema.Array(LinkedSidebarEnvironment), +}); +export type LinkedSidebarResult = typeof LinkedSidebarResult.Type; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index d68878a84a7da..b82deb7bfad94 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -30,6 +30,8 @@ import { PeerLinkRequestError, PeerLinkSummary, } from "./peerLink.ts"; +import { LinkedSidebarInput, LinkedSidebarResult } from "./linkedSidebar.ts"; + import { ChatGptReconnectProfileInput, ChatGptReconnectProfile, @@ -529,6 +531,7 @@ export const WS_METHODS = { peerLinksUnlink: "peerLinks.unlink", peerLinksAddToApp: "peerLinks.addToApp", peerLinksEnvironments: "peerLinks.environments", + peerLinksLinkedSidebar: "peerLinks.linkedSidebar", peerLinksReportAppConnections: "peerLinks.reportAppConnections", peerLinksAnswerRequest: "peerLinks.answerRequest", serverGetSettings: "server.getSettings", @@ -880,6 +883,12 @@ const WsPeerLinksEnvironmentsRpc = Rpc.make(WS_METHODS.peerLinksEnvironments, { error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), }); +const WsPeerLinksLinkedSidebarRpc = Rpc.make(WS_METHODS.peerLinksLinkedSidebar, { + payload: LinkedSidebarInput, + success: LinkedSidebarResult, + error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]), +}); + const WsPeerLinksReportAppConnectionsRpc = Rpc.make(WS_METHODS.peerLinksReportAppConnections, { payload: AppConnectionsReportInput, error: EnvironmentAuthorizationError, @@ -2182,6 +2191,7 @@ export const WsRpcGroup = RpcGroup.make( WsPeerLinksUnlinkRpc, WsPeerLinksAddToAppRpc, WsPeerLinksEnvironmentsRpc, + WsPeerLinksLinkedSidebarRpc, WsPeerLinksReportAppConnectionsRpc, WsPeerLinksAnswerRequestRpc, WsServerDiscoverSourceControlRpc,