Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Resources: reference types, with a slug people can get right

Simon Flack2ae8e1fc743f
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.ts
index aa64b365d..411df1d7f 100644
--- 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.ts
@@ -26,6 +26,10 @@ const {
addPackageMember,
fetchPackageMembers,
removePackageMember,
+ createReferenceType,
+ deleteReferenceType,
+ fetchManagedReferenceTypes,
+ updateReferenceType,
} = await import('./library-client');
const SERVER = {
@@ -204,9 +208,11 @@ describe('reading the library', () => {
expect(types[2]).toEqual({
type: 'wiki',
displayName: 'Wiki',
+ instructions: '',
valueHint: 'Pages',
isBuiltin: false,
ownerName: 'Bo',
+ ownerId: null,
});
});
});
@@ -366,3 +372,72 @@ describe('packages', () => {
});
});
});
+
+describe('reference types', () => {
+ const OWNED = {
+ type: 'linear',
+ display_name: 'Linear',
+ instructions: 'Use the Linear connector.',
+ value_schema: {},
+ value_hint: 'Issue links',
+ is_builtin: false,
+ owner_id: 'u1',
+ owner_name: 'Ada',
+ read_visibility: 'public',
+ write_visibility: 'private',
+ shadowed_by_builtin: false,
+ created_at: '2026-11-05T09:00:00+00:00',
+ };
+
+ it('reads the types the viewer may change, with their access', async () => {
+ fetchMock.mockImplementation(async () => jsonResponse([OWNED]));
+ const [type] = await fetchManagedReferenceTypes(SERVER);
+ expect(lastCall().url).toMatch(/\/gateway\/references\/reference-types\/owned$/);
+ expect(type).toMatchObject({
+ type: 'linear',
+ displayName: 'Linear',
+ instructions: 'Use the Linear connector.',
+ ownerId: 'u1',
+ readVisibility: 'public',
+ writeVisibility: 'private',
+ shadowedByBuiltin: false,
+ });
+ });
+
+ it('creates one with its slug, and changes only what is given', async () => {
+ fetchMock.mockImplementation(async () => jsonResponse(OWNED));
+ await createReferenceType(SERVER, {
+ type: 'linear',
+ displayName: 'Linear',
+ instructions: 'Use the Linear connector.',
+ valueHint: 'Issue links',
+ readVisibility: 'public',
+ writeVisibility: 'private',
+ });
+ expect(lastCall()).toEqual({
+ url: expect.stringMatching(/\/gateway\/references\/reference-types$/),
+ method: 'POST',
+ body: {
+ type: 'linear',
+ display_name: 'Linear',
+ instructions: 'Use the Linear connector.',
+ value_hint: 'Issue links',
+ read_visibility: 'public',
+ write_visibility: 'private',
+ },
+ });
+ await updateReferenceType(SERVER, 'linear', { valueHint: 'Links to issues' });
+ expect(lastCall()).toEqual({
+ url: expect.stringMatching(/\/reference-types\/linear$/),
+ method: 'PATCH',
+ body: { value_hint: 'Links to issues' },
+ });
+ });
+
+ it('deletes one by its slug', async () => {
+ fetchMock.mockImplementation(async () => jsonResponse({ deleted_type: 'linear' }));
+ await deleteReferenceType(SERVER, 'linear');
+ expect(lastCall()).toMatchObject({ method: 'DELETE' });
+ expect(lastCall().url).toMatch(/\/reference-types\/linear$/);
+ });
+});
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.ts
index e08175f35..7da87d388 100644
--- 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.ts
@@ -8,7 +8,10 @@ import type {
LibraryKind,
LibraryVisibility,
PackageMemberKind,
+ ManagedReferenceType,
PackageMemberRemoval,
+ ReferenceTypeChanges,
+ ReferenceTypeInput,
ReferenceTypeOption,
} from '@shared/core/switch-servers/library';
import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
@@ -178,30 +181,109 @@ export async function fetchLibraryItemRooms(
);
}
+type ReferenceTypeJson = {
+ type: string;
+ display_name: string;
+ instructions?: string;
+ value_hint?: string | null;
+ is_builtin?: boolean;
+ owner_id?: string | null;
+ owner_name?: string | null;
+ read_visibility?: string;
+ write_visibility?: string;
+ shadowed_by_builtin?: boolean;
+ created_at?: string;
+};
+
+function mapReferenceType(t: ReferenceTypeJson): ReferenceTypeOption {
+ return {
+ type: t.type,
+ displayName: t.display_name,
+ instructions: t.instructions ?? '',
+ valueHint: t.value_hint ?? '',
+ isBuiltin: t.is_builtin ?? false,
+ ownerName: t.owner_name ?? null,
+ ownerId: t.owner_id ?? null,
+ };
+}
+
+function mapManagedReferenceType(t: ReferenceTypeJson): ManagedReferenceType {
+ return {
+ ...mapReferenceType(t),
+ ownerId: t.owner_id ?? '',
+ readVisibility: visibility(t.read_visibility ?? 'private'),
+ writeVisibility: visibility(t.write_visibility ?? 'private'),
+ shadowedByBuiltin: t.shadowed_by_builtin ?? false,
+ createdAt: t.created_at ?? '',
+ };
+}
+
/** 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,
- }))
+ return ((await res.json()) as ReferenceTypeJson[])
+ .map(mapReferenceType)
.sort(
(a, b) =>
Number(b.isBuiltin) - Number(a.isBuiltin) || a.displayName.localeCompare(b.displayName)
);
}
+/** The types the viewer may change: their own, or every one for an admin. */
+export async function fetchManagedReferenceTypes(
+ server: SwitchServer
+): Promise<ManagedReferenceType[]> {
+ const res = await gatewayFetch(server, '/references/reference-types/owned', {
+ authenticated: true,
+ });
+ return ((await res.json()) as ReferenceTypeJson[]).map(mapManagedReferenceType);
+}
+
+function typeBody(input: ReferenceTypeChanges & { type?: string }) {
+ return {
+ ...(input.type !== undefined ? { type: input.type } : {}),
+ ...(input.displayName !== undefined ? { display_name: input.displayName } : {}),
+ ...(input.instructions !== undefined ? { instructions: input.instructions } : {}),
+ ...(input.valueHint !== undefined ? { value_hint: input.valueHint } : {}),
+ ...(input.readVisibility !== undefined ? { read_visibility: input.readVisibility } : {}),
+ ...(input.writeVisibility !== undefined ? { write_visibility: input.writeVisibility } : {}),
+ };
+}
+
+const typePath = (type: string) => `/references/reference-types/${encodeURIComponent(type)}`;
+
+/** Add a reference type. Refusals (a slug in use, a built-in's slug) propagate in the gateway's words. */
+export async function createReferenceType(
+ server: SwitchServer,
+ input: ReferenceTypeInput
+): Promise<ManagedReferenceType> {
+ const res = await gatewayFetch(server, '/references/reference-types', {
+ authenticated: true,
+ method: 'POST',
+ body: typeBody(input),
+ });
+ return mapManagedReferenceType((await res.json()) as ReferenceTypeJson);
+}
+
+/** Change a reference type; its slug stays. */
+export async function updateReferenceType(
+ server: SwitchServer,
+ type: string,
+ changes: ReferenceTypeChanges
+): Promise<ManagedReferenceType> {
+ const res = await gatewayFetch(server, typePath(type), {
+ authenticated: true,
+ method: 'PATCH',
+ body: typeBody(changes),
+ });
+ return mapManagedReferenceType((await res.json()) as ReferenceTypeJson);
+}
+
+/** Delete a reference type. The server refuses (409) while references still use it. */
+export async function deleteReferenceType(server: SwitchServer, type: string): Promise<void> {
+ await gatewayFetch(server, typePath(type), { authenticated: true, method: 'DELETE' });
+}
+
/** The references or documents a package holds (`GET /packages/{id}/{kind}`). */
export async function fetchPackageMembers(
server: SwitchServer,
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.ts
index f78450fb8..5078ad88e 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
@@ -115,6 +115,10 @@ import {
addPackageMember,
fetchPackageMembers,
removePackageMember,
+ createReferenceType,
+ deleteReferenceType,
+ fetchManagedReferenceTypes,
+ updateReferenceType,
} 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';
@@ -153,7 +157,10 @@ import type {
LibraryItemRoom,
LibraryKind,
PackageMemberKind,
+ ManagedReferenceType,
PackageMemberRemoval,
+ ReferenceTypeChanges,
+ ReferenceTypeInput,
ReferenceTypeOption,
} from '@shared/core/switch-servers/library';
import type {
@@ -1195,6 +1202,33 @@ export const workspacesController = createRPCController({
listReferenceTypes: (params: { workspaceId: string }): Promise<ReferenceTypeOption[]> =>
withWorkspaceSession(params.workspaceId, (server) => fetchReferenceTypes(server)),
+ /** The reference types the signed-in person may change. */
+ listManagedReferenceTypes: (params: { workspaceId: string }): Promise<ManagedReferenceType[]> =>
+ withWorkspaceSession(params.workspaceId, (server) => fetchManagedReferenceTypes(server)),
+
+ /** Add, change or delete a reference type. Refusals propagate in the gateway's words. */
+ createReferenceType: (params: {
+ workspaceId: string;
+ input: ReferenceTypeInput;
+ }): Promise<ManagedReferenceType> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ createReferenceType(server, params.input)
+ ),
+
+ updateReferenceType: (params: {
+ workspaceId: string;
+ type: string;
+ changes: ReferenceTypeChanges;
+ }): Promise<ManagedReferenceType> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ updateReferenceType(server, params.type, params.changes)
+ ),
+
+ deleteReferenceType: (params: { workspaceId: string; type: string }): Promise<void> =>
+ withReachableWorkspaceSession(params.workspaceId, (server) =>
+ deleteReferenceType(server, params.type)
+ ),
+
/** 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.ts
index 6e8c9b97f..20982d606 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
@@ -13,6 +13,7 @@ import {
DeleteLibraryItemModal,
NewLibraryItemModal,
} from '@renderer/features/library/library-modals';
+import { ReferenceTypeModal } from '@renderer/features/library/reference-types';
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';
@@ -90,6 +91,10 @@ export const modalRegistry = {
dismissOnOutsideClick: false,
}),
deleteLibraryItemModal: createModal(DeleteLibraryItemModal, { size: 'sm' }),
+ referenceTypeModal: createModal(ReferenceTypeModal, {
+ size: 'md',
+ dismissOnOutsideClick: false,
+ }),
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/features/library/library-item-form.tsx b/console/apps/switch-console-desktop/src/renderer/features/library/library-item-form.tsx
index e20b62da8..d37df9668 100644
--- 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.tsx
@@ -27,6 +27,7 @@ export function LibraryItemFields({
typeLocked = false,
canChangeAccess = true,
autoFocus = false,
+ onNewType = null,
}: {
kind: LibraryKind;
form: LibraryForm;
@@ -36,6 +37,8 @@ export function LibraryItemFields({
typeLocked?: boolean;
canChangeAccess?: boolean;
autoFocus?: boolean;
+ /** Makes a new type to pick, where the type is still being chosen. */
+ onNewType?: (() => void) | null;
}) {
const id = useId();
const set = (patch: Partial<LibraryForm>) => onChange({ ...form, ...patch });
@@ -50,7 +53,10 @@ export function LibraryItemFields({
) : (
<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>
+ <SelectValue>
+ {/* A type just made shows by its slug until the list has it. */}
+ {type ? type.displayName : form.type || 'Pick a type'}
+ </SelectValue>
</SelectTrigger>
<SelectContent>
{types.map((t) => (
@@ -64,6 +70,15 @@ export function LibraryItemFields({
</SelectContent>
</Select>
)}
+ {!typeLocked && onNewType && (
+ <button
+ type="button"
+ className="cursor-pointer self-start text-xs text-foreground-muted underline-offset-2 hover:text-foreground hover:underline"
+ onClick={onNewType}
+ >
+ None fit? New type…
+ </button>
+ )}
</Field>
)}
{kind === 'references' && (
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.tsx
index 71ddea174..adc9c97af 100644
--- 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.tsx
@@ -24,6 +24,7 @@ import {
libraryRoomsKey,
referenceTypesKey,
} from './library-queries';
+import { ReferenceTypeModal } from './reference-types';
type NewProps = BaseModalProps<LibraryItem> & { workspaceId: string; kind: LibraryKind };
@@ -40,6 +41,8 @@ export function NewLibraryItemModal({ workspaceId, kind, onSuccess, onClose }: N
});
const text = KIND_TEXT[kind];
const problem = formProblem(kind, form);
+ // A new type is made in this same window (one modal at a time), then picked.
+ const [addingType, setAddingType] = useState(false);
const save = async () => {
setSaving(true);
@@ -59,6 +62,20 @@ export function NewLibraryItemModal({ workspaceId, kind, onSuccess, onClose }: N
}
};
+ if (addingType) {
+ return (
+ <ReferenceTypeModal
+ workspaceId={workspaceId}
+ editing={null}
+ onSuccess={(created) => {
+ setForm((now) => ({ ...now, type: created.type }));
+ setAddingType(false);
+ }}
+ onClose={() => setAddingType(false)}
+ />
+ );
+ }
+
return (
<ModalLayout
header={
@@ -94,6 +111,7 @@ export function NewLibraryItemModal({ workspaceId, kind, onSuccess, onClose }: N
onChange={setForm}
types={types.data ?? []}
autoFocus
+ onNewType={kind === 'references' ? () => setAddingType(true) : null}
/>
)}
{error && (
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.tsx
index 29a485694..5838a12b1 100644
--- 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.tsx
@@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query';
-import { FileText, Library, Link2, Package, Plus } from 'lucide-react';
+import { FileText, Library, Link2, Package, Plus, Shapes } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
@@ -28,6 +28,7 @@ import {
typeOptions,
} from './library-model';
import { libraryItemsKey } from './library-queries';
+import { ReferenceTypesPanel } from './reference-types';
function useViewParams() {
return useParams('library').params;
@@ -43,7 +44,11 @@ const KINDS = [
{ value: 'references', label: 'References', icon: Link2 },
{ value: 'documents', label: 'Documents', icon: FileText },
{ value: 'packages', label: 'Packages', icon: Package },
-] as const satisfies readonly { value: LibraryKind; label: string; icon: typeof Link2 }[];
+ { value: 'types', label: 'Reference types', icon: Shapes },
+] as const satisfies readonly { value: LibraryTab; label: string; icon: typeof Link2 }[];
+
+/** The page's tabs: each kind of item, and the types references take. */
+type LibraryTab = LibraryKind | 'types';
const SCOPES = [
{ value: 'all', label: 'All' },
@@ -61,11 +66,15 @@ const LibraryPanel = observer(function LibraryPanel() {
const { navigate } = useNavigate();
const showNew = useShowModal('newLibraryItemModal');
const showDelete = useShowModal('deleteLibraryItemModal');
- const [kind, setKind] = useState<LibraryKind>(initialKind ?? 'references');
+ const showType = useShowModal('referenceTypeModal');
+ const [tab, setTab] = useState<LibraryTab>(initialKind ?? 'references');
// Coming back from an item's page lands on that item's kind.
useEffect(() => {
- if (initialKind) setKind(initialKind);
+ if (initialKind) setTab(initialKind);
}, [initialKind]);
+ const onTypes = tab === 'types';
+ // The items query and its words follow the tab; the types tab reads its own.
+ const kind: LibraryKind = onTypes ? 'references' : tab;
const [filter, setFilter] = useState(NO_LIBRARY_FILTER);
const workspaceId = workspacesStore.idOnServerInScope(serverId);
const viewer = {
@@ -75,7 +84,7 @@ const LibraryPanel = observer(function LibraryPanel() {
const items = useQuery({
queryKey: libraryItemsKey(workspaceId ?? '', kind),
queryFn: () => rpc.workspaces.listLibraryItems({ workspaceId: workspaceId as string, kind }),
- enabled: workspaceId !== null,
+ enabled: workspaceId !== null && !onTypes,
});
const text = KIND_TEXT[kind];
const all = items.data ?? [];
@@ -91,8 +100,10 @@ const LibraryPanel = observer(function LibraryPanel() {
navigate('libraryItem', { serverId, kind: item.kind, itemId: item.id });
const create = () => {
if (workspaceId === null) return;
- showNew({ workspaceId, kind, onSuccess: (created: LibraryItem) => open(created) });
+ if (onTypes) showType({ workspaceId, editing: null });
+ else showNew({ workspaceId, kind, onSuccess: (created: LibraryItem) => open(created) });
};
+ const listLabel = onTypes ? 'reference types' : text.title.toLowerCase();
return (
<ServerPage
@@ -102,7 +113,7 @@ const LibraryPanel = observer(function LibraryPanel() {
action={
<Button size="sm" disabled={workspaceId === null} onClick={create}>
<Plus className="size-4" />
- New {text.noun}
+ {onTypes ? 'New reference type' : `New ${text.noun}`}
</Button>
}
>
@@ -113,9 +124,9 @@ const LibraryPanel = observer(function LibraryPanel() {
) : (
<div className="flex flex-col gap-4">
<SegmentedControl
- ariaLabel="References, documents or packages"
- value={kind}
- onChange={setKind}
+ ariaLabel="References, documents, packages or reference types"
+ value={tab}
+ onChange={setTab}
options={KINDS}
className="w-max"
/>
@@ -123,7 +134,7 @@ const LibraryPanel = observer(function LibraryPanel() {
scope={
viewer.id !== null && (
<SegmentedControl
- ariaLabel={`Whose ${text.title.toLowerCase()}`}
+ ariaLabel={`Whose ${listLabel}`}
value={filter.mineOnly ? 'mine' : 'all'}
onChange={(next) => setFilter({ ...filter, mineOnly: next === 'mine' })}
options={SCOPES}
@@ -136,12 +147,12 @@ const LibraryPanel = observer(function LibraryPanel() {
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`}
+ placeholder={`Search ${listLabel}…`}
+ aria-label={`Search ${listLabel} by name and description`}
/>
}
filters={
- kind === 'references' &&
+ tab === 'references' &&
types.length > 0 && (
<FilterSelect
label="Type"
@@ -153,7 +164,7 @@ const LibraryPanel = observer(function LibraryPanel() {
)
}
/>
- {kind === 'documents' && (
+ {tab === 'documents' && (
// The server keeps an agent's room documents out of this list, which
// surprises someone who knows one exists: say where it is.
<p className="text-xs text-foreground-muted">
@@ -161,7 +172,9 @@ const LibraryPanel = observer(function LibraryPanel() {
Find them in the room’s Resources tab.
</p>
)}
- {items.isPending ? (
+ {onTypes ? (
+ <ReferenceTypesPanel workspaceId={workspaceId} viewerId={viewer.id} filter={filter} />
+ ) : 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">
diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/reference-type-slug.test.ts b/console/apps/switch-console-desktop/src/renderer/features/library/reference-type-slug.test.ts
new file mode 100644
index 000000000..4211acdd1
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/library/reference-type-slug.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+import { slugAsTyped, slugFromName, slugProblem } from './reference-type-slug';
+
+const known = { builtin: new Set(['github']), taken: new Set(['linear']) };
+
+describe('the reference type slug', () => {
+ it('is made from the name', () => {
+ expect(slugFromName('Linear issues')).toBe('linear_issues');
+ expect(slugFromName(' Q4 / roadmap docs! ')).toBe('q4_roadmap_docs');
+ expect(slugFromName('2024 Plans')).toBe('plans');
+ expect(slugFromName('x'.repeat(80))).toHaveLength(63);
+ });
+
+ it('mends the common slips as it is typed', () => {
+ expect(slugAsTyped('Linear Issues')).toBe('linear_issues');
+ expect(slugAsTyped('my-type')).toBe('my_type');
+ expect(slugAsTyped('café')).toBe('café');
+ });
+
+ it('says in words what is wrong', () => {
+ expect(slugProblem('', known)).toBe('Give it a slug.');
+ expect(slugProblem('café', known)).toBe('Use only letters, digits and underscores.');
+ expect(slugProblem('2fa', known)).toBe('Start with a letter.');
+ expect(slugProblem('a', known)).toBe('At least 2 characters.');
+ expect(slugProblem(`a${'b'.repeat(63)}`, known)).toBe('At most 63 characters.');
+ expect(slugProblem('github', known)).toBe('Switch already has a built-in type with this slug.');
+ expect(slugProblem('linear', known)).toBe('Another type already uses this slug.');
+ expect(slugProblem('linear_issues', known)).toBeNull();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/reference-type-slug.ts b/console/apps/switch-console-desktop/src/renderer/features/library/reference-type-slug.ts
new file mode 100644
index 000000000..f48cfa88e
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/library/reference-type-slug.ts
@@ -0,0 +1,44 @@
+/**
+ * A reference type's slug, the name stored on every reference of the type.
+ * The server takes lowercase letters, digits and underscores, starting with a
+ * letter, 2 to 63 long. People are not shown that rule as a pattern: the field
+ * writes what it can for them and says, in words, what is still wrong.
+ */
+
+export const SLUG_MIN = 2;
+export const SLUG_MAX = 63;
+
+/** A slug made from a display name: "Linear issues" becomes "linear_issues". */
+export function slugFromName(name: string): string {
+ return name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '_')
+ .replace(/^[^a-z]+/, '')
+ .replace(/_+$/, '')
+ .slice(0, SLUG_MAX)
+ .replace(/_+$/, '');
+}
+
+/**
+ * What typing into the slug field keeps: lower case, and spaces or hyphens as
+ * underscores, so the common slips are mended rather than refused. Anything
+ * else stays as typed, for {@link slugProblem} to point out.
+ */
+export function slugAsTyped(value: string): string {
+ return value.toLowerCase().replace(/[\s-]/g, '_');
+}
+
+/** What is wrong with a slug, in words, or null when the server would take it. */
+export function slugProblem(
+ slug: string,
+ known: { builtin: ReadonlySet<string>; taken: ReadonlySet<string> }
+): string | null {
+ if (slug.length === 0) return 'Give it a slug.';
+ if (/[^a-z0-9_]/.test(slug)) return 'Use only letters, digits and underscores.';
+ if (!/^[a-z]/.test(slug)) return 'Start with a letter.';
+ if (slug.length < SLUG_MIN) return `At least ${SLUG_MIN} characters.`;
+ if (slug.length > SLUG_MAX) return `At most ${SLUG_MAX} characters.`;
+ if (known.builtin.has(slug)) return 'Switch already has a built-in type with this slug.';
+ if (known.taken.has(slug)) return 'Another type already uses this slug.';
+ return null;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/library/reference-types.tsx b/console/apps/switch-console-desktop/src/renderer/features/library/reference-types.tsx
new file mode 100644
index 000000000..49d5cc3da
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/library/reference-types.tsx
@@ -0,0 +1,588 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { MoreVertical, Pencil, Shapes, Trash2 } from 'lucide-react';
+import { useEffect, useId, useRef, 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 { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
+import { Badge } from '@renderer/lib/ui/badge';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@renderer/lib/ui/dropdown-menu';
+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import { ModalLayout } from '@renderer/lib/ui/modal-layout';
+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
+import { Textarea } from '@renderer/lib/ui/textarea';
+import type {
+ ManagedReferenceType,
+ ReferenceTypeChanges,
+ ReferenceTypeInput,
+ ReferenceTypeOption,
+} from '@shared/core/switch-servers/library';
+import {
+ ACCESS_SHORT,
+ accessOf,
+ type LibraryAccess,
+ LIBRARY_ACCESS_OPTIONS,
+ type LibraryFilter,
+ visibilityOf,
+} from './library-model';
+import { referenceTypesKey } from './library-queries';
+import { slugAsTyped, slugFromName, slugProblem } from './reference-type-slug';
+
+export const managedReferenceTypesKey = (workspaceId: string) => [
+ 'managed-reference-types',
+ workspaceId,
+];
+
+/** One reference type as the tab lists it: Switch's own, or one someone wrote. */
+export type ReferenceTypeCard = {
+ key: string;
+ type: string;
+ displayName: string;
+ instructions: string;
+ valueHint: string;
+ isBuiltin: boolean;
+ ownerId: string | null;
+ ownerName: string | null;
+ /** Null when the viewer is not told (someone else's type). */
+ access: LibraryAccess | null;
+ shadowedByBuiltin: boolean;
+ /** Its full settings, when the viewer may change it; null otherwise. */
+ managed: ManagedReferenceType | null;
+};
+
+/**
+ * Every type the viewer can see, built-ins first, merged with the ones they
+ * may change. A type hidden by a built-in of the same slug is not offered for
+ * new references, so it shows only to whoever may change it.
+ */
+export function referenceTypeCards(
+ visible: readonly ReferenceTypeOption[],
+ managed: readonly ManagedReferenceType[]
+): ReferenceTypeCard[] {
+ const managedBySlug = new Map(managed.map((t) => [t.type, t]));
+ const cards: ReferenceTypeCard[] = visible.map((t) => {
+ const own = t.isBuiltin ? null : (managedBySlug.get(t.type) ?? null);
+ return {
+ key: `${t.isBuiltin ? 'builtin' : 'user'}:${t.type}`,
+ type: t.type,
+ displayName: t.displayName,
+ instructions: t.instructions,
+ valueHint: t.valueHint,
+ isBuiltin: t.isBuiltin,
+ ownerId: t.ownerId,
+ ownerName: t.ownerName,
+ access: own ? accessOf(own) : null,
+ shadowedByBuiltin: false,
+ managed: own,
+ };
+ });
+ const listed = new Set(cards.filter((c) => !c.isBuiltin).map((c) => c.type));
+ for (const t of managed) {
+ if (listed.has(t.type)) continue;
+ cards.push({
+ key: `user:${t.type}`,
+ type: t.type,
+ displayName: t.displayName,
+ instructions: t.instructions,
+ valueHint: t.valueHint,
+ isBuiltin: false,
+ ownerId: t.ownerId,
+ ownerName: t.ownerName,
+ access: accessOf(t),
+ shadowedByBuiltin: t.shadowedByBuiltin,
+ managed: t,
+ });
+ }
+ return cards.sort(
+ (a, b) =>
+ Number(b.isBuiltin) - Number(a.isBuiltin) || a.displayName.localeCompare(b.displayName)
+ );
+}
+
+/** The cards the filter row lets through: yours, and what matches the search. */
+export function filterReferenceTypeCards(
+ cards: readonly ReferenceTypeCard[],
+ filter: Pick<LibraryFilter, 'mineOnly' | 'query'>,
+ viewerId: string | null
+): ReferenceTypeCard[] {
+ const needle = filter.query.trim().toLowerCase();
+ return cards
+ .filter((c) => !filter.mineOnly || (viewerId !== null && c.ownerId === viewerId))
+ .filter(
+ (c) =>
+ !needle ||
+ c.displayName.toLowerCase().includes(needle) ||
+ c.type.includes(needle) ||
+ c.valueHint.toLowerCase().includes(needle)
+ );
+}
+
+/** The Reference types tab: every type the viewer can see, as cards. */
+export function ReferenceTypesPanel({
+ workspaceId,
+ viewerId,
+ filter,
+}: {
+ workspaceId: string;
+ viewerId: string | null;
+ filter: Pick<LibraryFilter, 'mineOnly' | 'query'>;
+}) {
+ const queryClient = useQueryClient();
+ const showType = useShowModal('referenceTypeModal');
+ const confirm = useShowModal('confirmActionModal');
+ const visible = useQuery({
+ queryKey: referenceTypesKey(workspaceId),
+ queryFn: () => rpc.workspaces.listReferenceTypes({ workspaceId }),
+ });
+ const managed = useQuery({
+ queryKey: managedReferenceTypesKey(workspaceId),
+ queryFn: () => rpc.workspaces.listManagedReferenceTypes({ workspaceId }),
+ });
+ const cards = referenceTypeCards(visible.data ?? [], managed.data ?? []);
+ const shown = filterReferenceTypeCards(cards, filter, viewerId);
+
+ const remove = (card: ReferenceTypeCard) =>
+ confirm({
+ title: `Delete ${card.displayName}?`,
+ description: 'It is deleted for everyone. Switch refuses while any reference still uses it.',
+ confirmLabel: 'Delete',
+ onSuccess: () => {
+ rpc.workspaces
+ .deleteReferenceType({ workspaceId, type: card.type })
+ .then(async () => {
+ toast({ title: `"${card.displayName}" deleted` });
+ await invalidateReferenceTypes(queryClient, workspaceId);
+ })
+ .catch((e: unknown) =>
+ toast({
+ title: `Could not delete "${card.displayName}"`,
+ description: failureText(e, 'Check the server connection and try again.'),
+ variant: 'destructive',
+ })
+ );
+ },
+ });
+
+ if (visible.isPending) return <p className="py-2 text-sm text-foreground-muted">Loading…</p>;
+ if (visible.isError) {
+ return (
+ <p className="py-2 text-sm text-foreground-muted">
+ {failureText(visible.error, 'Could not read the reference types.')}
+ </p>
+ );
+ }
+ if (shown.length === 0) {
+ return (
+ <p className="py-2 text-sm text-foreground-muted">
+ {filter.mineOnly && !filter.query.trim()
+ ? 'You have made no reference types yet.'
+ : 'No reference type matches.'}
+ </p>
+ );
+ }
+ return (
+ <div
+ role="list"
+ aria-label="Reference types"
+ className="grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-[14px]"
+ >
+ {shown.map((card) => (
+ <div role="listitem" key={card.key}>
+ <TypeCard
+ card={card}
+ viewerId={viewerId}
+ showYours={!filter.mineOnly}
+ onOpen={() => showType({ workspaceId, editing: card.managed, viewing: card })}
+ onEdit={
+ card.managed
+ ? () => showType({ workspaceId, editing: card.managed, viewing: card })
+ : null
+ }
+ onDelete={card.managed ? () => remove(card) : null}
+ />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function TypeCard({
+ card,
+ viewerId,
+ showYours,
+ onOpen,
+ onEdit,
+ onDelete,
+}: {
+ card: ReferenceTypeCard;
+ viewerId: string | null;
+ showYours: boolean;
+ onOpen: () => void;
+ onEdit: (() => void) | null;
+ onDelete: (() => void) | null;
+}) {
+ const mine = viewerId !== null && card.ownerId === viewerId;
+ const owner = card.isBuiltin
+ ? 'Comes with Switch'
+ : mine
+ ? 'Owned by you'
+ : card.ownerName
+ ? `Owned by ${card.ownerName}`
+ : null;
+ return (
+ <div
+ data-reference-type-card={card.type}
+ 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 ${card.displayName}`}
+ 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${onEdit ? ' pr-8' : ''}`}>
+ <Shapes className="size-4.5 shrink-0 text-foreground-muted" />
+ <h3 className="min-w-0 truncate font-medium text-foreground">{card.displayName}</h3>
+ {card.isBuiltin && <Badge variant="outline">Built-in</Badge>}
+ {showYours && mine && <Badge variant="secondary">Yours</Badge>}
+ </div>
+ <p className="line-clamp-2 text-sm text-foreground-muted">
+ {card.valueHint || <span className="italic">No hint for its links.</span>}
+ </p>
+ <p className="flex min-w-0 items-center gap-1 text-xs text-foreground-muted">
+ <span className="truncate font-mono">{card.type}</span>
+ {card.access && (
+ <>
+ <span aria-hidden>·</span>
+ <span>{ACCESS_SHORT[card.access]}</span>
+ </>
+ )}
+ {card.shadowedByBuiltin && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="text-foreground-warning">Hidden by a built-in</span>
+ </>
+ )}
+ </p>
+ {owner && (
+ <div className="mt-auto border-t border-border pt-2.5 text-xs text-foreground-muted">
+ {owner}
+ </div>
+ )}
+ </div>
+ {(onEdit || 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={`${card.displayName} actions`}
+ >
+ <MoreVertical className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-max whitespace-nowrap">
+ {onEdit && (
+ <DropdownMenuItem onClick={onEdit}>
+ <Pencil className="size-4" />
+ Edit…
+ </DropdownMenuItem>
+ )}
+ {onDelete && (
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 className="size-4" />
+ Delete…
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export async function invalidateReferenceTypes(
+ queryClient: ReturnType<typeof useQueryClient>,
+ workspaceId: string
+): Promise<void> {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: referenceTypesKey(workspaceId) }),
+ queryClient.invalidateQueries({ queryKey: managedReferenceTypesKey(workspaceId) }),
+ // References show their type's name.
+ queryClient.invalidateQueries({ queryKey: ['library-items', workspaceId, 'references'] }),
+ queryClient.invalidateQueries({ queryKey: ['library-item', workspaceId, 'references'] }),
+ ]);
+}
+
+type TypeForm = {
+ displayName: string;
+ type: string;
+ instructions: string;
+ valueHint: string;
+ access: LibraryAccess;
+};
+
+type ModalProps = BaseModalProps<ManagedReferenceType> & {
+ workspaceId: string;
+ /** The type to change; null makes a new one, or shows one the viewer may not change. */
+ editing: ManagedReferenceType | null;
+ /** A type to show read-only when it is not the viewer's to change. */
+ viewing?: ReferenceTypeCard;
+};
+
+/**
+ * Makes a reference type, changes one, or shows one read-only. The slug is
+ * filled in from the display name until edited, kept in the shape the server
+ * takes as it is typed, and anything still wrong is said in words.
+ */
+export function ReferenceTypeModal({
+ workspaceId,
+ editing,
+ viewing,
+ onSuccess,
+ onClose,
+}: ModalProps) {
+ const queryClient = useQueryClient();
+ const id = useId();
+ const readOnly = editing === null && viewing !== undefined;
+ const creating = editing === null && viewing === undefined;
+ const [form, setForm] = useState<TypeForm>(() => {
+ const from = editing ?? viewing;
+ return {
+ displayName: from?.displayName ?? '',
+ type: from?.type ?? '',
+ instructions: from?.instructions ?? '',
+ valueHint: from?.valueHint ?? '',
+ access: editing ? accessOf(editing) : 'shared',
+ };
+ });
+ // The slug follows the name until the person types into it.
+ const slugEdited = useRef(!creating);
+ const [touchedSlug, setTouchedSlug] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const visible = useQuery({
+ queryKey: referenceTypesKey(workspaceId),
+ queryFn: () => rpc.workspaces.listReferenceTypes({ workspaceId }),
+ enabled: creating,
+ });
+ const builtin = new Set((visible.data ?? []).filter((t) => t.isBuiltin).map((t) => t.type));
+ const taken = new Set((visible.data ?? []).filter((t) => !t.isBuiltin).map((t) => t.type));
+ const problem = creating ? slugProblem(form.type, { builtin, taken }) : null;
+ const nameMissing = form.displayName.trim() === '';
+
+ useEffect(() => {
+ if (creating && !slugEdited.current) {
+ setForm((now) => ({ ...now, type: slugFromName(now.displayName) }));
+ }
+ }, [creating, form.displayName]);
+
+ const save = async () => {
+ setSaving(true);
+ setError(null);
+ try {
+ const saved = creating
+ ? await rpc.workspaces.createReferenceType({
+ workspaceId,
+ input: inputOf(form),
+ })
+ : await rpc.workspaces.updateReferenceType({
+ workspaceId,
+ type: form.type,
+ changes: changesOf(editing as ManagedReferenceType, form),
+ });
+ await invalidateReferenceTypes(queryClient, workspaceId);
+ toast({ title: creating ? `"${saved.displayName}" added` : 'Saved' });
+ onSuccess(saved);
+ } catch (e) {
+ setError(failureText(e, creating ? 'Could not add the type.' : 'Could not save the type.'));
+ setSaving(false);
+ }
+ };
+
+ const title = creating
+ ? 'New reference type'
+ : readOnly
+ ? (viewing?.displayName ?? 'Reference type')
+ : `Edit ${editing?.displayName ?? 'reference type'}`;
+
+ return (
+ <ModalLayout
+ header={
+ <DialogHeader showCloseButton={!saving}>
+ <DialogTitle>{title}</DialogTitle>
+ </DialogHeader>
+ }
+ footer={
+ <DialogFooter>
+ {readOnly ? (
+ <Button type="button" variant="outline" onClick={onClose}>
+ Close
+ </Button>
+ ) : (
+ <>
+ <Button type="button" variant="outline" onClick={onClose} disabled={saving}>
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ onClick={() => void save()}
+ disabled={
+ saving ||
+ nameMissing ||
+ problem !== null ||
+ (editing !== null && Object.keys(changesOf(editing, form)).length === 0)
+ }
+ >
+ {saving ? 'Saving…' : creating ? 'Add type' : 'Save'}
+ </Button>
+ </>
+ )}
+ </DialogFooter>
+ }
+ >
+ <DialogContentArea className="max-h-[calc(100dvh-2rem-var(--modal-chrome,10rem))] gap-4 overflow-y-auto">
+ {readOnly && viewing?.isBuiltin && (
+ <p className="text-sm text-foreground-muted">
+ Comes with Switch, so it can’t be changed.
+ </p>
+ )}
+ {readOnly && !viewing?.isBuiltin && (
+ <p className="text-sm text-foreground-muted">
+ {viewing?.ownerName ? `${viewing.ownerName}’s type. ` : ''}Only its owner or an admin
+ changes it.
+ </p>
+ )}
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor={`${id}-name`}>Name</FieldLabel>
+ <Input
+ id={`${id}-name`}
+ value={form.displayName}
+ disabled={readOnly}
+ onChange={(e) => setForm({ ...form, displayName: e.target.value })}
+ placeholder="Linear issues"
+ autoFocus={!readOnly}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`${id}-slug`}>Slug</FieldLabel>
+ <Input
+ id={`${id}-slug`}
+ value={form.type}
+ disabled={!creating}
+ aria-invalid={creating && touchedSlug && problem !== null}
+ className="font-mono"
+ onChange={(e) => {
+ slugEdited.current = true;
+ setTouchedSlug(true);
+ setForm({ ...form, type: slugAsTyped(e.target.value) });
+ }}
+ onBlur={() => setTouchedSlug(true)}
+ placeholder="linear_issues"
+ />
+ {creating && (touchedSlug || form.type !== '') && problem !== null ? (
+ <p className="text-xs text-destructive">{problem}</p>
+ ) : null}
+ <p className="text-xs text-foreground-muted">
+ Stored on every reference of this type, so it cannot be changed later.
+ </p>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`${id}-hint`}>What the links point at</FieldLabel>
+ <Input
+ id={`${id}-hint`}
+ value={form.valueHint}
+ disabled={readOnly}
+ onChange={(e) => setForm({ ...form, valueHint: e.target.value })}
+ placeholder="Links to Linear issues, e.g. https://linear.app/acme/issue/ENG-123"
+ />
+ <p className="text-xs text-foreground-muted">
+ Shown under the links when someone adds a reference of this type.
+ </p>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={`${id}-instructions`}>Instructions for agents</FieldLabel>
+ <Textarea
+ id={`${id}-instructions`}
+ value={form.instructions}
+ disabled={readOnly}
+ onChange={(e) => setForm({ ...form, instructions: e.target.value })}
+ placeholder="What an agent needs to use these links, such as the connector to read them with"
+ className="min-h-20"
+ />
+ <p className="text-xs text-foreground-muted">
+ Every agent in a room with a reference of this type is told this.
+ </p>
+ </Field>
+ {!readOnly && (
+ <Field>
+ <FieldLabel>Who can see it</FieldLabel>
+ <div className="flex">
+ <SegmentedControl
+ value={form.access}
+ onChange={(access) => setForm({ ...form, access })}
+ options={LIBRARY_ACCESS_OPTIONS}
+ ariaLabel="Who can see it"
+ />
+ </div>
+ <p className="text-xs text-foreground-muted">
+ {LIBRARY_ACCESS_OPTIONS.find((o) => o.value === form.access)?.hint}
+ </p>
+ </Field>
+ )}
+ </FieldGroup>
+ {error && (
+ <Alert variant="destructive">
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+ </DialogContentArea>
+ </ModalLayout>
+ );
+}
+
+function inputOf(form: TypeForm): ReferenceTypeInput {
+ return {
+ type: form.type,
+ displayName: form.displayName.trim(),
+ instructions: form.instructions.trim(),
+ valueHint: form.valueHint.trim(),
+ ...visibilityOf(form.access),
+ };
+}
+
+/** Only what changed, so a save does not overwrite another field someone else changed. */
+export function changesOf(before: ManagedReferenceType, form: TypeForm): ReferenceTypeChanges {
+ const next = inputOf(form);
+ const changes: ReferenceTypeChanges = {};
+ if (next.displayName !== before.displayName) changes.displayName = next.displayName;
+ if (next.instructions !== before.instructions) changes.instructions = next.instructions;
+ if (next.valueHint !== before.valueHint) changes.valueHint = next.valueHint;
+ if (form.access !== accessOf(before)) {
+ changes.readVisibility = next.readVisibility;
+ changes.writeVisibility = next.writeVisibility;
+ }
+ return changes;
+}
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.tsx
index f4b89bc4d..226565268 100644
--- 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.tsx
@@ -37,6 +37,10 @@ const rpcMock = vi.hoisted(() => ({
listPackageMembers: vi.fn(),
addPackageMember: vi.fn(),
removePackageMember: vi.fn(),
+ listManagedReferenceTypes: vi.fn(),
+ createReferenceType: vi.fn(),
+ updateReferenceType: vi.fn(),
+ deleteReferenceType: vi.fn(),
}));
const showModal = vi.hoisted(() => vi.fn());
const navigate = vi.hoisted(() => vi.fn());
@@ -83,8 +87,12 @@ vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
}));
import { libraryItemView } from '@renderer/features/library/library-item-view';
-import { DeleteLibraryItemModal } from '@renderer/features/library/library-modals';
+import {
+ DeleteLibraryItemModal,
+ NewLibraryItemModal,
+} from '@renderer/features/library/library-modals';
import { libraryView } from '@renderer/features/library/library-view';
+import { ReferenceTypeModal } from '@renderer/features/library/reference-types';
import { Dialog, DialogContent } from '@renderer/lib/ui/dialog';
function item(over: Partial<LibraryItem>): LibraryItem {
@@ -173,6 +181,78 @@ beforeEach(() => {
hiddenAffectedRoomsCount: 1,
});
showModal.mockReset();
+ rpcMock.listReferenceTypes.mockResolvedValue([
+ {
+ type: 'github',
+ displayName: 'GitHub',
+ instructions: '',
+ valueHint: 'Repositories',
+ isBuiltin: true,
+ ownerName: null,
+ ownerId: null,
+ },
+ {
+ type: 'linear',
+ displayName: 'Linear',
+ instructions: 'Use the Linear connector.',
+ valueHint: 'Issue links',
+ isBuiltin: false,
+ ownerName: 'Me',
+ ownerId: 'me',
+ },
+ {
+ type: 'wiki',
+ displayName: 'Wiki',
+ instructions: '',
+ valueHint: 'Pages',
+ isBuiltin: false,
+ ownerName: 'Bob',
+ ownerId: 'bob',
+ },
+ ]);
+ rpcMock.listManagedReferenceTypes.mockResolvedValue([
+ {
+ type: 'linear',
+ displayName: 'Linear',
+ instructions: 'Use the Linear connector.',
+ valueHint: 'Issue links',
+ isBuiltin: false,
+ ownerName: 'Me',
+ ownerId: 'me',
+ readVisibility: 'public',
+ writeVisibility: 'private',
+ shadowedByBuiltin: false,
+ createdAt: '',
+ },
+ {
+ type: 'jira',
+ displayName: 'Old Jira',
+ instructions: '',
+ valueHint: '',
+ isBuiltin: false,
+ ownerName: 'Me',
+ ownerId: 'me',
+ readVisibility: 'private',
+ writeVisibility: 'private',
+ shadowedByBuiltin: true,
+ createdAt: '',
+ },
+ ]);
+ rpcMock.createReferenceType.mockImplementation(
+ async ({ input }: { input: { type: string; displayName: string } }) => ({
+ ...input,
+ instructions: '',
+ valueHint: '',
+ isBuiltin: false,
+ ownerName: 'Me',
+ ownerId: 'me',
+ readVisibility: 'public',
+ writeVisibility: 'private',
+ shadowedByBuiltin: false,
+ createdAt: '',
+ })
+ );
+ rpcMock.updateReferenceType.mockResolvedValue({});
navigate.mockReset();
});
@@ -543,3 +623,124 @@ describe('a package', () => {
expect(container.querySelector('[aria-label^="Remove "]')).toBeNull();
});
});
+
+describe('reference types', () => {
+ beforeEach(() => {
+ state.params = { serverId: 'srv' };
+ });
+
+ const typeCard = (slug: string) =>
+ container.querySelector<HTMLElement>(`[data-reference-type-card="${slug}"]`);
+
+ it('lists Switch’s types, read-only, beside people’s, and one hidden by a built-in', async () => {
+ await render(libraryView.MainPanel);
+ await act(async () => button('Reference types')!.click());
+ await settle();
+ expect(typeCard('github')!.textContent).toContain('Built-in');
+ expect(typeCard('github')!.querySelector('[aria-label$=" actions"]')).toBeNull();
+ expect(typeCard('linear')!.textContent).toContain('Owned by you');
+ expect(typeCard('linear')!.querySelector('[aria-label="Linear actions"]')).not.toBeNull();
+ // Bob's type: shown, not offered for changing.
+ expect(typeCard('wiki')!.querySelector('[aria-label$=" actions"]')).toBeNull();
+ expect(typeCard('jira')!.textContent).toContain('Hidden by a built-in');
+ expect(button('New reference type')).toBeDefined();
+ });
+
+ const renderTypeModal = (editing: unknown) =>
+ render(() => (
+ <Dialog open>
+ <DialogContent>
+ <ReferenceTypeModal
+ workspaceId="ws"
+ editing={editing as never}
+ onSuccess={() => {}}
+ onClose={() => {}}
+ />
+ </DialogContent>
+ </Dialog>
+ ));
+ const dialog = () => document.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;
+ const input = (placeholder: string) =>
+ dialog().querySelector<HTMLInputElement>(`input[placeholder="${placeholder}"]`)!;
+ const type = async (field: HTMLInputElement, value: string) => {
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(field, value);
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ };
+ const dialogButton = (label: string) =>
+ [...dialog().querySelectorAll('button')].find((b) => b.textContent?.trim() === label);
+
+ it('fills the slug from the name, and makes the type', async () => {
+ await renderTypeModal(null);
+ await type(input('Linear issues'), 'Notion Pages');
+ expect(input('linear_issues').value).toBe('notion_pages');
+ expect(dialog().textContent).toContain('Stored on every reference of this type');
+ await act(async () => dialogButton('Add type')!.click());
+ await settle();
+ expect(rpcMock.createReferenceType).toHaveBeenCalledWith({
+ workspaceId: 'ws',
+ input: expect.objectContaining({ type: 'notion_pages', displayName: 'Notion Pages' }),
+ });
+ });
+
+ it('lowercases a typed slug and says in words what is wrong with it', async () => {
+ await renderTypeModal(null);
+ await type(input('Linear issues'), 'Anything');
+ await type(input('linear_issues'), 'My Type!');
+ expect(input('linear_issues').value).toBe('my_type!');
+ expect(dialog().textContent).toContain('Use only letters, digits and underscores.');
+ expect(dialogButton('Add type')!.disabled).toBe(true);
+ await type(input('linear_issues'), 'Linear');
+ expect(dialog().textContent).toContain('Another type already uses this slug.');
+ await type(input('linear_issues'), 'GitHub');
+ expect(dialog().textContent).toContain('Switch already has a built-in type with this slug.');
+ });
+
+ it('keeps the slug as it is when editing, and sends only what changed', async () => {
+ await renderTypeModal({
+ type: 'linear',
+ displayName: 'Linear',
+ instructions: 'Use the Linear connector.',
+ valueHint: 'Issue links',
+ isBuiltin: false,
+ ownerName: 'Me',
+ ownerId: 'me',
+ readVisibility: 'public',
+ writeVisibility: 'private',
+ shadowedByBuiltin: false,
+ createdAt: '',
+ });
+ expect(input('linear_issues').disabled).toBe(true);
+ await type(input('Linear issues'), 'Linear tickets');
+ await act(async () => dialogButton('Save')!.click());
+ await settle();
+ expect(rpcMock.updateReferenceType).toHaveBeenCalledWith({
+ workspaceId: 'ws',
+ type: 'linear',
+ changes: { displayName: 'Linear tickets' },
+ });
+ });
+
+ it('makes a new type from New reference, then picks it', async () => {
+ await render(() => (
+ <Dialog open>
+ <DialogContent>
+ <NewLibraryItemModal
+ workspaceId="ws"
+ kind="references"
+ onSuccess={() => {}}
+ onClose={() => {}}
+ />
+ </DialogContent>
+ </Dialog>
+ ));
+ await act(async () => dialogButton('None fit? New type…')!.click());
+ expect(dialog().textContent).toContain('New reference type');
+ await type(input('Linear issues'), 'Figma files');
+ await act(async () => dialogButton('Add type')!.click());
+ await settle();
+ expect(dialog().textContent).toContain('New reference');
+ expect(dialog().querySelector('[aria-label="Type"]')?.textContent).toContain('figma_files');
+ });
+});
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.ts
index 91b2fbb3d..dca38251d 100644
--- 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.ts
@@ -54,13 +54,39 @@ export type LibraryDocument = LibraryItem & { content: string };
export type ReferenceTypeOption = {
type: string;
displayName: string;
+ /** What every reference of this type tells agents about using it. */
+ instructions: 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;
+ ownerId: string | null;
+};
+
+/** A type the viewer may change (theirs, or any for an admin), with its settings. */
+export type ManagedReferenceType = ReferenceTypeOption & {
+ ownerId: string;
+ readVisibility: LibraryVisibility;
+ writeVisibility: LibraryVisibility;
+ /** A built-in with the same slug hides it: references of that slug use the built-in. */
+ shadowedByBuiltin: boolean;
+ createdAt: string;
+};
+
+/** What a new reference type is made of. The slug cannot change afterwards. */
+export type ReferenceTypeInput = {
+ type: string;
+ displayName: string;
+ instructions: string;
+ valueHint: string;
+ readVisibility: LibraryVisibility;
+ writeVisibility: LibraryVisibility;
};
+/** The fields of a reference type to change; anything left out stays as it is. */
+export type ReferenceTypeChanges = Partial<Omit<ReferenceTypeInput, 'type'>>;
+
/** What a new library item is made of. */
export type LibraryItemInput = {
name: string;