Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Library: references and documents get a page of their own
Simon Flack18f545fa6f59
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/library-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/library-client.test.tsnew file mode 100644index 000000000..28aaa50e9--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/library-client.test.ts@@ -0,0 +1,255 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const getSessionCookie = vi.hoisted(() => vi.fn());++vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({+ managedServerHostBlocked: () => null,+ managedServerStoppedPhase: () => null,+ noteManagedServerUnanswered: () => undefined,+}));+vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie: vi.fn() }));+vi.mock('./auth', () => ({+ refreshSession: vi.fn(),+ reauthenticateManagedServer: vi.fn(),+ extractAuthCookie: () => null,+}));+vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));++const {+ createLibraryItem,+ deleteLibraryItem,+ fetchLibraryItem,+ fetchLibraryItemRooms,+ fetchLibraryItems,+ fetchReferenceTypes,+ updateLibraryItem,+} = await import('./library-client');++const SERVER = {+ id: 'srv-1',+ name: 'S',+ url: 'https://switch.example.com',+ dashboardUrl: null,+ managed: false,+} as never;++function makeJwt(secondsFromNow: number): string {+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');+ const exp = Math.floor(Date.now() / 1000) + secondsFromNow;+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');+ return `${header}.${payload}.sig`;+}++function jsonResponse(body: unknown): Response {+ return {+ status: 200,+ ok: true,+ json: async () => body,+ headers: { get: () => null, getSetCookie: () => [] },+ text: async () => JSON.stringify(body),+ } as unknown as Response;+}++/** A gateway `ReferenceDetail` with every field the client reads. */+const REFERENCE = {+ id: 'ref-1',+ owner_id: 'u1',+ owner_name: 'Ada',+ read_visibility: 'public',+ write_visibility: 'private',+ type: 'github',+ type_display_name: 'GitHub',+ name: 'Switch repo',+ description: 'The code',+ instructions: 'Read the README first',+ value: { urls: ['https://github.com/acme/switch'] },+ attached_rooms_count: 2,+ packages: ['pkg-1'],+ created_at: '2026-11-01T09:00:00+00:00',+};++const DOCUMENT = {+ id: 'doc-1',+ owner_id: 'u2',+ owner_name: null,+ read_visibility: 'private',+ write_visibility: 'private',+ name: 'Style guide',+ description: '',+ instructions: '',+ content: '# Style',+ attached_rooms_count: 0,+ packages: [],+ scope: 'global',+ created_at: '2026-11-01T09:00:00+00:00',+};++const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => jsonResponse(REFERENCE));++function lastCall(): { url: string; method: string; body: unknown } {+ const [url, init] = fetchMock.mock.calls.at(-1) as [string, RequestInit | undefined];+ return {+ url,+ method: init?.method ?? 'GET',+ body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ getSessionCookie.mockResolvedValue(makeJwt(2 * 60 * 60));+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('reading the library', () => {+ it('maps a reference with its owner, access, type and links', async () => {+ fetchMock.mockImplementation(async () => jsonResponse([REFERENCE]));+ const [item] = await fetchLibraryItems(SERVER, 'references');+ expect(lastCall().url).toMatch(/\/gateway\/references$/);+ expect(item).toEqual({+ id: 'ref-1',+ kind: 'references',+ name: 'Switch repo',+ description: 'The code',+ instructions: 'Read the README first',+ ownerId: 'u1',+ ownerName: 'Ada',+ readVisibility: 'public',+ writeVisibility: 'private',+ type: 'github',+ typeLabel: 'GitHub',+ urls: ['https://github.com/acme/switch'],+ attachedRoomsCount: 2,+ packageIds: ['pkg-1'],+ createdAt: '2026-11-01T09:00:00+00:00',+ });+ });++ it('leaves agents’ room-only documents out of the library', async () => {+ fetchMock.mockImplementation(async () =>+ jsonResponse([DOCUMENT, { ...DOCUMENT, id: 'doc-2', scope: 'room' }])+ );+ const items = await fetchLibraryItems(SERVER, 'documents');+ expect(items.map((d) => d.id)).toEqual(['doc-1']);+ expect(items[0]).toMatchObject({ type: null, typeLabel: null, urls: [], ownerName: null });+ });++ it('reads a document with its content', async () => {+ fetchMock.mockImplementation(async () => jsonResponse(DOCUMENT));+ const doc = await fetchLibraryItem(SERVER, 'documents', 'doc-1');+ expect(lastCall().url).toMatch(/\/gateway\/documents\/doc-1$/);+ expect(doc).toMatchObject({ id: 'doc-1', content: '# Style' });+ });++ it('lists the rooms an item is in', async () => {+ fetchMock.mockImplementation(async () =>+ jsonResponse([{ room_id: 'room-1', room_name: 'design' }])+ );+ expect(await fetchLibraryItemRooms(SERVER, 'references', 'ref-1')).toEqual([+ { roomId: 'room-1', roomName: 'design' },+ ]);+ expect(lastCall().url).toMatch(/\/gateway\/references\/ref-1\/rooms$/);+ });++ it('offers Switch’s own reference types first, then people’s, by name', async () => {+ fetchMock.mockImplementation(async () =>+ jsonResponse([+ {+ type: 'wiki',+ display_name: 'Wiki',+ value_hint: 'Pages',+ is_builtin: false,+ owner_name: 'Bo',+ },+ { type: 'github', display_name: 'GitHub', value_hint: 'Repos', is_builtin: true },+ { type: 'confluence', display_name: 'Confluence', value_hint: null, is_builtin: true },+ ])+ );+ const types = await fetchReferenceTypes(SERVER);+ expect(types.map((t) => t.type)).toEqual(['confluence', 'github', 'wiki']);+ expect(types[2]).toEqual({+ type: 'wiki',+ displayName: 'Wiki',+ valueHint: 'Pages',+ isBuiltin: false,+ ownerName: 'Bo',+ });+ });+});++describe('changing the library', () => {+ it('creates a reference with its type and links as the value', async () => {+ fetchMock.mockImplementation(async () => jsonResponse(REFERENCE));+ await createLibraryItem(SERVER, 'references', {+ name: 'Switch repo',+ description: 'The code',+ instructions: '',+ readVisibility: 'public',+ writeVisibility: 'private',+ type: 'github',+ urls: ['https://github.com/acme/switch'],+ });+ expect(lastCall()).toEqual({+ url: expect.stringMatching(/\/gateway\/references$/),+ method: 'POST',+ body: {+ name: 'Switch repo',+ description: 'The code',+ instructions: '',+ read_visibility: 'public',+ write_visibility: 'private',+ type: 'github',+ value: { urls: ['https://github.com/acme/switch'] },+ },+ });+ });++ it('creates a document with its content and nothing of a reference’s', async () => {+ fetchMock.mockImplementation(async () => jsonResponse(DOCUMENT));+ await createLibraryItem(SERVER, 'documents', {+ name: 'Style guide',+ description: '',+ instructions: '',+ readVisibility: 'private',+ writeVisibility: 'private',+ content: '# Style',+ });+ expect(lastCall().body).toEqual({+ name: 'Style guide',+ description: '',+ instructions: '',+ read_visibility: 'private',+ write_visibility: 'private',+ content: '# Style',+ });+ });++ it('sends only the fields that changed', async () => {+ fetchMock.mockImplementation(async () => jsonResponse(DOCUMENT));+ await updateLibraryItem(SERVER, 'documents', 'doc-1', { content: '# New' });+ expect(lastCall()).toEqual({+ url: expect.stringMatching(/\/gateway\/documents\/doc-1$/),+ method: 'PATCH',+ body: { content: '# New' },+ });+ });++ it('reports what deleting took with it', async () => {+ fetchMock.mockImplementation(async () =>+ jsonResponse({+ deleted_id: 'ref-1',+ detached_room_ids: ['room-1'],+ affected_package_ids: ['pkg-1'],+ })+ );+ expect(await deleteLibraryItem(SERVER, 'references', 'ref-1')).toEqual({+ detachedRoomIds: ['room-1'],+ affectedPackageIds: ['pkg-1'],+ });+ expect(lastCall()).toMatchObject({ method: 'DELETE' });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/library-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/library-client.tsnew file mode 100644index 000000000..9a54aacb5--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/library-client.ts@@ -0,0 +1,192 @@+import type {+ LibraryDeleteResult,+ LibraryDocument,+ LibraryItem,+ LibraryItemChanges,+ LibraryItemInput,+ LibraryItemRoom,+ LibraryKind,+ LibraryVisibility,+ ReferenceTypeOption,+} from '@shared/core/switch-servers/library';+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';+import { gatewayFetch } from './gateway-client';++// The workspace library's references and documents, through the gateway's+// `/references` and `/documents` routes. Attaching one to a room is the room+// resources call in gateway-client.++type LibraryItemJson = {+ id: string;+ owner_id: string;+ owner_name?: string | null;+ read_visibility: string;+ write_visibility: string;+ name: string;+ description: string;+ instructions?: string;+ type?: string;+ type_display_name?: string | null;+ value?: { urls?: unknown };+ content?: string;+ attached_rooms_count?: number;+ packages?: string[];+ scope?: 'global' | 'room';+ created_at: string;+};++function visibility(value: string): LibraryVisibility {+ return value === 'public' ? 'public' : 'private';+}++export function mapLibraryItem(kind: LibraryKind, r: LibraryItemJson): LibraryItem {+ const urls = Array.isArray(r.value?.urls)+ ? r.value.urls.filter((url): url is string => typeof url === 'string')+ : [];+ return {+ id: r.id,+ kind,+ name: r.name,+ description: r.description,+ instructions: r.instructions ?? '',+ ownerId: r.owner_id,+ ownerName: r.owner_name ?? null,+ readVisibility: visibility(r.read_visibility),+ writeVisibility: visibility(r.write_visibility),+ type: kind === 'references' ? (r.type ?? null) : null,+ typeLabel: kind === 'references' ? (r.type_display_name ?? r.type ?? null) : null,+ urls,+ attachedRoomsCount: r.attached_rooms_count ?? 0,+ packageIds: r.packages ?? [],+ createdAt: r.created_at,+ };+}++function itemPath(kind: LibraryKind, id: string): string {+ return `/${kind}/${encodeURIComponent(id)}`;+}++/** The library items of one kind the signed-in person may read (`GET /{kind}`). */+export async function fetchLibraryItems(+ server: SwitchServer,+ kind: LibraryKind+): Promise<LibraryItem[]> {+ const res = await gatewayFetch(server, `/${kind}`, { authenticated: true });+ // Agents' room-only documents are the room's, not the library's.+ return ((await res.json()) as LibraryItemJson[])+ .filter((r) => r.scope !== 'room')+ .map((r) => mapLibraryItem(kind, r));+}++/** One library item; a document comes with its content. */+export async function fetchLibraryItem(+ server: SwitchServer,+ kind: LibraryKind,+ id: string+): Promise<LibraryItem | LibraryDocument> {+ const res = await gatewayFetch(server, itemPath(kind, id), { authenticated: true });+ const json = (await res.json()) as LibraryItemJson;+ const item = mapLibraryItem(kind, json);+ return kind === 'documents' ? { ...item, content: json.content ?? '' } : item;+}++function body(kind: LibraryKind, input: LibraryItemChanges & { type?: string }) {+ return {+ ...(input.name !== undefined ? { name: input.name } : {}),+ ...(input.description !== undefined ? { description: input.description } : {}),+ ...(input.instructions !== undefined ? { instructions: input.instructions } : {}),+ ...(input.readVisibility !== undefined ? { read_visibility: input.readVisibility } : {}),+ ...(input.writeVisibility !== undefined ? { write_visibility: input.writeVisibility } : {}),+ ...(kind === 'references' && input.type !== undefined ? { type: input.type } : {}),+ ...(kind === 'references' && input.urls !== undefined ? { value: { urls: input.urls } } : {}),+ ...(kind === 'documents' && input.content !== undefined ? { content: input.content } : {}),+ };+}++/** Add a reference or document to the library. Refusals propagate in the gateway's words. */+export async function createLibraryItem(+ server: SwitchServer,+ kind: LibraryKind,+ input: LibraryItemInput+): Promise<LibraryItem> {+ const res = await gatewayFetch(server, `/${kind}`, {+ authenticated: true,+ method: 'POST',+ body: body(kind, input),+ });+ return mapLibraryItem(kind, (await res.json()) as LibraryItemJson);+}++/** Change a library item; only the fields given are sent. */+export async function updateLibraryItem(+ server: SwitchServer,+ kind: LibraryKind,+ id: string,+ changes: LibraryItemChanges+): Promise<LibraryItem | LibraryDocument> {+ const res = await gatewayFetch(server, itemPath(kind, id), {+ authenticated: true,+ method: 'PATCH',+ body: body(kind, changes),+ });+ const json = (await res.json()) as LibraryItemJson;+ const item = mapLibraryItem(kind, json);+ return kind === 'documents' ? { ...item, content: json.content ?? '' } : item;+}++/** Delete a library item, detaching it from every room and package it was in. */+export async function deleteLibraryItem(+ server: SwitchServer,+ kind: LibraryKind,+ id: string+): Promise<LibraryDeleteResult> {+ const res = await gatewayFetch(server, itemPath(kind, id), {+ authenticated: true,+ method: 'DELETE',+ });+ const json = (await res.json()) as {+ detached_room_ids?: string[];+ affected_package_ids?: string[];+ };+ return {+ detachedRoomIds: json.detached_room_ids ?? [],+ affectedPackageIds: json.affected_package_ids ?? [],+ };+}++/** The rooms a library item is attached to that the signed-in person can see. */+export async function fetchLibraryItemRooms(+ server: SwitchServer,+ kind: LibraryKind,+ id: string+): Promise<LibraryItemRoom[]> {+ const res = await gatewayFetch(server, `${itemPath(kind, id)}/rooms`, { authenticated: true });+ return ((await res.json()) as { room_id: string; room_name: string }[]).map((r) => ({+ roomId: r.room_id,+ roomName: r.room_name,+ }));+}++/** The types a new reference may be given: Switch's own, then those people wrote. */+export async function fetchReferenceTypes(server: SwitchServer): Promise<ReferenceTypeOption[]> {+ const res = await gatewayFetch(server, '/references/reference-types', { authenticated: true });+ const json = (await res.json()) as {+ type: string;+ display_name: string;+ value_hint?: string | null;+ is_builtin?: boolean;+ owner_name?: string | null;+ }[];+ return json+ .map((t) => ({+ type: t.type,+ displayName: t.display_name,+ valueHint: t.value_hint ?? '',+ isBuiltin: t.is_builtin ?? false,+ ownerName: t.owner_name ?? null,+ }))+ .sort(+ (a, b) =>+ Number(b.isBuiltin) - Number(a.isBuiltin) || a.displayName.localeCompare(b.displayName)+ );+}diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.tsindex 2bfaa9907..8a3d91a0b 100644--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts@@ -104,6 +104,15 @@ import {requireLinkConfirmationOnServer,searchDirectoryOnServer,} from '@main/core/switch-servers/identities';+import {+ createLibraryItem,+ deleteLibraryItem,+ fetchLibraryItem,+ fetchLibraryItemRooms,+ fetchLibraryItems,+ fetchReferenceTypes,+ updateLibraryItem,+} from '@main/core/switch-servers/library-client';import { hostUnreachable } from '@main/core/switch-servers/require-server';import { serverKindOf } from '@main/core/switch-servers/servers-store';import {@@ -132,6 +141,16 @@ import {} from '@main/core/telemetry/narrow';import { telemetryService, trackEvent, trackEventAt } from '@main/core/telemetry/telemetry-service';import { log } from '@main/lib/logger';+import type {+ LibraryDeleteResult,+ LibraryDocument,+ LibraryItem,+ LibraryItemChanges,+ LibraryItemInput,+ LibraryItemRoom,+ LibraryKind,+ ReferenceTypeOption,+} from '@shared/core/switch-servers/library';import type {SlackOwnAppSetup,SlackTokensChecked,@@ -1081,6 +1100,65 @@ export const workspacesController = createRPCController({fetchRoomDocument(server, params.roomId, params.documentId)),+ /** The workspace library's references or documents the signed-in person may read. */+ listLibraryItems: (params: { workspaceId: string; kind: LibraryKind }): Promise<LibraryItem[]> =>+ withWorkspaceSession(params.workspaceId, (server) => fetchLibraryItems(server, params.kind)),++ /** One library item; a document comes with its content. */+ getLibraryItem: (params: {+ workspaceId: string;+ kind: LibraryKind;+ itemId: string;+ }): Promise<LibraryItem | LibraryDocument> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ fetchLibraryItem(server, params.kind, params.itemId)+ ),++ /** Add a reference or document to the library. Refusals propagate in the gateway's words. */+ createLibraryItem: (params: {+ workspaceId: string;+ kind: LibraryKind;+ input: LibraryItemInput;+ }): Promise<LibraryItem> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ createLibraryItem(server, params.kind, params.input)+ ),++ /** Change a library item. */+ updateLibraryItem: (params: {+ workspaceId: string;+ kind: LibraryKind;+ itemId: string;+ changes: LibraryItemChanges;+ }): Promise<LibraryItem | LibraryDocument> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ updateLibraryItem(server, params.kind, params.itemId, params.changes)+ ),++ /** Delete a library item, detaching it from its rooms and packages. */+ deleteLibraryItem: (params: {+ workspaceId: string;+ kind: LibraryKind;+ itemId: string;+ }): Promise<LibraryDeleteResult> =>+ withReachableWorkspaceSession(params.workspaceId, (server) =>+ deleteLibraryItem(server, params.kind, params.itemId)+ ),++ /** The rooms a library item is attached to. */+ listLibraryItemRooms: (params: {+ workspaceId: string;+ kind: LibraryKind;+ itemId: string;+ }): Promise<LibraryItemRoom[]> =>+ withWorkspaceSession(params.workspaceId, (server) =>+ fetchLibraryItemRooms(server, params.kind, params.itemId)+ ),++ /** The types a new reference may be given. */+ listReferenceTypes: (params: { workspaceId: string }): Promise<ReferenceTypeOption[]> =>+ withWorkspaceSession(params.workspaceId, (server) => fetchReferenceTypes(server)),+/** The rooms a room points at. */listLinkedRooms: (params: { workspaceId: string; roomId: string }): Promise<LinkedRoom[]> =>withWorkspaceSession(params.workspaceId, (server) => fetchLinkedRooms(server, params.roomId)),diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.tsindex 8c9025c82..6e8c9b97f 100644--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts@@ -9,6 +9,10 @@ import { RenameChatModal } from '@renderer/features/chats/components/chat-modalsimport { CommandPaletteModal } from '@renderer/features/command-palette/command-palette-modal';import { ConnectServiceModal } from '@renderer/features/connectors/connect-service-modal';import { DisconnectServiceDialog } from '@renderer/features/connectors/disconnect-dialog';+import {+ DeleteLibraryItemModal,+ NewLibraryItemModal,+} from '@renderer/features/library/library-modals';import { AddAgentModal } from '@renderer/features/locations/components/add-agent-modal/add-agent-modal';import { DeleteAgentModal } from '@renderer/features/locations/components/delete-agent-modal';import { ResetAgentModal } from '@renderer/features/locations/components/reset-agent-modal';@@ -81,6 +85,11 @@ export const modalRegistry = {}),saveTemplateModal: createModal(SaveTemplateModal, { size: 'sm', dismissOnOutsideClick: false }),confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),+ newLibraryItemModal: createModal(NewLibraryItemModal, {+ size: 'md',+ dismissOnOutsideClick: false,+ }),+ deleteLibraryItemModal: createModal(DeleteLibraryItemModal, { size: 'sm' }),deleteAgentModal: createModal(DeleteAgentModal, { size: 'sm' }),renameAgentModal: createModal(RenameAgentModal, { size: 'sm', dismissOnOutsideClick: false }),removeAgentConfigModal: createModal(RemoveAgentConfigModal, { size: 'sm' }),diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.tsindex 2deaf6f26..c22f5a6aa 100644--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts@@ -3,6 +3,8 @@ import { homeView } from '@renderer/app/home-view';import { adminView } from '@renderer/features/admin/admin-view';import { chatView } from '@renderer/features/chats/chat-view';import { connectorsView } from '@renderer/features/connectors/connectors-view';+import { libraryItemView } from '@renderer/features/library/library-item-view';+import { libraryView } from '@renderer/features/library/library-view';import { locationView } from '@renderer/features/locations/view';import { machineView } from '@renderer/features/machines/machine-view';import { managedAgentView } from '@renderer/features/managed-agents/managed-agent-view';@@ -27,7 +29,7 @@ import type { ViewIdName } from '@shared/core/views/view-ids';// Switch Console views: agents-at-a-location (location), sessions (session), home, settings,// and a connected Switch gateway's workspace — its Home (server) plus that-// server's agents and rooms. Automations, library, skills, and mcp were removed.+// server's agents, rooms and library. Automations, skills, and mcp were removed.export const views = {home: homeView,location: locationView,@@ -45,6 +47,8 @@ export const views = {remoteHosts: remoteHostsView,remoteHost: remoteHostView,templateImport: templateImportView,+ library: libraryView,+ libraryItem: libraryItemView,templates: templatesView,templateDetail: templateDetailView,templateUse: templateUseView,diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-card.tsx b/console/apps/switch-console-desktop/src/renderer/features/library/library-card.tsxnew file mode 100644index 000000000..11aac0d0c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-card.tsx@@ -0,0 +1,114 @@+import { DoorOpen, FileText, Link2, MoreVertical, Trash2 } from 'lucide-react';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@renderer/lib/ui/dropdown-menu';+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';+import type { LibraryItem } from '@shared/core/switch-servers/library';+import {+ ACCESS_SHORT,+ accessOf,+ LIBRARY_ACCESS_OPTIONS,+ ownerText,+ roomsText,+} from './library-model';++/**+ * One reference or document on the Library page. The whole card opens it; the+ * menu at its top right deletes it, and is there only for its owner and admins.+ * A reference's links stay on its page: they may be private.+ */+export function LibraryCard({+ item,+ viewerId,+ showYours,+ onOpen,+ onDelete,+}: {+ item: LibraryItem;+ viewerId: string | null;+ /** Marks your items "Yours": in All, where they sit among everyone's. */+ showYours: boolean;+ onOpen: () => void;+ /** Null when you may not delete it. */+ onDelete: (() => void) | null;+}) {+ const Icon = item.kind === 'references' ? Link2 : FileText;+ const mine = viewerId !== null && item.ownerId === viewerId;+ const access = accessOf(item);+ const owner = ownerText(item, viewerId);+ return (+ <div+ data-library-card={item.id}+ className="group relative flex h-full min-h-[150px] flex-col rounded-[11px] border border-border bg-background transition-colors hover:border-border-1"+ >+ <button+ type="button"+ aria-label={`Open ${item.name}`}+ className="focus-visible:ring-ring absolute inset-0 cursor-pointer rounded-[11px] focus-visible:ring-2 focus-visible:outline-none"+ onClick={onOpen}+ />+ <div className="pointer-events-none flex flex-1 flex-col gap-2 p-4">+ <div className={`flex items-center gap-2${onDelete ? ' pr-8' : ''}`}>+ <Icon className="size-4.5 shrink-0 text-foreground-muted" />+ <h3 className="min-w-0 truncate font-medium text-foreground">{item.name}</h3>+ {showYours && mine && <Badge variant="secondary">Yours</Badge>}+ </div>+ <p className="line-clamp-2 text-sm text-foreground-muted">+ {item.description || <span className="italic">No description.</span>}+ </p>+ <p className="flex min-w-0 items-center gap-1 text-xs text-foreground-muted">+ {item.typeLabel && (+ <>+ <span className="truncate">{item.typeLabel}</span>+ <span aria-hidden>·</span>+ </>+ )}+ <Tooltip>+ <TooltipTrigger+ render={<span className="pointer-events-auto relative">{ACCESS_SHORT[access]}</span>}+ />+ <TooltipContent>+ {LIBRARY_ACCESS_OPTIONS.find((option) => option.value === access)?.hint}+ </TooltipContent>+ </Tooltip>+ </p>+ <div className="mt-auto flex flex-col gap-1.5 border-t border-border pt-2.5 text-xs text-foreground-muted">+ {owner && <span className="truncate">{owner}</span>}+ <span className="flex items-center gap-1">+ <DoorOpen className="size-3.5" />+ {roomsText(item.attachedRoomsCount)}+ </span>+ </div>+ </div>+ {onDelete && (+ <div className="absolute top-2.5 right-2.5">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="sm"+ className="size-7 p-0"+ aria-label={`${item.name} actions`}+ >+ <MoreVertical className="size-4" />+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-max whitespace-nowrap">+ <DropdownMenuItem variant="destructive" onClick={onDelete}>+ <Trash2 className="size-4" />+ Delete…+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ )}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-form.ts b/console/apps/switch-console-desktop/src/renderer/features/library/library-form.tsnew file mode 100644index 000000000..3ac1dd02c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-form.ts@@ -0,0 +1,88 @@+import type {+ LibraryItem,+ LibraryItemChanges,+ LibraryItemInput,+ LibraryKind,+} from '@shared/core/switch-servers/library';+import { accessOf, type LibraryAccess, parseUrls, visibilityOf } from './library-model';++/** What the form holds while someone fills it in. */+export type LibraryForm = {+ name: string;+ description: string;+ instructions: string;+ access: LibraryAccess;+ type: string;+ /** A reference's links, one per line. */+ urlsText: string;+ content: string;+};++export function emptyForm(): LibraryForm {+ return {+ name: '',+ description: '',+ instructions: '',+ access: 'shared',+ type: '',+ urlsText: '',+ content: '',+ };+}++export function formOf(item: LibraryItem & { content?: string }): LibraryForm {+ return {+ name: item.name,+ description: item.description,+ instructions: item.instructions,+ access: accessOf(item),+ type: item.type ?? '',+ urlsText: item.urls.join('\n'),+ content: item.content ?? '',+ };+}++/** Why the form cannot be saved yet, or null when it can. */+export function formProblem(kind: LibraryKind, form: LibraryForm): string | null {+ if (!form.name.trim()) return 'Give it a name.';+ if (kind === 'references') {+ if (!form.type) return 'Pick a type.';+ if (parseUrls(form.urlsText).length === 0) return 'Add at least one link.';+ }+ return null;+}++export function inputOf(kind: LibraryKind, form: LibraryForm): LibraryItemInput {+ return {+ name: form.name.trim(),+ description: form.description.trim(),+ instructions: form.instructions.trim(),+ ...visibilityOf(form.access),+ ...(kind === 'references'+ ? { type: form.type, urls: parseUrls(form.urlsText) }+ : { content: form.content }),+ };+}++/** Only what changed, so a save does not overwrite someone else's edit to another field. */+export function changesOf(+ kind: LibraryKind,+ before: LibraryForm,+ after: LibraryForm+): LibraryItemChanges {+ const next = inputOf(kind, after);+ const prev = inputOf(kind, before);+ const changes: LibraryItemChanges = {};+ if (next.name !== prev.name) changes.name = next.name;+ if (next.description !== prev.description) changes.description = next.description;+ if (next.instructions !== prev.instructions) changes.instructions = next.instructions;+ if (after.access !== before.access) {+ changes.readVisibility = next.readVisibility;+ changes.writeVisibility = next.writeVisibility;+ }+ if (kind === 'references' && next.urls?.join('\n') !== prev.urls?.join('\n')) {+ changes.urls = next.urls;+ }+ if (kind === 'documents' && next.content !== prev.content) changes.content = next.content;+ return changes;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-item-form.tsx b/console/apps/switch-console-desktop/src/renderer/features/library/library-item-form.tsxnew file mode 100644index 000000000..504d38fe0--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-item-form.tsx@@ -0,0 +1,186 @@+import { useId, useState } from 'react';+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';+import { Input } from '@renderer/lib/ui/input';+import { MarkdownRenderer } from '@renderer/lib/ui/markdown-renderer';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';+import { Textarea } from '@renderer/lib/ui/textarea';+import type { LibraryKind, ReferenceTypeOption } from '@shared/core/switch-servers/library';+import type { LibraryForm } from './library-form';+import { LIBRARY_ACCESS_OPTIONS } from './library-model';++/**+ * The fields of a reference or a document, for creating one and for editing+ * it in place. A reference's type is chosen once: the server does not change it.+ */+export function LibraryItemFields({+ kind,+ form,+ onChange,+ types,+ typeLocked = false,+ canChangeAccess = true,+ autoFocus = false,+}: {+ kind: LibraryKind;+ form: LibraryForm;+ onChange: (next: LibraryForm) => void;+ /** The types a new reference may take; unused for a document. */+ types: readonly ReferenceTypeOption[];+ typeLocked?: boolean;+ canChangeAccess?: boolean;+ autoFocus?: boolean;+}) {+ const id = useId();+ const set = (patch: Partial<LibraryForm>) => onChange({ ...form, ...patch });+ const type = types.find((t) => t.type === form.type) ?? null;+ return (+ <FieldGroup>+ {kind === 'references' && (+ <Field>+ <FieldLabel htmlFor={`${id}-type`}>Type</FieldLabel>+ {typeLocked ? (+ <p className="text-sm text-foreground">{type?.displayName ?? form.type}</p>+ ) : (+ <Select value={form.type || null} onValueChange={(next) => set({ type: String(next) })}>+ <SelectTrigger id={`${id}-type`} aria-label="Type" className="w-full">+ <SelectValue>{type ? type.displayName : 'Pick a type'}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {types.map((t) => (+ <SelectItem key={t.type} value={t.type}>+ {t.displayName}+ {!t.isBuiltin && t.ownerName && (+ <span className="text-foreground-muted"> · by {t.ownerName}</span>+ )}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ </Field>+ )}+ {kind === 'references' && (+ <Field>+ <FieldLabel htmlFor={`${id}-urls`}>Links</FieldLabel>+ <Textarea+ id={`${id}-urls`}+ value={form.urlsText}+ onChange={(e) => set({ urlsText: e.target.value })}+ placeholder="https://… (one per line)"+ className="min-h-20 font-mono text-xs"+ />+ <p className="text-xs text-foreground-muted">{type?.valueHint || 'One link per line.'}</p>+ </Field>+ )}+ <Field>+ <FieldLabel htmlFor={`${id}-name`}>Name</FieldLabel>+ <Input+ id={`${id}-name`}+ value={form.name}+ onChange={(e) => set({ name: e.target.value })}+ autoFocus={autoFocus && kind === 'documents'}+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-description`}>+ Description <span className="text-foreground-muted">(optional)</span>+ </FieldLabel>+ <Input+ id={`${id}-description`}+ value={form.description}+ onChange={(e) => set({ description: e.target.value })}+ placeholder="What it is, in a line"+ />+ </Field>+ <Field>+ <FieldLabel htmlFor={`${id}-instructions`}>+ Instructions for agents <span className="text-foreground-muted">(optional)</span>+ </FieldLabel>+ <Textarea+ id={`${id}-instructions`}+ value={form.instructions}+ onChange={(e) => set({ instructions: e.target.value })}+ placeholder="When to use it, and anything to watch out for"+ className="min-h-16"+ />+ </Field>+ {kind === 'documents' && (+ <DocumentContentField+ value={form.content}+ onChange={(content) => set({ content })}+ inputId={`${id}-content`}+ />+ )}+ {canChangeAccess && (+ <Field>+ <FieldLabel>Who can see it</FieldLabel>+ <SegmentedControl+ value={form.access}+ onChange={(access) => set({ access })}+ options={LIBRARY_ACCESS_OPTIONS}+ ariaLabel="Who can see it"+ className="w-max"+ />+ <p className="text-xs text-foreground-muted">+ {LIBRARY_ACCESS_OPTIONS.find((o) => o.value === form.access)?.hint}+ </p>+ </Field>+ )}+ </FieldGroup>+ );+}++const CONTENT_MODES = [+ { value: 'write', label: 'Write' },+ { value: 'preview', label: 'Preview' },+] as const;++/** A document's markdown, written in plain text and previewed as it will read. */+export function DocumentContentField({+ value,+ onChange,+ inputId,+}: {+ value: string;+ onChange: (next: string) => void;+ inputId: string;+}) {+ const [mode, setMode] = useState<'write' | 'preview'>('write');+ return (+ <Field>+ <div className="flex items-center justify-between gap-2">+ <FieldLabel htmlFor={inputId}>Content</FieldLabel>+ <SegmentedControl+ value={mode}+ onChange={setMode}+ options={CONTENT_MODES}+ ariaLabel="Write or preview the content"+ />+ </div>+ {mode === 'write' ? (+ <Textarea+ id={inputId}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder="Markdown"+ className="max-h-[45vh] min-h-48 font-mono text-xs"+ />+ ) : (+ <div className="max-h-[45vh] min-h-48 overflow-y-auto rounded-md border border-border px-3 py-2">+ {value.trim() ? (+ <MarkdownRenderer content={value} variant="compact" />+ ) : (+ <p className="text-sm text-foreground-muted italic">Nothing written yet.</p>+ )}+ </div>+ )}+ </Field>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-item-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/library/library-item-view.tsxnew file mode 100644index 000000000..fccdf0383--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-item-view.tsx@@ -0,0 +1,642 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import {+ ArrowLeft,+ DoorOpen,+ ExternalLink,+ Library,+ Loader2,+ Package,+ Pencil,+ Plus,+ Search,+ Trash2,+ X,+} from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { type ReactNode, useState } from 'react';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { openRoom } from '@renderer/features/switch-rooms/open-room';+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { useReadableRoomsInWorkspace } from '@renderer/features/switch-servers/use-listed-rooms';+import { administersWorkspaceInScope } from '@renderer/features/switch-servers/workspace-admin';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { PageHeader } from '@renderer/lib/components/page-header';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { openExternalUrl } from '@renderer/lib/open-external';+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';+import { Badge } from '@renderer/lib/ui/badge';+import { Button } from '@renderer/lib/ui/button';+import {+ Dialog,+ DialogContent,+ DialogContentArea,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { Input } from '@renderer/lib/ui/input';+import { MarkdownRenderer } from '@renderer/lib/ui/markdown-renderer';+import type {+ LibraryDocument,+ LibraryItem,+ LibraryKind,+} from '@shared/core/switch-servers/library';+import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';+import { changesOf, formOf, formProblem, type LibraryForm } from './library-form';+import { LibraryItemFields } from './library-item-form';+import {+ accessOf,+ KIND_TEXT,+ LIBRARY_ACCESS_OPTIONS,+ libraryPermissions,+ ownerText,+} from './library-model';+import {+ invalidateLibrary,+ libraryItemKey,+ libraryRoomsKey,+ referenceTypesKey,+} from './library-queries';++function useViewParams() {+ return useParams('libraryItem').params;+}++const LibraryItemTitlebar = observer(function LibraryItemTitlebar() {+ const { serverId, kind, itemId } = useViewParams();+ const { navigate } = useNavigate();+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ // The panel reads the same item, so this is answered from its cache.+ const item = useQuery({+ queryKey: libraryItemKey(workspaceId ?? '', kind, itemId),+ queryFn: () =>+ rpc.workspaces.getLibraryItem({ workspaceId: workspaceId as string, kind, itemId }),+ enabled: workspaceId !== null,+ });+ return (+ <ServerSectionTitlebar+ serverId={serverId}+ icon={Library}+ label="Library"+ onSectionClick={() => navigate('library', { serverId, kind })}+ item={{ label: item.data?.name ?? KIND_TEXT[kind].Noun }}+ />+ );+});++/**+ * One reference or document: what it is, changed in place by whoever may, the+ * rooms it is attached to, and attaching it to more from here.+ */+const LibraryItemPanel = observer(function LibraryItemPanel() {+ const { serverId, kind, itemId } = useViewParams();+ const { navigate } = useNavigate();+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ const viewer = {+ id: switchServersStore.statusFor(serverId)?.user?.id ?? null,+ isAdmin: administersWorkspaceInScope(serverId),+ };+ const item = useQuery({+ queryKey: libraryItemKey(workspaceId ?? '', kind, itemId),+ queryFn: () =>+ rpc.workspaces.getLibraryItem({ workspaceId: workspaceId as string, kind, itemId }),+ enabled: workspaceId !== null,+ });+ const showDelete = useShowModal('deleteLibraryItemModal');+ const [editing, setEditing] = useState(false);+ const text = KIND_TEXT[kind];++ const back = (+ <Button+ size="sm"+ variant="ghost"+ className="-ml-2"+ onClick={() => navigate('library', { serverId, kind })}+ >+ <ArrowLeft className="size-4" /> All {text.title.toLowerCase()}+ </Button>+ );++ if (workspaceId === null || item.isError) {+ return (+ <Page>+ <PageHeader sticky title={text.Noun} back={back} />+ <p className="text-sm text-destructive">+ {workspaceId === null+ ? 'This server has no workspace yet, so its library cannot be read.'+ : failureText(item.error, `Could not read this ${text.noun}.`)}+ </p>+ </Page>+ );+ }+ if (item.isPending) {+ return (+ <div className="flex flex-1 items-center justify-center">+ <Loader2 className="size-5 animate-spin text-foreground-muted" />+ </div>+ );+ }++ const data = item.data;+ const permissions = libraryPermissions(data, viewer);+ const access = accessOf(data);+ const accessHint = LIBRARY_ACCESS_OPTIONS.find((o) => o.value === access)?.hint;+ const owner = ownerText(data, viewer.id);++ return (+ <Page>+ <PageHeader+ sticky+ title={data.name}+ description={+ <span className="flex flex-col gap-1.5">+ <span>{data.description || 'No description.'}</span>+ <span className="flex flex-wrap items-center gap-2 text-xs text-foreground-passive">+ {owner && (+ <>+ <span>{owner}</span>+ <span>·</span>+ </>+ )}+ <span>{accessHint}</span>+ </span>+ </span>+ }+ back={back}+ >+ <div className="flex flex-wrap items-center gap-2">+ <Badge variant="secondary">{data.typeLabel ?? text.Noun}</Badge>+ <span className="flex-1" />+ {permissions.canEdit && !editing && (+ <Button size="sm" variant="outline" onClick={() => setEditing(true)}>+ <Pencil className="size-3.5" />+ Edit+ </Button>+ )}+ {permissions.canDelete && (+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ showDelete({+ workspaceId,+ item: data,+ onSuccess: () => navigate('library', { serverId, kind }),+ })+ }+ >+ <Trash2 className="size-3.5" />+ Delete+ </Button>+ )}+ </div>+ </PageHeader>++ {editing ? (+ <EditForm+ workspaceId={workspaceId}+ item={data}+ canChangeAccess={permissions.canChangeAccess}+ onDone={() => setEditing(false)}+ />+ ) : (+ <ItemBody item={data} />+ )}++ <RoomsSection workspaceId={workspaceId} item={data} />+ {data.packageIds.length > 0 && <PackagesLine workspaceId={workspaceId} item={data} />}+ </Page>+ );+});++function Page({ children }: { children: ReactNode }) {+ return (+ <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">+ <div className="mx-auto w-full max-w-[820px] space-y-7 px-8 pb-10">{children}</div>+ </div>+ );+}++function Section({+ title,+ action,+ children,+}: {+ title: string;+ action?: ReactNode;+ children: ReactNode;+}) {+ return (+ <section aria-label={title} className="flex flex-col gap-2.5">+ <div className="flex min-h-7 items-center justify-between gap-3">+ <h2 className="text-sm font-semibold text-foreground">{title}</h2>+ {action}+ </div>+ {children}+ </section>+ );+}++function ItemBody({ item }: { item: LibraryItem | LibraryDocument }) {+ return (+ <>+ {item.kind === 'references' && (+ <Section title="Links">+ {item.urls.length === 0 ? (+ <p className="text-sm text-foreground-muted">No links.</p>+ ) : (+ <List>+ {item.urls.map((url) => (+ <button+ key={url}+ type="button"+ className="flex w-full cursor-pointer items-center gap-2 px-3.5 py-2.5 text-left text-sm hover:bg-background-1"+ onClick={() => void openExternalUrl(url, 'Could not open the link')}+ >+ <span className="min-w-0 flex-1 truncate font-mono text-xs">{url}</span>+ <ExternalLink className="size-3.5 shrink-0 text-foreground-muted" />+ </button>+ ))}+ </List>+ )}+ </Section>+ )}+ <Section title="Instructions for agents">+ {item.instructions ? (+ <p className="text-sm whitespace-pre-wrap text-foreground">{item.instructions}</p>+ ) : (+ <p className="text-sm text-foreground-muted">None.</p>+ )}+ </Section>+ {'content' in item && (+ <Section title="Content">+ {item.content.trim() ? (+ <div className="rounded-[11px] border border-border px-4 py-3">+ <MarkdownRenderer content={item.content} variant="compact" />+ </div>+ ) : (+ <p className="text-sm text-foreground-muted">Empty.</p>+ )}+ </Section>+ )}+ </>+ );+}++function EditForm({+ workspaceId,+ item,+ canChangeAccess,+ onDone,+}: {+ workspaceId: string;+ item: LibraryItem | LibraryDocument;+ canChangeAccess: boolean;+ onDone: () => void;+}) {+ const queryClient = useQueryClient();+ const [initial] = useState<LibraryForm>(() => formOf(item));+ const [form, setForm] = useState<LibraryForm>(initial);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const types = useQuery({+ queryKey: referenceTypesKey(workspaceId),+ queryFn: () => rpc.workspaces.listReferenceTypes({ workspaceId }),+ enabled: item.kind === 'references',+ });+ const changes = changesOf(item.kind, initial, form);+ const changed = Object.keys(changes).length > 0;+ const problem = formProblem(item.kind, form);++ const save = async () => {+ setSaving(true);+ setError(null);+ try {+ await rpc.workspaces.updateLibraryItem({+ workspaceId,+ kind: item.kind,+ itemId: item.id,+ changes,+ });+ await invalidateLibrary(queryClient, workspaceId, item.kind);+ toast({ title: 'Saved' });+ onDone();+ } catch (e) {+ setError(failureText(e, 'Could not save the changes.'));+ setSaving(false);+ }+ };++ return (+ <section+ aria-label="Edit"+ className="flex flex-col gap-4 rounded-[11px] border border-border p-4"+ >+ <LibraryItemFields+ kind={item.kind}+ form={form}+ onChange={setForm}+ types={types.data ?? []}+ typeLocked+ canChangeAccess={canChangeAccess}+ />+ {error && (+ <Alert variant="destructive">+ <AlertDescription>{error}</AlertDescription>+ </Alert>+ )}+ <div className="flex items-center justify-end gap-2">+ {problem && <span className="mr-auto text-xs text-foreground-muted">{problem}</span>}+ <Button size="sm" variant="outline" onClick={onDone} disabled={saving}>+ Cancel+ </Button>+ <Button+ size="sm"+ onClick={() => void save()}+ disabled={saving || !changed || problem !== null}+ >+ {saving ? 'Saving…' : 'Save'}+ </Button>+ </div>+ </section>+ );+}++const RoomsSection = observer(function RoomsSection({+ workspaceId,+ item,+}: {+ workspaceId: string;+ item: LibraryItem;+}) {+ const queryClient = useQueryClient();+ const rooms = useQuery({+ queryKey: libraryRoomsKey(workspaceId, item.kind, item.id),+ queryFn: () =>+ rpc.workspaces.listLibraryItemRooms({ workspaceId, kind: item.kind, itemId: item.id }),+ });+ const readable = useReadableRoomsInWorkspace(workspaceId);+ const summaries = new Map(readable.map((room) => [room.id, room]));+ const [picking, setPicking] = useState(false);+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const attachedIds = new Set((rooms.data ?? []).map((room) => room.roomId));+ const mayAttach = (room: RemoteRoomSummary) =>+ switchRoomsStore.roomPermissions(workspaceId, room).canWrite;+ const attachable = readable.filter(+ (room) => !room.archived && !attachedIds.has(room.id) && mayAttach(room)+ );++ async function detach(roomId: string, roomName: string) {+ setBusy(roomId);+ setError(null);+ try {+ await rpc.workspaces.setRoomResourceAttached({+ workspaceId,+ roomId,+ kind: item.kind,+ resourceId: item.id,+ attached: false,+ });+ await invalidateLibrary(queryClient, workspaceId, item.kind);+ } catch (cause) {+ setError(failureText(cause, `Could not detach it from ${roomName}.`));+ } finally {+ setBusy(null);+ }+ }++ return (+ <Section+ title="Rooms"+ action={+ attachable.length > 0 && (+ <Button size="sm" variant="outline" onClick={() => setPicking(true)}>+ <Plus className="size-3.5" />+ Attach to rooms+ </Button>+ )+ }+ >+ {rooms.isPending ? (+ <Loader2 className="size-4 animate-spin text-foreground-muted" />+ ) : rooms.isError ? (+ <p className="text-xs text-destructive">+ {failureText(rooms.error, 'Could not list the rooms it is in.')}+ </p>+ ) : rooms.data.length === 0 ? (+ <p className="text-sm text-foreground-muted">+ Not attached to any room you can see. Attach it and the agents there can use it.+ </p>+ ) : (+ <List>+ {rooms.data.map((room) => {+ const summary = summaries.get(room.roomId);+ const mayDetach =+ summary !== undefined &&+ switchRoomsStore.roomPermissions(workspaceId, summary).canUnlink;+ return (+ <div key={room.roomId} className="flex items-center gap-2 px-3.5 py-2.5">+ <button+ type="button"+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 text-left"+ onClick={() => void openRoom(room.roomId)}+ >+ <DoorOpen className="size-4 shrink-0 text-foreground-muted" />+ <span className="truncate text-sm text-foreground">{room.roomName}</span>+ </button>+ {mayDetach && (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={`Detach from ${room.roomName}`}+ title={`Detach from ${room.roomName}`}+ disabled={busy === room.roomId}+ onClick={() => void detach(room.roomId, room.roomName)}+ >+ {busy === room.roomId ? <Loader2 className="animate-spin" /> : <X />}+ </Button>+ )}+ </div>+ );+ })}+ </List>+ )}+ {error !== null && <p className="text-xs text-destructive">{error}</p>}+ {picking && (+ <AttachToRoomsDialog+ workspaceId={workspaceId}+ item={item}+ rooms={attachable}+ onClose={() => setPicking(false)}+ />+ )}+ </Section>+ );+});++/** The rooms you may attach it to that do not have it yet, each attached with a click. */+function AttachToRoomsDialog({+ workspaceId,+ item,+ rooms,+ onClose,+}: {+ workspaceId: string;+ item: LibraryItem;+ rooms: RemoteRoomSummary[];+ onClose: () => void;+}) {+ const queryClient = useQueryClient();+ const [filter, setFilter] = useState('');+ const [done, setDone] = useState<Set<string>>(new Set());+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const needle = filter.trim().toLowerCase();+ const shown = rooms+ .filter((room) => !done.has(room.id))+ .filter((room) => !needle || room.name.toLowerCase().includes(needle))+ .sort((a, b) => a.name.localeCompare(b.name));++ async function attach(room: RemoteRoomSummary) {+ setBusy(room.id);+ setError(null);+ try {+ await rpc.workspaces.setRoomResourceAttached({+ workspaceId,+ roomId: room.id,+ kind: item.kind,+ resourceId: item.id,+ attached: true,+ });+ setDone((current) => new Set(current).add(room.id));+ await invalidateLibrary(queryClient, workspaceId, item.kind);+ } catch (cause) {+ setError(failureText(cause, `Could not attach it to ${room.name}.`));+ } finally {+ setBusy(null);+ }+ }++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Attach {item.name} to rooms</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="flex flex-col gap-3 pt-0">+ <div className="relative">+ <Search className="absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-foreground-muted" />+ <Input+ autoFocus+ className="pl-8"+ placeholder="Search rooms…"+ value={filter}+ onChange={(event) => setFilter(event.target.value)}+ />+ </div>+ {shown.length === 0 ? (+ <p className="text-sm text-foreground-muted">+ {needle ? 'No room matches.' : 'It is in every room you can attach it to.'}+ </p>+ ) : (+ <div className="flex max-h-80 flex-col overflow-y-auto">+ {shown.map((room) => (+ <div key={room.id} className="flex items-center gap-2 py-1.5">+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm text-foreground">{room.name}</span>+ {room.description && (+ <span className="truncate text-xs text-foreground-muted">+ {room.description}+ </span>+ )}+ </span>+ <Button+ size="sm"+ variant="outline"+ disabled={busy !== null}+ onClick={() => void attach(room)}+ >+ {busy === room.id ? <Loader2 className="animate-spin" /> : 'Attach'}+ </Button>+ </div>+ ))}+ </div>+ )}+ {error !== null && <p className="text-xs text-destructive">{error}</p>}+ <div className="flex justify-end">+ <Button size="sm" variant="outline" onClick={onClose}>+ Done+ </Button>+ </div>+ </DialogContentArea>+ </DialogContent>+ </Dialog>+ );+}++function PackagesLine({ workspaceId, item }: { workspaceId: string; item: LibraryItem }) {+ const packages = useQuery({+ queryKey: ['library', workspaceId, 'packages'],+ queryFn: () => rpc.workspaces.listLibrary({ workspaceId, kind: 'packages' }),+ });+ const names = item.packageIds.map((id) => packages.data?.find((p) => p.id === id)?.name ?? null);+ const hidden = names.filter((name) => name === null).length;+ return (+ <Section title="In packages">+ <div className="flex flex-wrap items-center gap-1.5">+ {names+ .filter((name): name is string => name !== null)+ .map((name) => (+ <Badge key={name} variant="outline">+ <Package className="size-3" />+ {name}+ </Badge>+ ))}+ {hidden > 0 && !packages.isPending && (+ <span className="text-xs text-foreground-muted">+ {hidden === 1 ? 'and 1 you cannot see' : `and ${hidden} you cannot see`}+ </span>+ )}+ </div>+ </Section>+ );+}++function List({ children }: { children: ReactNode }) {+ return (+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">+ {children}+ </div>+ );+}++export const libraryItemView = {+ WrapView: ({+ children,+ }: {+ children: React.ReactNode;+ serverId: string;+ kind: LibraryKind;+ itemId: string;+ }) => <>{children}</>,+ TitlebarSlot: LibraryItemTitlebar,+ MainPanel: LibraryItemPanel,+ canActivate: (params: unknown): GuardResult => {+ const p =+ typeof params === 'object' && params !== null ? (params as Record<string, unknown>) : {};+ if (+ typeof p.serverId !== 'string' ||+ typeof p.itemId !== 'string' ||+ (p.kind !== 'references' && p.kind !== 'documents')+ ) {+ return { ok: false, redirect: 'home', discardParams: true };+ }+ return { ok: true };+ },+} satisfies ViewDefinition<{ serverId: string; kind: LibraryKind; itemId: string }>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-modals.tsx b/console/apps/switch-console-desktop/src/renderer/features/library/library-modals.tsxnew file mode 100644index 000000000..1e035e35e--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-modals.tsx@@ -0,0 +1,213 @@+import { useQuery, useQueryClient } from '@tanstack/react-query';+import { Loader2 } from 'lucide-react';+import { useState } from 'react';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';+import { Button } from '@renderer/lib/ui/button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';+import { ModalLayout } from '@renderer/lib/ui/modal-layout';+import type { LibraryItem, LibraryKind } from '@shared/core/switch-servers/library';+import { emptyForm, formProblem, inputOf, type LibraryForm } from './library-form';+import { LibraryItemFields } from './library-item-form';+import { KIND_TEXT } from './library-model';+import { invalidateLibrary, libraryRoomsKey, referenceTypesKey } from './library-queries';++type NewProps = BaseModalProps<LibraryItem> & { workspaceId: string; kind: LibraryKind };++/** Add a reference or a document to the workspace's library. */+export function NewLibraryItemModal({ workspaceId, kind, onSuccess, onClose }: NewProps) {+ const queryClient = useQueryClient();+ const [form, setForm] = useState<LibraryForm>(emptyForm);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const types = useQuery({+ queryKey: referenceTypesKey(workspaceId),+ queryFn: () => rpc.workspaces.listReferenceTypes({ workspaceId }),+ enabled: kind === 'references',+ });+ const text = KIND_TEXT[kind];+ const problem = formProblem(kind, form);++ const save = async () => {+ setSaving(true);+ setError(null);+ try {+ const created = await rpc.workspaces.createLibraryItem({+ workspaceId,+ kind,+ input: inputOf(kind, form),+ });+ await invalidateLibrary(queryClient, workspaceId, kind);+ toast({ title: `"${created.name}" added to the library` });+ onSuccess(created);+ } catch (e) {+ setError(failureText(e, `Could not add the ${text.noun}.`));+ setSaving(false);+ }+ };++ return (+ <ModalLayout+ header={+ <DialogHeader showCloseButton={!saving}>+ <DialogTitle>New {text.noun}</DialogTitle>+ </DialogHeader>+ }+ footer={+ <DialogFooter>+ {problem && form.name.trim() && (+ <span className="mr-auto self-center text-xs text-foreground-muted">{problem}</span>+ )}+ <Button type="button" variant="outline" onClick={onClose} disabled={saving}>+ Cancel+ </Button>+ <Button type="button" onClick={() => void save()} disabled={saving || problem !== null}>+ {saving ? 'Adding…' : `Add ${text.noun}`}+ </Button>+ </DialogFooter>+ }+ >+ <DialogContentArea className="max-h-[calc(100dvh-2rem-var(--modal-chrome,10rem))] gap-4 overflow-y-auto">+ {kind === 'references' && types.isError ? (+ <Alert variant="destructive">+ <AlertDescription>+ {failureText(types.error, 'Could not read the reference types.')}+ </AlertDescription>+ </Alert>+ ) : (+ <LibraryItemFields+ kind={kind}+ form={form}+ onChange={setForm}+ types={types.data ?? []}+ autoFocus+ />+ )}+ {error && (+ <Alert variant="destructive">+ <AlertDescription>{error}</AlertDescription>+ </Alert>+ )}+ </DialogContentArea>+ </ModalLayout>+ );+}++type DeleteProps = BaseModalProps<void> & {+ workspaceId: string;+ item: Pick<LibraryItem, 'id' | 'kind' | 'name' | 'packageIds'>;+};++/**+ * Asks before deleting a library item, naming what it comes out of: every room+ * it is attached to and every package it is in, for everyone.+ */+export function DeleteLibraryItemModal({ workspaceId, item, onSuccess, onClose }: DeleteProps) {+ const queryClient = useQueryClient();+ const [deleting, setDeleting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const rooms = useQuery({+ queryKey: libraryRoomsKey(workspaceId, item.kind, item.id),+ queryFn: () =>+ rpc.workspaces.listLibraryItemRooms({ workspaceId, kind: item.kind, itemId: item.id }),+ });+ const packages = useQuery({+ queryKey: ['library', workspaceId, 'packages'],+ queryFn: () => rpc.workspaces.listLibrary({ workspaceId, kind: 'packages' }),+ enabled: item.packageIds.length > 0,+ });+ const packageNames = item.packageIds.map(+ (id) => packages.data?.find((p) => p.id === id)?.name ?? 'a package you cannot see'+ );+ const noun = KIND_TEXT[item.kind].noun;++ const remove = async () => {+ setDeleting(true);+ setError(null);+ try {+ await rpc.workspaces.deleteLibraryItem({ workspaceId, kind: item.kind, itemId: item.id });+ await invalidateLibrary(queryClient, workspaceId, item.kind);+ toast({ title: `"${item.name}" deleted` });+ onSuccess();+ } catch (e) {+ setError(failureText(e, `Could not delete the ${noun}.`));+ setDeleting(false);+ }+ };++ return (+ <ModalLayout+ header={+ <DialogHeader showCloseButton={!deleting}>+ <DialogTitle>Delete {item.name}?</DialogTitle>+ </DialogHeader>+ }+ footer={+ <DialogFooter>+ <Button type="button" variant="outline" onClick={onClose} disabled={deleting}>+ Cancel+ </Button>+ <Button+ type="button"+ variant="destructive"+ onClick={() => void remove()}+ disabled={deleting || rooms.isPending}+ >+ {deleting ? 'Deleting…' : 'Delete'}+ </Button>+ </DialogFooter>+ }+ >+ <DialogContentArea className="gap-3">+ <p className="text-sm text-foreground-muted">+ The {noun} is deleted for everyone. This cannot be undone.+ </p>+ {rooms.isPending ? (+ <Loader2 className="size-4 animate-spin text-foreground-muted" />+ ) : rooms.isError ? (+ <p className="text-xs text-destructive">+ {failureText(rooms.error, 'Could not list the rooms it is in.')}+ </p>+ ) : rooms.data.length > 0 ? (+ <WhatItLeaves+ title="It is removed from these rooms:"+ names={rooms.data.map((r) => r.roomName)}+ />+ ) : (+ <p className="text-sm text-foreground-muted">+ It is not attached to any room you can see.+ </p>+ )}+ {packageNames.length > 0 && (+ <WhatItLeaves title="And from these packages:" names={packageNames} />+ )}+ {error && (+ <Alert variant="destructive">+ <AlertDescription>{error}</AlertDescription>+ </Alert>+ )}+ </DialogContentArea>+ </ModalLayout>+ );+}++function WhatItLeaves({ title, names }: { title: string; names: string[] }) {+ return (+ <div className="flex flex-col gap-1 text-sm">+ <span className="text-foreground">{title}</span>+ <ul className="max-h-40 list-disc overflow-y-auto pl-5 text-foreground-muted">+ {names.map((name, i) => (+ <li key={`${name}-${i}`}>{name}</li>+ ))}+ </ul>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-model.test.ts b/console/apps/switch-console-desktop/src/renderer/features/library/library-model.test.tsnew file mode 100644index 000000000..6e168875d--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-model.test.ts@@ -0,0 +1,168 @@+import { describe, expect, it } from 'vitest';+import type { LibraryItem } from '@shared/core/switch-servers/library';+import { changesOf, emptyForm, formOf, formProblem, inputOf } from './library-form';+import {+ accessOf,+ filterLibraryItems,+ libraryPermissions,+ NO_LIBRARY_FILTER,+ parseUrls,+ typeOptions,+ visibilityOf,+} from './library-model';++function item(over: Partial<LibraryItem> = {}): LibraryItem {+ return {+ id: 'ref-1',+ kind: 'references',+ name: 'Switch repo',+ description: 'The code',+ instructions: '',+ ownerId: 'u1',+ ownerName: 'Ada',+ readVisibility: 'public',+ writeVisibility: 'private',+ type: 'github',+ typeLabel: 'GitHub',+ urls: ['https://github.com/acme/switch'],+ attachedRoomsCount: 0,+ packageIds: [],+ createdAt: '2026-11-01',+ ...over,+ };+}++describe('access', () => {+ it('reads the two flags as one of three settings, and back', () => {+ for (const access of ['private', 'shared', 'open'] as const) {+ expect(accessOf(visibilityOf(access))).toBe(access);+ }+ // Private to read is private, whatever writing says.+ expect(accessOf({ readVisibility: 'private', writeVisibility: 'public' })).toBe('private');+ });+});++describe('libraryPermissions', () => {+ it('lets the owner do everything', () => {+ expect(libraryPermissions(item(), { id: 'u1', isAdmin: false })).toEqual({+ canEdit: true,+ canDelete: true,+ canChangeAccess: true,+ });+ });++ it('lets an admin do everything with someone else’s', () => {+ expect(libraryPermissions(item(), { id: 'u9', isAdmin: true }).canDelete).toBe(true);+ });++ it('lets anyone change an open item, but only its owner delete it or change who sees it', () => {+ expect(+ libraryPermissions(item({ writeVisibility: 'public' }), { id: 'u2', isAdmin: false })+ ).toEqual({ canEdit: true, canDelete: false, canChangeAccess: false });+ });++ it('lets nobody else change a shared item', () => {+ expect(libraryPermissions(item(), { id: 'u2', isAdmin: false }).canEdit).toBe(false);+ });++ it('offers nothing to a viewer it does not know', () => {+ expect(+ libraryPermissions(item({ writeVisibility: 'public' }), { id: null, isAdmin: false })+ ).toEqual({ canEdit: false, canDelete: false, canChangeAccess: false });+ });+});++describe('filterLibraryItems', () => {+ const items = [+ item({ id: 'a', name: 'Zeta', ownerId: 'u1' }),+ item({ id: 'b', name: 'alpha', ownerId: 'u2', type: 'jira', typeLabel: 'Jira' }),+ item({ id: 'c', name: 'Beta', description: 'release notes', ownerId: 'u2' }),+ ];++ it('sorts by name', () => {+ expect(filterLibraryItems(items, NO_LIBRARY_FILTER, 'u1').map((i) => i.id)).toEqual([+ 'b',+ 'c',+ 'a',+ ]);+ });++ it('keeps yours, a type, or what matches the search', () => {+ expect(+ filterLibraryItems(items, { ...NO_LIBRARY_FILTER, mineOnly: true }, 'u1').map((i) => i.id)+ ).toEqual(['a']);+ expect(+ filterLibraryItems(items, { ...NO_LIBRARY_FILTER, type: 'jira' }, 'u1').map((i) => i.id)+ ).toEqual(['b']);+ expect(+ filterLibraryItems(items, { ...NO_LIBRARY_FILTER, query: ' RELEASE ' }, 'u1').map((i) => i.id)+ ).toEqual(['c']);+ });++ it('shows nothing as yours to a viewer it does not know', () => {+ expect(filterLibraryItems(items, { ...NO_LIBRARY_FILTER, mineOnly: true }, null)).toEqual([]);+ });++ it('offers each type once, by its name', () => {+ expect(typeOptions(items)).toEqual([+ { value: 'github', label: 'GitHub' },+ { value: 'jira', label: 'Jira' },+ ]);+ });+});++describe('the form', () => {+ it('takes links one per line, without blanks or surrounding space', () => {+ expect(parseUrls(' https://a.example \n\n https://b.example\n')).toEqual([+ 'https://a.example',+ 'https://b.example',+ ]);+ });++ it('asks for a name, and for a reference a type and a link', () => {+ expect(formProblem('documents', emptyForm())).toBe('Give it a name.');+ expect(formProblem('documents', { ...emptyForm(), name: 'Notes' })).toBeNull();+ expect(formProblem('references', { ...emptyForm(), name: 'Repo' })).toBe('Pick a type.');+ expect(formProblem('references', { ...emptyForm(), name: 'Repo', type: 'github' })).toBe(+ 'Add at least one link.'+ );+ });++ it('sends a reference its links and a document its content, trimmed', () => {+ const form = {+ ...emptyForm(),+ name: ' Repo ',+ type: 'github',+ urlsText: 'https://a.example',+ content: 'ignored',+ };+ expect(inputOf('references', form)).toEqual({+ name: 'Repo',+ description: '',+ instructions: '',+ readVisibility: 'public',+ writeVisibility: 'private',+ type: 'github',+ urls: ['https://a.example'],+ });+ expect(inputOf('documents', { ...form, access: 'private' })).toMatchObject({+ readVisibility: 'private',+ content: 'ignored',+ });+ });++ it('sends only what changed', () => {+ const before = formOf(item());+ expect(changesOf('references', before, before)).toEqual({});+ expect(changesOf('references', before, { ...before, description: 'New' })).toEqual({+ description: 'New',+ });+ expect(changesOf('references', before, { ...before, access: 'open' })).toEqual({+ readVisibility: 'public',+ writeVisibility: 'public',+ });+ expect(+ changesOf('references', before, { ...before, urlsText: `${before.urlsText}\nhttps://b` })+ ).toEqual({ urls: ['https://github.com/acme/switch', 'https://b'] });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-model.ts b/console/apps/switch-console-desktop/src/renderer/features/library/library-model.tsnew file mode 100644index 000000000..1e9676cbe--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-model.ts@@ -0,0 +1,147 @@+import type {+ LibraryItem,+ LibraryKind,+ LibraryVisibility,+} from '@shared/core/switch-servers/library';++/** The three settings a library item can have, as one choice rather than two flags. */+export type LibraryAccess = 'private' | 'shared' | 'open';++export const LIBRARY_ACCESS_OPTIONS: { value: LibraryAccess; label: string; hint: string }[] = [+ { value: 'private', label: 'Private', hint: 'Only you and admins can see it or attach it.' },+ {+ value: 'shared',+ label: 'Shared',+ hint: 'Everyone on the workspace can see it and attach it to rooms. Only you change it.',+ },+ {+ value: 'open',+ label: 'Open',+ hint: 'Everyone on the workspace can see it, attach it and change it.',+ },+];++export const ACCESS_SHORT: Record<LibraryAccess, string> = {+ private: 'Private',+ shared: 'Shared',+ open: 'Open',+};++export function accessOf(item: {+ readVisibility: LibraryVisibility;+ writeVisibility: LibraryVisibility;+}): LibraryAccess {+ if (item.readVisibility === 'private') return 'private';+ return item.writeVisibility === 'public' ? 'open' : 'shared';+}++export function visibilityOf(access: LibraryAccess): {+ readVisibility: LibraryVisibility;+ writeVisibility: LibraryVisibility;+} {+ return {+ readVisibility: access === 'private' ? 'private' : 'public',+ writeVisibility: access === 'open' ? 'public' : 'private',+ };+}++/** Who is looking: their id, and whether they administer the workspace. */+export type Viewer = { id: string | null; isAdmin: boolean };++/**+ * What the viewer may do with an item, by the server's rule: its owner and+ * admins change and delete it; anyone changes an open one. The server sends no+ * answer of its own, so this mirrors it to keep from offering what it would+ * refuse; the server still checks every change.+ */+export function libraryPermissions(+ item: Pick<LibraryItem, 'ownerId' | 'writeVisibility'>,+ viewer: Viewer+): { canEdit: boolean; canDelete: boolean; canChangeAccess: boolean } {+ const owns = viewer.isAdmin || (viewer.id !== null && item.ownerId === viewer.id);+ return {+ canEdit: owns || (viewer.id !== null && item.writeVisibility === 'public'),+ canDelete: owns,+ // Access decides who else may change it, so it stays with the owner and admins.+ canChangeAccess: owns,+ };+}++export const KIND_TEXT: Record<+ LibraryKind,+ { title: string; noun: string; Noun: string; none: string }+> = {+ references: {+ title: 'References',+ noun: 'reference',+ Noun: 'Reference',+ none: 'No references here yet. Add one to point your agents at a repository, a doc or a page.',+ },+ documents: {+ title: 'Documents',+ noun: 'document',+ Noun: 'Document',+ none: 'No documents here yet. Write one to give your agents notes or instructions to share.',+ },+};++export type LibraryFilter = {+ mineOnly: boolean;+ query: string;+ /** A reference type slug, or null for any. */+ type: string | null;+};++export const NO_LIBRARY_FILTER: LibraryFilter = { mineOnly: false, query: '', type: null };++/** The items the filter row lets through, by name. */+export function filterLibraryItems(+ items: readonly LibraryItem[],+ filter: LibraryFilter,+ viewerId: string | null+): LibraryItem[] {+ const needle = filter.query.trim().toLowerCase();+ return items+ .filter((item) => !filter.mineOnly || (viewerId !== null && item.ownerId === viewerId))+ .filter((item) => filter.type === null || item.type === filter.type)+ .filter(+ (item) =>+ needle.length === 0 ||+ item.name.toLowerCase().includes(needle) ||+ item.description.toLowerCase().includes(needle) ||+ (item.typeLabel ?? '').toLowerCase().includes(needle)+ )+ .sort((a, b) => a.name.localeCompare(b.name));+}++/** The reference types the items carry, for the type filter. */+export function typeOptions(items: readonly LibraryItem[]): { value: string; label: string }[] {+ const seen = new Map<string, string>();+ for (const item of items) {+ if (item.type !== null && !seen.has(item.type))+ seen.set(item.type, item.typeLabel ?? item.type);+ }+ return [...seen.entries()]+ .map(([value, label]) => ({ value, label }))+ .sort((a, b) => a.label.localeCompare(b.label));+}++/** The links typed into a reference, one per line, without blanks or surrounding space. */+export function parseUrls(text: string): string[] {+ return text+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+}++export function ownerText(+ item: Pick<LibraryItem, 'ownerId' | 'ownerName'>,+ viewerId: string | null+) {+ if (viewerId !== null && item.ownerId === viewerId) return 'Owned by you';+ return item.ownerName ? `Owned by ${item.ownerName}` : null;+}++export function roomsText(count: number): string {+ return count === 0 ? 'In no rooms' : count === 1 ? 'In 1 room' : `In ${count} rooms`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-queries.ts b/console/apps/switch-console-desktop/src/renderer/features/library/library-queries.tsnew file mode 100644index 000000000..19483a4f5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-queries.ts@@ -0,0 +1,42 @@+import type { QueryClient } from '@tanstack/react-query';+import type { LibraryKind } from '@shared/core/switch-servers/library';++export const libraryItemsKey = (workspaceId: string, kind: LibraryKind) => [+ 'library-items',+ workspaceId,+ kind,+];++export const libraryItemKey = (workspaceId: string, kind: LibraryKind, itemId: string) => [+ 'library-item',+ workspaceId,+ kind,+ itemId,+];++export const libraryRoomsKey = (workspaceId: string, kind: LibraryKind, itemId: string) => [+ 'library-item-rooms',+ workspaceId,+ kind,+ itemId,+];++export const referenceTypesKey = (workspaceId: string) => ['reference-types', workspaceId];++/**+ * Everything that shows library items of a kind reads again after one changes:+ * the Library page, an item's page, and what a room's Attach dialog offers.+ */+export async function invalidateLibrary(+ queryClient: QueryClient,+ workspaceId: string,+ kind: LibraryKind+): Promise<void> {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ['library-items', workspaceId, kind] }),+ queryClient.invalidateQueries({ queryKey: ['library-item', workspaceId, kind] }),+ queryClient.invalidateQueries({ queryKey: ['library-item-rooms', workspaceId, kind] }),+ queryClient.invalidateQueries({ queryKey: ['library', workspaceId, kind] }),+ queryClient.invalidateQueries({ queryKey: ['room-resources', workspaceId] }),+ ]);+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/library-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/library/library-view.tsxnew file mode 100644index 000000000..463e8b184--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/library/library-view.tsx@@ -0,0 +1,221 @@+import { useQuery } from '@tanstack/react-query';+import { FileText, Library, Link2, Plus } from 'lucide-react';+import { observer } from 'mobx-react-lite';+import { useEffect, useState } from 'react';+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { ServerPage, ServerTableEmpty } from '@renderer/features/switch-servers/server-page';+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';+import { administersWorkspaceInScope } from '@renderer/features/switch-servers/workspace-admin';+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { FilterSelect } from '@renderer/lib/components/filter-select';+import { LIST_PAGE_WIDTH, ListToolbar } from '@renderer/lib/components/list-toolbar';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';+import { useShowModal } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { SearchInput } from '@renderer/lib/ui/search-input';+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';+import type { LibraryItem, LibraryKind } from '@shared/core/switch-servers/library';+import { LibraryCard } from './library-card';+import {+ filterLibraryItems,+ KIND_TEXT,+ libraryPermissions,+ NO_LIBRARY_FILTER,+ typeOptions,+} from './library-model';+import { libraryItemsKey } from './library-queries';++function useViewParams() {+ return useParams('library').params;+}++const LibraryTitlebar = observer(function LibraryTitlebar() {+ return (+ <ServerSectionTitlebar serverId={useViewParams().serverId} icon={Library} label="Library" />+ );+});++const KINDS = [+ { value: 'references', label: 'References', icon: Link2 },+ { value: 'documents', label: 'Documents', icon: FileText },+] as const satisfies readonly { value: LibraryKind; label: string; icon: typeof Link2 }[];++const SCOPES = [+ { value: 'all', label: 'All' },+ { value: 'mine', label: 'Mine' },+] as const;++/**+ * The workspace's library: the references and documents anyone may attach to+ * a room, as cards. Each opens a page to change it, see the rooms it is in and+ * attach it to more.+ */+const LibraryPanel = observer(function LibraryPanel() {+ const { serverId, kind: initialKind } = useViewParams();+ const { navigate } = useNavigate();+ const showNew = useShowModal('newLibraryItemModal');+ const showDelete = useShowModal('deleteLibraryItemModal');+ const [kind, setKind] = useState<LibraryKind>(initialKind ?? 'references');+ // Coming back from an item's page lands on that item's kind.+ useEffect(() => {+ if (initialKind) setKind(initialKind);+ }, [initialKind]);+ const [filter, setFilter] = useState(NO_LIBRARY_FILTER);+ const workspaceId = workspacesStore.idOnServerInScope(serverId);+ const viewer = {+ id: switchServersStore.statusFor(serverId)?.user?.id ?? null,+ isAdmin: administersWorkspaceInScope(serverId),+ };+ const items = useQuery({+ queryKey: libraryItemsKey(workspaceId ?? '', kind),+ queryFn: () => rpc.workspaces.listLibraryItems({ workspaceId: workspaceId as string, kind }),+ enabled: workspaceId !== null,+ });+ const text = KIND_TEXT[kind];+ const all = items.data ?? [];+ const types = kind === 'references' ? typeOptions(all) : [];+ // A type picked on References means nothing on Documents.+ const applied = { ...filter, type: kind === 'references' ? filter.type : null };+ const shown = filterLibraryItems(all, applied, viewer.id);+ const filtering = applied.mineOnly || applied.query.trim() !== '' || applied.type !== null;++ const open = (item: LibraryItem) =>+ navigate('libraryItem', { serverId, kind: item.kind, itemId: item.id });+ const create = () => {+ if (workspaceId === null) return;+ showNew({ workspaceId, kind, onSuccess: (created: LibraryItem) => open(created) });+ };++ return (+ <ServerPage+ width={LIST_PAGE_WIDTH}+ title="Library"+ description="References and documents your agents can be given. Attach them to a room and every agent there can use them."+ action={+ <Button size="sm" disabled={workspaceId === null} onClick={create}>+ <Plus className="size-4" />+ New {text.noun}+ </Button>+ }+ >+ {workspaceId === null ? (+ <ServerTableEmpty>+ This server has no workspace yet, so its library cannot be read.+ </ServerTableEmpty>+ ) : (+ <div className="flex flex-col gap-4">+ <SegmentedControl+ ariaLabel="References or documents"+ value={kind}+ onChange={setKind}+ options={KINDS}+ className="w-max"+ />+ <ListToolbar+ scope={+ viewer.id !== null && (+ <SegmentedControl+ ariaLabel={`Whose ${text.title.toLowerCase()}`}+ value={filter.mineOnly ? 'mine' : 'all'}+ onChange={(next) => setFilter({ ...filter, mineOnly: next === 'mine' })}+ options={SCOPES}+ />+ )+ }+ search={+ <SearchInput+ containerClassName="w-full"+ className="h-8"+ value={filter.query}+ onChange={(e) => setFilter({ ...filter, query: e.target.value })}+ placeholder={`Search ${text.title.toLowerCase()}…`}+ aria-label={`Search ${text.title.toLowerCase()} by name and description`}+ />+ }+ filters={+ kind === 'references' &&+ types.length > 0 && (+ <FilterSelect+ label="Type"+ anyLabel="Any type"+ value={applied.type}+ options={types}+ onChange={(type) => setFilter({ ...filter, type })}+ />+ )+ }+ />+ {items.isPending ? (+ <p className="py-2 text-sm text-foreground-muted">Loading…</p>+ ) : items.isError ? (+ <div className="flex flex-col items-start gap-2 rounded-[11px] border border-border px-4 py-4">+ <p className="text-sm text-foreground-muted">+ {failureText(items.error, `Could not read the ${text.title.toLowerCase()}.`)}+ </p>+ <Button size="sm" variant="outline" onClick={() => void items.refetch()}>+ Try again+ </Button>+ </div>+ ) : shown.length === 0 ? (+ filtering ? (+ <p className="py-2 text-sm text-foreground-muted">+ {applied.mineOnly && all.length > 0 && !applied.query.trim() && !applied.type+ ? `None of these ${text.title.toLowerCase()} are yours.`+ : `No ${text.noun} matches.`}+ </p>+ ) : (+ <div className="flex flex-col items-start gap-3 rounded-[11px] border border-dashed border-border px-4 py-5">+ <p className="text-sm text-foreground-muted">{text.none}</p>+ <Button size="sm" variant="outline" onClick={create}>+ <Plus className="size-3.5" />+ New {text.noun}+ </Button>+ </div>+ )+ ) : (+ <div+ role="list"+ aria-label={text.title}+ className="grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-[14px]"+ >+ {shown.map((item) => (+ <div role="listitem" key={item.id}>+ <LibraryCard+ item={item}+ viewerId={viewer.id}+ showYours={!filter.mineOnly}+ onOpen={() => open(item)}+ onDelete={+ libraryPermissions(item, viewer).canDelete+ ? () => showDelete({ workspaceId, item })+ : null+ }+ />+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </ServerPage>+ );+});++export const libraryView = {+ WrapView: ({ children }: { children: React.ReactNode; serverId: string; kind?: LibraryKind }) => (+ <>{children}</>+ ),+ TitlebarSlot: LibraryTitlebar,+ MainPanel: LibraryPanel,+ canActivate: (params: unknown): GuardResult => {+ const serverId =+ typeof params === 'object' && params !== null+ ? (params as { serverId?: unknown }).serverId+ : undefined;+ if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };+ return { ok: true };+ },+} satisfies ViewDefinition<{ serverId: string; kind?: LibraryKind }>;diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.tsindex a827296d8..61e177611 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav-views.ts@@ -2,6 +2,7 @@ export type WorkspaceNavView =| 'server'| 'serverAgents'| 'serverRooms'+ | 'library'| 'templates'| 'connectors'| 'admin';@@ -21,6 +22,7 @@ export function workspaceNavViews(server: {'server','serverAgents','serverRooms',+ 'library','templates',...(server.serviceConnections ? (['connectors'] as const) : []),...(server.admin ? (['admin'] as const) : []),diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsxindex 95032e48b..640eb15a8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx@@ -3,6 +3,7 @@ import {DoorOpen,FileText,House,+ Library,type LucideIcon,Plug,Settings,@@ -40,6 +41,7 @@ export const WorkspaceNav = observer(function WorkspaceNav() {const { params: roomsParams } = useParams('serverRooms');const { params: connectorsParams } = useParams('connectors');const { params: templatesParams } = useParams('templates');+ const { params: libraryParams } = useParams('library');const { params: adminParams } = useParams('admin');const active = switchServersStore.activeServer;const health = useRoomHealth(active?.id ?? null);@@ -56,6 +58,7 @@ export const WorkspaceNav = observer(function WorkspaceNav() {server: { icon: House, label: 'Home', params: homeParams },serverAgents: { icon: Bot, label: 'Your Agents', params: agentsParams },serverRooms: { icon: DoorOpen, label: 'Rooms', params: roomsParams },+ library: { icon: Library, label: 'Library', params: libraryParams },templates: { icon: FileText, label: 'Templates', params: templatesParams },connectors: { icon: Plug, label: 'Connectors', params: connectorsParams },admin: { icon: ShieldCheck, label: 'Admin', params: adminParams },diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsxindex 8e709aa54..5f3dfe96e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-resources-panel.tsx@@ -1,5 +1,15 @@import { useQuery, useQueryClient } from '@tanstack/react-query';-import { ExternalLink, FileText, Link2, Loader2, Package, Plus, Search, X } from 'lucide-react';+import {+ ExternalLink,+ FileText,+ Library,+ Link2,+ Loader2,+ Package,+ Plus,+ Search,+ X,+} from 'lucide-react';import { observer } from 'mobx-react-lite';import { type ReactNode, useState } from 'react';import { opensAsConsoleChat } from '@renderer/features/chats/console-chat-redirect';@@ -19,6 +29,7 @@ import {DialogTitle,} from '@renderer/lib/ui/dialog';import { Input } from '@renderer/lib/ui/input';+import { MarkdownRenderer } from '@renderer/lib/ui/markdown-renderer';import type { RoomResource, RoomResourceKind } from '@shared/core/switch-servers/switch-servers';import { useRoomDetail } from './room-participants';import { attachableResources, resourcesByOrigin } from './room-resources';@@ -116,6 +127,8 @@ const ResourceSection = observer(function ResourceSection({canUnlink: boolean;}) {const queryClient = useQueryClient();+ const { navigate } = useNavigate();+ const serverId = workspacesStore.serverIdFor(workspaceId);const key = roomResourcesKey(workspaceId, roomId, kind);const attached = useQuery({queryKey: key,@@ -197,6 +210,11 @@ const ResourceSection = observer(function ResourceSection({? () => setReading(resource): null}+ onShowInLibrary={+ serverId !== null && kind !== 'packages'+ ? () => navigate('libraryItem', { serverId, kind, itemId: resource.id })+ : null+ }removeLabel={canUnlink ? `Detach ${resource.name}` : null}busy={busy === resource.id}onRemove={() => void detach(resource)}@@ -261,11 +279,14 @@ function ResourceRow({busy,confirm = false,onRemove,+ onShowInLibrary = null,}: {resource: RoomResource;/** The packages that brought it in, by name. */via: string[];onOpen: (() => void) | null;+ /** Opens its page in the Library; null for what has none there. */+ onShowInLibrary?: (() => void) | null;/** The remove button's label, or null for someone who may not remove it. */removeLabel: string | null;busy: boolean;@@ -310,6 +331,17 @@ function ResourceRow({) : (<div className="flex min-w-0 flex-1 items-center gap-3">{body}</div>)}+ {onShowInLibrary && (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={`Show ${resource.name} in the Library`}+ title="Show in the Library"+ onClick={onShowInLibrary}+ >+ <Library />+ </Button>+ )}{removeLabel && confirm && armed && (<span className="flex shrink-0 items-center gap-1"><span className="text-xs text-foreground-muted">Delete for everyone?</span>@@ -490,9 +522,13 @@ function DocumentDialog({{failureText(content.error, 'Could not read this document.')}</p>) : (- <pre className="rounded-md bg-background-1 p-3 font-mono text-xs whitespace-pre-wrap text-foreground">- {content.data.content}- </pre>+ <div className="rounded-md border border-border px-4 py-3">+ {content.data.content.trim() ? (+ <MarkdownRenderer content={content.data.content} variant="compact" />+ ) : (+ <p className="text-sm text-foreground-muted italic">Empty.</p>+ )}+ </div>)}</DialogContentArea></DialogContent>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsxindex 4e62cde6a..fd580ce03 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx@@ -9,6 +9,7 @@ import { useArchiveRoomConfirm } from '@renderer/features/switch-rooms/archive-rimport { openRoom } from '@renderer/features/switch-rooms/open-room';import { roomDetailKey } from '@renderer/features/switch-rooms/room-participants';import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';+import { FilterSelect } from '@renderer/lib/components/filter-select';import { LIST_PAGE_WIDTH, ListToolbar } from '@renderer/lib/components/list-toolbar';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';@@ -18,13 +19,6 @@ import { useShowModal } from '@renderer/lib/modal/modal-provider';import { Button } from '@renderer/lib/ui/button';import { SearchInput } from '@renderer/lib/ui/search-input';import { SegmentedControl } from '@renderer/lib/ui/segmented-control';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@renderer/lib/ui/select';import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';import { AppMark, RoomCard } from './room-card';import { allReadableRooms, isConsoleGroupChatSummary, withConsoleGroupChats } from './room-filters';@@ -65,8 +59,6 @@ const STATES = [{ value: 'archived', label: 'Archived' },] as const satisfies readonly { value: State; label: string }[];-const ANY = '__any__';-/*** The workspace's rooms as cards: yours by default, every room you can read* at a switch, and the archived ones at another. The same card whichever@@ -338,57 +330,6 @@ export function emptyText({: 'No rooms here yet. Create one to give your agents somewhere to work.';}-function FilterSelect({- label,- anyLabel,- value,- options,- onChange,-}: {- label: string;- anyLabel: string;- value: string | null;- options: { value: string; label: string; icon?: React.ReactNode }[];- onChange: (next: string | null) => void;-}) {- const current = options.find((option) => option.value === value);- return (- <Select- value={value ?? ANY}- onValueChange={(next) => onChange(next === ANY ? null : (next as string))}- >- <SelectTrigger size="sm" className="w-auto min-w-[150px]" aria-label={label}>- <SelectValue>- {current ? (- <span className="flex items-center gap-1.5">- {current.icon}- {current.label}- </span>- ) : (- anyLabel- )}- </SelectValue>- </SelectTrigger>- {/* As wide as its longest name, so two connections that differ only at the end stay told apart. */}- <SelectContent- align="start"- alignItemWithTrigger={false}- className="w-auto min-w-(--anchor-width)"- >- <SelectItem value={ANY}>{anyLabel}</SelectItem>- {options.map((option) => (- <SelectItem key={option.value} value={option.value}>- <span className="flex items-center gap-1.5">- {option.icon}- {option.label}- </span>- </SelectItem>- ))}- </SelectContent>- </Select>- );-}-export const serverRoomsView = {WrapView: ({ children }: { children: React.ReactNode; serverId: string }) => <>{children}</>,TitlebarSlot: ServerRoomsTitlebar,diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/filter-select.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/filter-select.tsxnew file mode 100644index 000000000..c15a006c2--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/filter-select.tsx@@ -0,0 +1,65 @@+import type { ReactNode } from 'react';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@renderer/lib/ui/select';++const ANY = '__any__';++/**+ * One narrowing filter on a list page's filter row: "any" first, then each+ * value it can take, so picking nothing and picking "any" read the same.+ */+export function FilterSelect({+ label,+ anyLabel,+ value,+ options,+ onChange,+}: {+ label: string;+ anyLabel: string;+ value: string | null;+ options: { value: string; label: string; icon?: ReactNode }[];+ onChange: (next: string | null) => void;+}) {+ const current = options.find((option) => option.value === value);+ return (+ <Select+ value={value ?? ANY}+ onValueChange={(next) => onChange(next === ANY ? null : (next as string))}+ >+ <SelectTrigger size="sm" className="w-auto min-w-[150px]" aria-label={label}>+ <SelectValue>+ {current ? (+ <span className="flex items-center gap-1.5">+ {current.icon}+ {current.label}+ </span>+ ) : (+ anyLabel+ )}+ </SelectValue>+ </SelectTrigger>+ {/* As wide as its longest name, so two connections that differ only at the end stay told apart. */}+ <SelectContent+ align="start"+ alignItemWithTrigger={false}+ className="w-auto min-w-(--anchor-width)"+ >+ <SelectItem value={ANY}>{anyLabel}</SelectItem>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ <span className="flex items-center gap-1.5">+ {option.icon}+ {option.label}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/library-view.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/library-view.test.tsxnew file mode 100644index 000000000..11039e2df--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/library-view.test.tsx@@ -0,0 +1,323 @@+/**+ * The Library: the workspace's references and documents as cards, with an+ * item's own page to change it and attach it to rooms. What is offered follows+ * the server's rule — the owner and admins change and delete, anyone changes+ * an open item.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { LibraryItem } from '@shared/core/switch-servers/library';++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++const state = vi.hoisted(() => ({+ params: {} as Record<string, unknown>,+ items: { references: [] as unknown[], documents: [] as unknown[] },+ item: null as unknown,+ rooms: [] as { roomId: string; roomName: string }[],+ admin: false,+}));+const rpcMock = vi.hoisted(() => ({+ listLibraryItems: vi.fn(),+ getLibraryItem: vi.fn(),+ updateLibraryItem: vi.fn(),+ listLibraryItemRooms: vi.fn(),+ listReferenceTypes: vi.fn(),+ listLibrary: vi.fn(),+ setRoomResourceAttached: vi.fn(),+}));+const showModal = vi.hoisted(() => vi.fn());+const navigate = vi.hoisted(() => vi.fn());++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: () => () => {} },+ rpc: { workspaces: rpcMock },+}));+vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useParams: () => ({ params: state.params }),+ useNavigate: () => ({ navigate }),+}));+vi.mock('@renderer/lib/modal/modal-provider', () => ({+ useShowModal: (id: string) => (args: unknown) => showModal(id, args),+ showModal: vi.fn(),+}));+vi.mock('@renderer/lib/hooks/useTheme', () => ({+ useTheme: () => ({ effectiveTheme: 'emlight' }),+}));+vi.mock('@renderer/lib/hooks/use-toast', () => ({ toast: () => {} }));+vi.mock('@renderer/features/switch-rooms/open-room', () => ({ openRoom: async () => {} }));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { idOnServerInScope: () => 'ws', serverIdFor: () => 'srv', activeId: 'ws' },+}));+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ servers: [{ id: 'srv', name: 'Server', managed: false }],+ statusFor: () => ({ connected: true, user: { id: 'me' } }),+ },+}));+vi.mock('@renderer/features/switch-servers/workspace-admin', () => ({+ administersWorkspaceInScope: () => state.admin,+}));+vi.mock('@renderer/features/switch-servers/use-listed-rooms', () => ({+ useReadableRoomsInWorkspace: () => [+ { id: 'room-1', name: 'design', description: '', archived: false, ownerId: 'me' },+ { id: 'room-2', name: 'support', description: '', archived: false, ownerId: 'me' },+ ],+}));+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({+ switchRoomsStore: {+ roomPermissions: () => ({ canWrite: true, canManage: true, canUnlink: true }),+ },+}));++import { libraryItemView } from '@renderer/features/library/library-item-view';+import { libraryView } from '@renderer/features/library/library-view';++function item(over: Partial<LibraryItem>): LibraryItem {+ return {+ id: 'ref-1',+ kind: 'references',+ name: 'Switch repo',+ description: 'The code',+ instructions: 'Read the README',+ ownerId: 'me',+ ownerName: 'Me',+ readVisibility: 'public',+ writeVisibility: 'private',+ type: 'github',+ typeLabel: 'GitHub',+ urls: ['https://github.com/acme/switch'],+ attachedRoomsCount: 1,+ packageIds: [],+ createdAt: '2026-11-01',+ ...over,+ };+}++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ state.admin = false;+ state.items = {+ references: [+ item({}),+ item({+ id: 'ref-2',+ name: 'Tracker',+ ownerId: 'bob',+ ownerName: 'Bob',+ type: 'jira',+ typeLabel: 'Jira',+ attachedRoomsCount: 0,+ }),+ ],+ documents: [+ item({ id: 'doc-1', kind: 'documents', name: 'Style guide', type: null, typeLabel: null }),+ ],+ };+ state.rooms = [{ roomId: 'room-1', roomName: 'design' }];+ for (const fn of Object.values(rpcMock)) fn.mockReset();+ rpcMock.listLibraryItems.mockImplementation(+ async ({ kind }: { kind: 'references' | 'documents' }) => state.items[kind]+ );+ rpcMock.getLibraryItem.mockImplementation(async () => state.item);+ rpcMock.listLibraryItemRooms.mockImplementation(async () => state.rooms);+ rpcMock.listReferenceTypes.mockResolvedValue([+ {+ type: 'github',+ displayName: 'GitHub',+ valueHint: 'Repositories',+ isBuiltin: true,+ ownerName: null,+ },+ ]);+ rpcMock.listLibrary.mockResolvedValue([]);+ rpcMock.updateLibraryItem.mockResolvedValue({});+ rpcMock.setRoomResourceAttached.mockResolvedValue(undefined);+ showModal.mockReset();+ navigate.mockReset();+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+});++async function render(Panel: React.ComponentType): Promise<void> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root.render(+ <QueryClientProvider client={client}>+ <Panel />+ </QueryClientProvider>+ )+ );+ await settle();+}++const settle = async () => {+ for (let i = 0; i < 6; i++) await act(async () => await Promise.resolve());+};+const button = (label: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === label);+const cardNames = () =>+ [...container.querySelectorAll('[data-library-card] h3')].map((h) => h.textContent);+const cardFor = (name: string) =>+ [...container.querySelectorAll<HTMLElement>('[data-library-card]')].find(+ (card) => card.querySelector('h3')?.textContent === name+ )!;++describe('the Library page', () => {+ beforeEach(() => {+ state.params = { serverId: 'srv' };+ });++ it('lists references as cards, saying whose each is, its access and its rooms', async () => {+ await render(libraryView.MainPanel);+ expect(cardNames()).toEqual(['Switch repo', 'Tracker']);+ const mine = cardFor('Switch repo').textContent;+ expect(mine).toContain('Yours');+ expect(mine).toContain('GitHub');+ expect(mine).toContain('Shared');+ expect(mine).toContain('Owned by you');+ expect(mine).toContain('In 1 room');+ expect(cardFor('Tracker').textContent).toContain('Owned by Bob');+ // A reference's links may be private: they stay on its page.+ expect(container.textContent).not.toContain('github.com/acme');+ });++ it('narrows to yours, and switches to documents', async () => {+ await render(libraryView.MainPanel);+ await act(async () => button('Mine')!.click());+ expect(cardNames()).toEqual(['Switch repo']);+ await act(async () => button('Documents')!.click());+ await settle();+ expect(cardNames()).toEqual(['Style guide']);+ expect(button('New document')).toBeDefined();+ });++ it('offers deleting only on what you own, unless you administer the workspace', async () => {+ await render(libraryView.MainPanel);+ expect(+ cardFor('Switch repo').querySelector('[aria-label="Switch repo actions"]')+ ).not.toBeNull();+ expect(cardFor('Tracker').querySelector('[aria-label="Tracker actions"]')).toBeNull();+ });++ it('lets an admin delete anyone’s', async () => {+ state.admin = true;+ await render(libraryView.MainPanel);+ expect(cardFor('Tracker').querySelector('[aria-label="Tracker actions"]')).not.toBeNull();+ });++ it('opens New reference for the shown kind', async () => {+ await render(libraryView.MainPanel);+ await act(async () => button('New reference')!.click());+ expect(showModal).toHaveBeenCalledWith(+ 'newLibraryItemModal',+ expect.objectContaining({ workspaceId: 'ws', kind: 'references' })+ );+ });++ it('says so when there is nothing yet', async () => {+ state.items.references = [];+ await render(libraryView.MainPanel);+ expect(container.textContent).toContain('No references here yet');+ });+});++describe('an item’s page', () => {+ beforeEach(() => {+ state.params = { serverId: 'srv', kind: 'references', itemId: 'ref-1' };+ });++ it('shows its links, instructions and rooms', async () => {+ state.item = item({});+ await render(libraryItemView.MainPanel);+ expect(container.textContent).toContain('https://github.com/acme/switch');+ expect(container.textContent).toContain('Read the README');+ expect(container.querySelector('[aria-label="Rooms"]')?.textContent).toContain('design');+ });++ it('saves only what changed', async () => {+ state.item = item({});+ await render(libraryItemView.MainPanel);+ await act(async () => button('Edit')!.click());+ const description = [...container.querySelectorAll('input')].find(+ (input) => input.value === 'The code'+ )!;+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;+ setter.call(description, 'All the code');+ description.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () => button('Save')!.click());+ await settle();+ expect(rpcMock.updateLibraryItem).toHaveBeenCalledWith({+ workspaceId: 'ws',+ kind: 'references',+ itemId: 'ref-1',+ changes: { description: 'All the code' },+ });+ });++ it('offers no edit or delete on someone else’s shared item', async () => {+ state.item = item({ ownerId: 'bob', ownerName: 'Bob' });+ await render(libraryItemView.MainPanel);+ expect(button('Edit')).toBeUndefined();+ expect(button('Delete')).toBeUndefined();+ });++ it('lets anyone edit an open item, but not delete it', async () => {+ state.item = item({ ownerId: 'bob', ownerName: 'Bob', writeVisibility: 'public' });+ await render(libraryItemView.MainPanel);+ expect(button('Edit')).toBeDefined();+ expect(button('Delete')).toBeUndefined();+ });++ it('attaches it to another room from here', async () => {+ state.item = item({});+ await render(libraryItemView.MainPanel);+ await act(async () => button('Attach to rooms')!.click());+ await settle();+ // design already has it; support does not.+ const dialog = document.querySelector('[data-slot="dialog-content"]')!;+ expect(dialog.textContent).toContain('support');+ expect(dialog.textContent).not.toContain('design');+ const attach = [...dialog.querySelectorAll('button')].find((b) => b.textContent === 'Attach')!;+ await act(async () => attach.click());+ await settle();+ expect(rpcMock.setRoomResourceAttached).toHaveBeenCalledWith({+ workspaceId: 'ws',+ roomId: 'room-2',+ kind: 'references',+ resourceId: 'ref-1',+ attached: true,+ });+ });++ it('renders a document’s content as markdown', async () => {+ state.params = { serverId: 'srv', kind: 'documents', itemId: 'doc-1' };+ state.item = {+ ...item({ id: 'doc-1', kind: 'documents', type: null, typeLabel: null, urls: [] }),+ content: '# Style\n\nUse **plain** words.',+ };+ await render(libraryItemView.MainPanel);+ const content = container.querySelector('[aria-label="Content"]')!;+ expect(content.textContent).toContain('Style');+ expect(content.textContent).not.toContain('# Style');+ expect(content.querySelector('strong')?.textContent).toBe('plain');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-resources-panel.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-resources-panel.test.tsxindex 3e9b4e22f..cf238a7be 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-resources-panel.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-resources-panel.test.tsx@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const listRoomResources = vi.hoisted(() => vi.fn());const setRoomResourceAttached = vi.hoisted(() => vi.fn());const listLinkedRooms = vi.hoisted(() => vi.fn());+const navigate = vi.hoisted(() => vi.fn());const permissions = vi.hoisted(() => ({value: { canWrite: true, canManage: false, canUnlink: true },}));@@ -44,6 +45,13 @@ vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({},}));+vi.mock('@renderer/lib/layout/navigation-provider', () => ({+ useNavigate: () => ({ navigate }),+}));+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({+ workspacesStore: { serverIdFor: () => 'srv-1', activeId: 'ws-1' },+}));+import { RoomResourcesPanel } from '@renderer/features/switch-rooms/room-resources-panel';const base = {@@ -218,4 +226,19 @@ describe('the Resources tab', () => {expect(el.querySelector('[aria-label^="Detach"]')).toBeNull();expect(el.querySelector('[aria-label^="Delete"]')).toBeNull();});++ it('opens a reference or document from the library on its Library page, not a room-only one', async () => {+ const el = await renderPanel();+ await act(async () =>+ el.querySelector<HTMLButtonElement>('[aria-label="Show Guide in the Library"]')!.click()+ );+ expect(navigate).toHaveBeenCalledWith('libraryItem', {+ serverId: 'srv-1',+ kind: 'documents',+ itemId: 'd-1',+ });+ expect(el.querySelector('[aria-label="Show Repo in the Library"]')).not.toBeNull();+ expect(el.querySelector('[aria-label="Show Standup notes in the Library"]')).toBeNull();+ expect(el.querySelector('[aria-label="Show Onboarding in the Library"]')).toBeNull();+ });});diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/library.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/library.tsnew file mode 100644index 000000000..a61531d30--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/library.ts@@ -0,0 +1,77 @@+/**+ * The workspace's library: references and documents anyone may attach to a+ * room, as the gateway's Resources pages show them. Packages bundle them and+ * join later.+ */++/** The library kinds the Library page lists. */+export type LibraryKind = 'references' | 'documents';++/** Who may read, or change, a library item: its owner (and admins) alone, or everyone. */+export type LibraryVisibility = 'private' | 'public';++/** One library item as the list and its page show it. */+export type LibraryItem = {+ id: string;+ kind: LibraryKind;+ name: string;+ description: string;+ /** What agents are told about using it. */+ instructions: string;+ ownerId: string;+ /** Null when the server could not name the owner. */+ ownerName: string | null;+ readVisibility: LibraryVisibility;+ writeVisibility: LibraryVisibility;+ /** A reference's type slug ("github"); null for a document. */+ type: string | null;+ /** A reference's type as people read it ("GitHub"); null for a document. */+ typeLabel: string | null;+ /** A reference's links; empty for a document. */+ urls: string[];+ attachedRoomsCount: number;+ /** The packages it is in, by id. */+ packageIds: string[];+ createdAt: string;+};++/** A document read in full. */+export type LibraryDocument = LibraryItem & { content: string };++/** A reference type a new reference may be given. */+export type ReferenceTypeOption = {+ type: string;+ displayName: string;+ /** What the links should point at, as the type describes it. */+ valueHint: string;+ isBuiltin: boolean;+ /** Who wrote a type of their own; null for a built-in one. */+ ownerName: string | null;+};++/** What a new library item is made of. */+export type LibraryItemInput = {+ name: string;+ description: string;+ instructions: string;+ readVisibility: LibraryVisibility;+ writeVisibility: LibraryVisibility;+ /** A reference's type. */+ type?: string;+ /** A reference's links. */+ urls?: string[];+ /** A document's content. */+ content?: string;+};++/** The fields of a library item to change; anything left out stays as it is. */+export type LibraryItemChanges = Partial<Omit<LibraryItemInput, 'type'>>;++/** What deleting a library item took with it. */+export type LibraryDeleteResult = {+ detachedRoomIds: string[];+ affectedPackageIds: string[];+};++/** A room a library item is attached to. */+export type LibraryItemRoom = { roomId: string; roomName: string };diff --git a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.tsindex aed7ce5ce..ce80fb66b 100644--- a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts+++ b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts@@ -24,6 +24,8 @@ export const VIEW_IDS = ['remoteHosts','remoteHost','templateImport',+ 'library',+ 'libraryItem','templates','templateDetail','templateUse',