Skip to content

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

Publish, edit, share and search templates from the Console (CHOO-2703) (#501)

Abel Dantas54f645e98618
diff --git a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
index 700ade308..1231c08f7 100644
--- a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
@@ -1,5 +1,8 @@
+import { writeFile } from 'node:fs/promises';
import Ajv from 'ajv';
+import { clipboard, dialog } from 'electron';
import { dump, load } from 'js-yaml';
+import { getMainWindow } from '@main/app/window';
import type { KV } from '@main/db/kv';
import exampleTemplateYaml from '@root/../../../examples/room-templates/red-blue-workroom.template.yaml?raw';
import {
@@ -231,6 +234,26 @@ export const roomTemplatesController = createRPCController({
params: (params: { yamlText: string }): ParamSpec[] =>
extractParams(parseYaml(params.yamlText).params),
+ /** Save YAML text to a file via the native save dialog. Returns the path, or
+ * null if the user cancelled. */
+ saveToFile: async (params: { yamlText: string; defaultName: string }): Promise<string | null> => {
+ const win = getMainWindow();
+ if (!win) return null;
+ const result = await dialog.showSaveDialog(win, {
+ title: 'Save room template',
+ defaultPath: params.defaultName,
+ filters: [{ name: 'YAML', extensions: ['yaml', 'yml'] }],
+ });
+ if (result.canceled || !result.filePath) return null;
+ await writeFile(result.filePath, params.yamlText, 'utf8');
+ return result.filePath;
+ },
+
+ /** Copy YAML text to the system clipboard. */
+ copyToClipboard: (params: { text: string }): void => {
+ clipboard.writeText(params.text);
+ },
+
parse: (params: { yamlText: string; schema?: Record<string, unknown> }): ParsedTemplate => {
const warnings: string[] = [];
const doc = parseYaml(params.yamlText);
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index b68cdf5ee..d34fadc41 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -105,16 +105,19 @@ import {
fetchRooms,
createTemplate,
deleteTemplate,
+ updateTemplate,
fetchTemplateDetail,
fetchTemplates,
GatewayError,
ownsOwnerAddressedAgent,
releaseBridgeIdentity,
createRoomFromTemplate,
+ exportRoomYaml,
fetchTemplateSchema,
removeRoomAgent,
type StoredTemplateDetail,
type StoredTemplateSummary,
+ type TemplateVisibility,
type ProvisionFromTemplateResult,
updateAddressingPolicy,
updateAgentIcon,
@@ -567,8 +570,10 @@ export const switchServersController = createRPCController({
listTemplates: async (params: {
serverId: string;
kind?: string;
+ /** Narrows to templates whose name or description contains it. */
+ q?: string;
}): Promise<StoredTemplateSummary[]> =>
- fetchTemplates(await requireServer(params.serverId), params.kind),
+ fetchTemplates(await requireServer(params.serverId), { kind: params.kind, q: params.q }),
getTemplateDetail: async (params: {
serverId: string;
@@ -579,12 +584,28 @@ export const switchServersController = createRPCController({
deleteTemplate: async (params: { serverId: string; templateId: string }): Promise<void> =>
deleteTemplate(await requireServer(params.serverId), params.templateId),
+ updateTemplate: async (params: {
+ serverId: string;
+ templateId: string;
+ name?: string;
+ description?: string;
+ kind?: string;
+ content?: string;
+ readVisibility?: TemplateVisibility;
+ writeVisibility?: TemplateVisibility;
+ }): Promise<StoredTemplateDetail> => {
+ const { serverId, templateId, ...changes } = params;
+ return updateTemplate(await requireServer(serverId), templateId, changes);
+ },
+
saveTemplate: async (params: {
serverId: string;
name: string;
description: string;
kind: string;
content: string;
+ readVisibility?: TemplateVisibility;
+ writeVisibility?: TemplateVisibility;
}): Promise<StoredTemplateDetail> => {
const { serverId, ...template } = params;
return createTemplate(await requireServer(serverId), template);
@@ -593,6 +614,9 @@ export const switchServersController = createRPCController({
fetchTemplateSchema: async (serverId: string): Promise<Record<string, unknown> | null> =>
fetchTemplateSchema(await requireServer(serverId)),
+ exportRoomYaml: async (params: { serverId: string; roomId: string }): Promise<string> =>
+ exportRoomYaml(await requireServer(params.serverId), params.roomId),
+
listAgentRooms: async (params: {
serverId: string;
agentId: string;
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index d7918c249..a3e4b6a05 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -1044,6 +1044,36 @@ export async function deleteAgent(server: SwitchServer, agentId: string): Promis
});
}
+/**
+ * Export a room's configuration as YAML (`GET /rooms/{roomId}/yaml`). Returns
+ * the raw YAML text, in the shape `POST /rooms/from-yaml` accepts, so the
+ * exported file round-trips through import unchanged.
+ *
+ * Each section can be dropped via its boolean toggles (default: all included).
+ */
+export async function exportRoomYaml(
+ server: SwitchServer,
+ roomId: string,
+ sections?: {
+ agents?: boolean;
+ users?: boolean;
+ references?: boolean;
+ docs?: boolean;
+ roles?: boolean;
+ }
+): Promise<string> {
+ const params = new URLSearchParams();
+ if (sections?.agents === false) params.set('agents', 'false');
+ if (sections?.users === false) params.set('users', 'false');
+ if (sections?.references === false) params.set('references', 'false');
+ if (sections?.docs === false) params.set('docs', 'false');
+ if (sections?.roles === false) params.set('roles', 'false');
+ const query = params.toString();
+ const path = `/rooms/${encodeURIComponent(roomId)}/yaml${query ? `?${query}` : ''}`;
+ const res = await gatewayFetch(server, path, { authenticated: true });
+ return res.text();
+}
+
/** The result of provisioning a room from a YAML template. */
export type TemplateProvisionResult = {
roomId: string;
@@ -1128,8 +1158,22 @@ export type StoredTemplateSummary = {
creator: string;
/** The owner's user id, so the Console can mark the signed-in user's own templates. */
ownerId: string | null;
+ /** Starts at 1 and goes up by one each time the document is changed. */
+ version: number;
+ /** `private` is seen by its owner and admins only. */
+ readVisibility: TemplateVisibility;
+ /** `public` lets anyone who can read it change it. */
+ writeVisibility: TemplateVisibility;
+ /** Whether the signed-in user may change the document, as the server judges
+ * it. Null when the server does not say. */
+ canEdit: boolean | null;
+ /** Whether the signed-in user may remove it or change who uses it: the
+ * owner, or an admin of the workspace. Null when the server does not say. */
+ canManage: boolean | null;
};
+export type TemplateVisibility = 'public' | 'private';
+
export type StoredTemplateDetail = StoredTemplateSummary & {
definition: string;
};
@@ -1141,6 +1185,11 @@ type RegistryTemplateSummary = {
name: string;
description: string;
kind: string;
+ version?: number;
+ read_visibility?: TemplateVisibility;
+ write_visibility?: TemplateVisibility;
+ can_edit?: boolean;
+ can_manage?: boolean;
};
function toSummary(t: RegistryTemplateSummary): StoredTemplateSummary {
@@ -1151,14 +1200,27 @@ function toSummary(t: RegistryTemplateSummary): StoredTemplateSummary {
kind: t.kind,
creator: t.owner_name ?? t.owner_id,
ownerId: t.owner_id,
+ // A server that does not report versions is read as being on the first.
+ version: t.version ?? 1,
+ // A server without visibility fields shares every template and lets its
+ // owner or an admin change it, which is what these defaults say.
+ readVisibility: t.read_visibility ?? 'public',
+ writeVisibility: t.write_visibility ?? 'private',
+ canEdit: t.can_edit ?? null,
+ canManage: t.can_manage ?? null,
};
}
+/** The templates the signed-in user may see, optionally narrowed by kind or
+ * by a search over name and description. */
export async function fetchTemplates(
server: SwitchServer,
- kind?: string
+ filter: { kind?: string; q?: string } = {}
): Promise<StoredTemplateSummary[]> {
- const qs = kind ? `?kind=${encodeURIComponent(kind)}` : '';
+ const params = new URLSearchParams();
+ if (filter.kind) params.set('kind', filter.kind);
+ if (filter.q) params.set('q', filter.q);
+ const qs = params.size > 0 ? `?${params}` : '';
const res = await gatewayFetch(server, `/templates${qs}`, {
authenticated: true,
});
@@ -1169,12 +1231,55 @@ export async function fetchTemplates(
/** Store a template document on the server's registry (`POST /templates`). */
export async function createTemplate(
server: SwitchServer,
- params: { name: string; description: string; kind: string; content: string }
+ params: {
+ name: string;
+ description: string;
+ kind: string;
+ content: string;
+ readVisibility?: TemplateVisibility;
+ writeVisibility?: TemplateVisibility;
+ }
): Promise<StoredTemplateDetail> {
+ const { readVisibility, writeVisibility, ...rest } = params;
const res = await gatewayFetch(server, '/templates', {
authenticated: true,
method: 'POST',
- body: params,
+ body: {
+ ...rest,
+ // Left out when unset: a server without visibility refuses unknown fields.
+ ...(readVisibility ? { read_visibility: readVisibility } : {}),
+ ...(writeVisibility ? { write_visibility: writeVisibility } : {}),
+ },
+ });
+ const t = (await res.json()) as RegistryTemplateSummary & { content: string };
+ return { ...toSummary(t), definition: t.content };
+}
+
+/** Change a stored template (`PATCH /templates/{id}`). The server answers
+ * 404 for a template the caller may not read, 403 for one they may not
+ * edit, and 409 when the owner already has a template by the new name. */
+export async function updateTemplate(
+ server: SwitchServer,
+ templateId: string,
+ changes: {
+ name?: string;
+ description?: string;
+ /** The listing label, sent when an edit changed the document's shape. */
+ kind?: string;
+ content?: string;
+ readVisibility?: TemplateVisibility;
+ writeVisibility?: TemplateVisibility;
+ }
+): Promise<StoredTemplateDetail> {
+ const { readVisibility, writeVisibility, ...rest } = changes;
+ const res = await gatewayFetch(server, `/templates/${encodeURIComponent(templateId)}`, {
+ authenticated: true,
+ method: 'PATCH',
+ body: {
+ ...rest,
+ ...(readVisibility ? { read_visibility: readVisibility } : {}),
+ ...(writeVisibility ? { write_visibility: writeVisibility } : {}),
+ },
});
const t = (await res.json()) as RegistryTemplateSummary & { content: string };
return { ...toSummary(t), definition: t.content };
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/update-template.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-template.test.ts
new file mode 100644
index 000000000..e799f8eca
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/update-template.test.ts
@@ -0,0 +1,94 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const refreshSession = vi.hoisted(() => vi.fn());
+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
+const managedServerHostBlocked = vi.hoisted(() => vi.fn(() => null));
+const managedServerStoppedPhase = vi.hoisted(() => vi.fn(() => null));
+
+vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
+ managedServerHostBlocked,
+ managedServerStoppedPhase,
+}));
+vi.mock('./servers-store', () => ({ getSessionCookie }));
+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
+
+const { updateTemplate, GatewayError } = await import('./gateway-client');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ gatewayUrl: 'https://switch.example.com',
+ managed: false,
+} as never;
+
+function validJwt(): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + 24 * 60 * 60;
+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');
+ return `${header}.${payload}.sig`;
+}
+
+function response(status: number, body: unknown): Response {
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ json: async () => body,
+ headers: { getSetCookie: () => [] },
+ text: async () => JSON.stringify(body),
+ } as unknown as Response;
+}
+
+const STORED = {
+ id: 'tpl/1',
+ owner_id: 'u1',
+ owner_name: 'Ana',
+ name: 'Triage pair',
+ description: 'Two agents and their room',
+ kind: 'group',
+ version: 3,
+ content: 'room:\n name: n\n',
+};
+
+const fetchMock = vi.fn();
+
+describe('updateTemplate', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(validJwt());
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('patches only the fields that changed and returns the new version', async () => {
+ fetchMock.mockResolvedValue(response(200, STORED));
+
+ const saved = await updateTemplate(SERVER, 'tpl/1', {
+ description: 'Two agents and their room',
+ });
+
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://switch.example.com/gateway/templates/tpl%2F1');
+ expect(init.method).toBe('PATCH');
+ expect(JSON.parse(init.body)).toEqual({ description: 'Two agents and their room' });
+ expect(saved).toMatchObject({ id: 'tpl/1', version: 3, definition: STORED.content });
+ });
+
+ it('sends the new kind alongside a document whose shape changed', async () => {
+ fetchMock.mockResolvedValue(response(200, STORED));
+ await updateTemplate(SERVER, 'tpl/1', { content: 'agent:\n name: a\n', kind: 'agent' });
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init.body)).toEqual({ content: 'agent:\n name: a\n', kind: 'agent' });
+ });
+
+ it('reports a name the owner already uses', async () => {
+ fetchMock.mockResolvedValue(response(409, { detail: 'You already have a template named x' }));
+
+ await expect(updateTemplate(SERVER, 'tpl/1', { name: 'x' })).rejects.toBeInstanceOf(
+ GatewayError
+ );
+ });
+});
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.ts
index 205db09aa..fbd991036 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,7 @@ import { homeView } from '@renderer/app/home-view';
import { locationView } from '@renderer/features/locations/view';
import { remoteHostView } from '@renderer/features/remote-hosts/views/remote-host-view';
import { remoteHostsView } from '@renderer/features/remote-hosts/views/remote-hosts-view';
+import { templateCaptureView } from '@renderer/features/room-templates/room-template-capture-view';
import { templateImportView } from '@renderer/features/room-templates/room-template-import-view';
import { sessionView } from '@renderer/features/sessions/view';
import { settingsView } from '@renderer/features/settings/settings-view';
@@ -35,6 +36,7 @@ export const views = {
templates: templatesView,
templateDetail: templateDetailView,
templateUse: templateUseView,
+ templateCapture: templateCaptureView,
// oxlint-disable-next-line typescript/no-explicit-any
} satisfies Record<string, ViewDefinition<any>>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx
new file mode 100644
index 000000000..f6f3bddca
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-capture-view.tsx
@@ -0,0 +1,454 @@
+import { parameterize, type ParamSubstitution } from '@switch-console/shared';
+import { CheckSquare, FileText, Loader2 } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import type { ParsedTemplate } from '@main/core/room-templates/controller';
+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
+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 { prefillForSave } from '@renderer/features/templates/agent-template-data';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
+import { useModalContext } from '@renderer/lib/modal/modal-provider';
+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
+import { Button } from '@renderer/lib/ui/button';
+import { Input } from '@renderer/lib/ui/input';
+
+type CaptureStep = 'loading' | 'preview' | 'error';
+
+/** Candidate fields the user can promote to params. */
+type Candidate = {
+ /** Identity of the row. The key is what the user edits, so it cannot be the identity. */
+ id: number;
+ /** The param key, as suggested, until the user edits it. */
+ key: string;
+ /** Human label for the field, e.g. "Room name" */
+ label: string;
+ /** The literal value that will be replaced. */
+ value: string;
+ checked: boolean;
+};
+
+/** Parse the exported YAML to find parameterizable values. */
+function extractCandidates(yamlText: string): Candidate[] {
+ const candidates: Omit<Candidate, 'id'>[] = [];
+
+ // A one-line scalar. A block header (`|`, `|-`, `>`) is not a value: the
+ // exporter writes multi-line text that way, and its body cannot be one
+ // literal to replace.
+ const scalarOf = (m: RegExpMatchArray | null): string | null => {
+ if (!m) return null;
+ const raw = m[1].trim();
+ if (/^[|>](?:[-+]?\d*|\d*[-+]?)$/.test(raw)) return null;
+ const val = raw.replace(/^['"]|['"]$/g, '');
+ return val || null;
+ };
+
+ const name = scalarOf(yamlText.match(/^\s*name:\s+(.+)$/m));
+ if (name) candidates.push({ key: 'name', label: 'Room name', value: name, checked: false });
+
+ const description = scalarOf(yamlText.match(/^\s*description:\s+(.+)$/m));
+ if (description) {
+ candidates.push({
+ key: 'description',
+ label: 'Description',
+ value: description,
+ checked: false,
+ });
+ }
+
+ const agentSection = yamlText.match(/^\s*agents:\s*\n((?:\s*-\s+.+\n?)*)/m);
+ if (agentSection) {
+ const lines = agentSection[1].matchAll(/^\s*-\s+(.+)$/gm);
+ let i = 0;
+ for (const m of lines) {
+ const val = m[1].replace(/^['"]|['"]$/g, '');
+ if (val) {
+ const key = i === 0 ? 'deploy_agent' : `agent_${i}`;
+ candidates.push({ key, label: `Agent ${val}`, value: val, checked: false });
+ i++;
+ }
+ }
+ }
+
+ // The instructions: a one-line value, or the body of a block scalar,
+ // which is every following line indented deeper than the `instructions:`
+ // line. A repository URL in there is worth a param.
+ const lines = yamlText.split('\n');
+ const at = lines.findIndex((l) => /^\s*instructions:/.test(l));
+ if (at >= 0) {
+ const header = lines[at];
+ const indent = header.match(/^ */)?.[0].length ?? 0;
+ const inline = header.replace(/^\s*instructions:\s*/, '');
+ const body: string[] = [];
+ for (const l of lines.slice(at + 1)) {
+ if (l.trim() !== '' && (l.match(/^ */)?.[0].length ?? 0) <= indent) break;
+ body.push(l);
+ }
+ const instrText = /^[|>]/.test(inline) ? body.join('\n') : inline;
+ const repoMatch = instrText.match(/https?:\/\/github\.com\/[\w./-]+/);
+ if (repoMatch) {
+ candidates.push({
+ key: 'repository',
+ label: 'Repository in instructions',
+ value: repoMatch[0],
+ checked: false,
+ });
+ }
+ }
+
+ return candidates.map((c, id) => ({ ...c, id }));
+}
+
+// ── Parameterize row ────────────────────────────────────────────────────────
+
+function CandidateRow({
+ candidate,
+ onToggle,
+ onKeyChange,
+}: {
+ candidate: Candidate;
+ onToggle: () => void;
+ onKeyChange: (key: string) => void;
+}) {
+ return (
+ <div className="flex items-center gap-3 rounded-md border border-border px-4 py-2.5">
+ <span className="min-w-0 shrink-0 text-sm text-foreground">{candidate.label} →</span>
+ <div className="flex flex-1 items-center justify-end gap-2">
+ {candidate.checked ? (
+ <>
+ <span className="font-mono text-sm text-foreground">{'{'}</span>
+ <Input
+ value={candidate.key}
+ onChange={(e) => onKeyChange(e.target.value.replace(/[^A-Za-z0-9_]/g, ''))}
+ className="h-7 w-28 font-mono text-sm"
+ />
+ <span className="font-mono text-sm text-foreground">{'}'}</span>
+ <span className="text-xs text-foreground-passive">
+ · was &quot;{candidate.value}&quot;
+ </span>
+ </>
+ ) : (
+ <span className="text-sm text-foreground-passive">keep literal</span>
+ )}
+ <input
+ type="checkbox"
+ checked={candidate.checked}
+ onChange={onToggle}
+ className="ml-1 size-4 rounded border-border"
+ />
+ </div>
+ </div>
+ );
+}
+
+// ── Round-trip check sidebar ────────────────────────────────────────────────
+
+function RoundTripCheck({
+ parsed,
+ candidates,
+ parameterizeOk,
+ parameterizeError,
+}: {
+ parsed: ParsedTemplate | null;
+ candidates: Candidate[];
+ parameterizeOk: boolean;
+ /** Why the substitution was refused, when it was. */
+ parameterizeError: string | null;
+}) {
+ const checkedCount = candidates.filter((c) => c.checked).length;
+ const allHaveDefaults = candidates.filter((c) => c.checked).every((c) => c.value !== '');
+ const parsesOk = parsed !== null && parsed.warnings.length === 0 && parameterizeOk;
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h3 className="mb-3 text-sm font-semibold text-foreground">Round-trip check</h3>
+ <div className="space-y-2">
+ <CheckItem ok={parsesOk}>Parses as a valid template</CheckItem>
+ {parameterizeError && <p className="text-xs text-destructive">{parameterizeError}</p>}
+ <CheckItem ok={checkedCount > 0 ? allHaveDefaults : true}>
+ {checkedCount > 0
+ ? `${checkedCount} param${checkedCount > 1 ? 's' : ''}, ${allHaveDefaults ? 'all' : 'not all'} with defaults`
+ : 'No params (literal export)'}
+ </CheckItem>
+ </div>
+ </div>
+ <div>
+ <h3 className="mb-2 text-sm font-semibold text-foreground">Share it</h3>
+ <p className="text-xs leading-relaxed text-foreground-passive">
+ Post the file in the team channel: &quot;try importing this in your Console.&quot;
+ That&apos;s the whole loop — capture here, import on the other side.
+ </p>
+ </div>
+ </div>
+ );
+}
+
+function CheckItem({ ok, children }: { ok: boolean; children: React.ReactNode }) {
+ return (
+ <div className="flex items-start gap-2">
+ <CheckSquare
+ className={`mt-0.5 size-4 shrink-0 ${ok ? 'text-green-600' : 'text-foreground-passive'}`}
+ />
+ <span className="text-sm text-foreground">{children}</span>
+ </div>
+ );
+}
+
+// ── Main view ───────────────────────────────────────────────────────────────
+
+function useCaptureParams() {
+ return useParams('templateCapture').params;
+}
+
+const CaptureTitlebar = observer(function CaptureTitlebar() {
+ const { serverId, roomId } = useCaptureParams();
+ const roomName = switchRoomsStore.roomNameById(roomId);
+ return (
+ <ServerSectionTitlebar
+ serverId={serverId}
+ icon={FileText}
+ label={roomName ? `${roomName} / Capture as template` : 'Capture as template'}
+ />
+ );
+});
+
+const CapturePanel = observer(function CapturePanel() {
+ const { serverId, roomId } = useCaptureParams();
+ const roomName = switchRoomsStore.roomNameById(roomId);
+
+ const [step, setStep] = useState<CaptureStep>('loading');
+ const [originalYaml, setOriginalYaml] = useState('');
+ const [candidates, setCandidates] = useState<Candidate[]>([]);
+ const [error, setError] = useState<string | null>(null);
+ const [saved, setSaved] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(
+ () => () => {
+ if (copyTimerRef.current !== null) clearTimeout(copyTimerRef.current);
+ },
+ []
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const yaml = await rpc.switchServers.exportRoomYaml({ serverId, roomId });
+ if (cancelled) return;
+ setOriginalYaml(yaml);
+ setCandidates(extractCandidates(yaml));
+ setStep('preview');
+ } catch (e) {
+ if (!cancelled) {
+ setError(failureText(e, 'Could not export this room.'));
+ setStep('error');
+ }
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [serverId, roomId]);
+
+ const handleToggle = useCallback((id: number) => {
+ setCandidates((prev) => prev.map((c) => (c.id === id ? { ...c, checked: !c.checked } : c)));
+ setSaved(false);
+ setCopied(false);
+ }, []);
+
+ const handleKeyChange = useCallback((id: number, newKey: string) => {
+ setCandidates((prev) => prev.map((c) => (c.id === id ? { ...c, key: newKey } : c)));
+ setSaved(false);
+ setCopied(false);
+ }, []);
+
+ // The check reports on the document that is saved or copied, not on the
+ // raw export: a substitution can break a document the export parsed.
+ const [outputParsed, setOutputParsed] = useState<ParsedTemplate | null>(null);
+ const { parameterizedYaml, parameterizeOk, parameterizeError } = useMemo(() => {
+ const checked = candidates.filter((c) => c.checked);
+ if (checked.length === 0)
+ return { parameterizedYaml: originalYaml, parameterizeOk: true, parameterizeError: null };
+ const subs: ParamSubstitution[] = checked.map((c) => ({ key: c.key, value: c.value }));
+ try {
+ return {
+ parameterizedYaml: parameterize(originalYaml, subs),
+ parameterizeOk: true,
+ parameterizeError: null,
+ };
+ } catch (e) {
+ return {
+ parameterizedYaml: originalYaml,
+ parameterizeOk: false,
+ parameterizeError: failureText(e, 'The params could not be applied.'),
+ };
+ }
+ }, [originalYaml, candidates]);
+ useEffect(() => {
+ if (step !== 'preview') return;
+ let cancelled = false;
+ setOutputParsed(null);
+ rpc.roomTemplates
+ .parse({ yamlText: parameterizedYaml })
+ .then((p) => {
+ if (!cancelled) setOutputParsed(p);
+ })
+ .catch(() => {
+ if (!cancelled) setOutputParsed(null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [parameterizedYaml, step]);
+
+ const handleSave = useCallback(async () => {
+ const slug = (roomName ?? 'room').replace(/[^a-z0-9_-]/gi, '-').toLowerCase();
+ const result = await rpc.roomTemplates.saveToFile({
+ yamlText: parameterizedYaml,
+ defaultName: `${slug}.yaml`,
+ });
+ if (result) setSaved(true);
+ }, [parameterizedYaml, roomName]);
+
+ const { showModal } = useModalContext();
+ const { navigate } = useNavigate();
+ const handleSaveToWorkspace = useCallback(async () => {
+ const prefill = await prefillForSave(parameterizedYaml, null);
+ showModal('saveTemplateModal', {
+ serverId,
+ serverName: switchServersStore.servers.find((sv) => sv.id === serverId)?.name ?? null,
+ content: parameterizedYaml,
+ ...prefill,
+ // `prefillForSave` answers a generic name when the room's name holds a
+ // placeholder; a captured room has a real name to use instead.
+ name: prefill.name === 'Room template' && roomName ? roomName : prefill.name,
+ onSuccess: ({ id }) => navigate('templateDetail', { serverId, templateId: id }),
+ });
+ }, [parameterizedYaml, serverId, roomName, showModal, navigate]);
+
+ const handleCopy = useCallback(() => {
+ void rpc.roomTemplates.copyToClipboard({ text: parameterizedYaml });
+ setCopied(true);
+ if (copyTimerRef.current !== null) clearTimeout(copyTimerRef.current);
+ copyTimerRef.current = setTimeout(() => setCopied(false), 2000);
+ }, [parameterizedYaml]);
+
+ if (step === 'loading') {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <Loader2 className="size-6 animate-spin text-foreground-passive" />
+ <span className="ml-2 text-sm text-foreground-passive">Exporting room…</span>
+ </div>
+ );
+ }
+
+ if (step === 'error') {
+ return (
+ <div className="mx-auto w-full max-w-4xl p-6">
+ <Alert variant="destructive">
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ </div>
+ );
+ }
+
+ return (
+ <div className="relative z-10 flex min-h-0 flex-1 overflow-auto bg-background">
+ {/* Main content */}
+ <div className="flex-1 p-6">
+ <div className="mx-auto max-w-3xl space-y-6">
+ <header>
+ <h2 className="text-2xl font-semibold text-foreground">Capture as template</h2>
+ <p className="mt-1 text-sm text-foreground-muted">
+ This room, packaged as a shareable file.
+ </p>
+ </header>
+
+ {/* Parameterize section */}
+ {candidates.length > 0 && (
+ <div>
+ <h3 className="mb-3 text-sm font-semibold text-foreground">Parameterize</h3>
+ <div className="space-y-2">
+ {candidates.map((c) => (
+ <CandidateRow
+ key={c.id}
+ candidate={c}
+ onToggle={() => handleToggle(c.id)}
+ onKeyChange={(newKey) => handleKeyChange(c.id, newKey)}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Preview */}
+ <div>
+ <h3 className="mb-3 text-sm font-semibold text-foreground">Preview</h3>
+ <pre className="max-h-80 overflow-auto rounded-md border border-border bg-background-secondary p-4 font-mono text-xs leading-relaxed">
+ {parameterizedYaml}
+ </pre>
+ </div>
+
+ {/* Buttons — stacked full width */}
+ <div className="flex flex-col gap-2">
+ {/* Every way out carries the same document, so a document the
+ substitution refused is offered by none of them. */}
+ <Button
+ variant="outline"
+ className="w-full"
+ disabled={!parameterizeOk}
+ onClick={handleCopy}
+ >
+ {copied ? 'Copied!' : 'Copy YAML'}
+ </Button>
+ <Button
+ variant="outline"
+ className="w-full"
+ disabled={!parameterizeOk}
+ onClick={handleSave}
+ >
+ {saved ? 'Saved!' : 'Save file…'}
+ </Button>
+ <Button
+ className="w-full"
+ disabled={!parameterizeOk}
+ onClick={() => void handleSaveToWorkspace()}
+ >
+ Save to workspace
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ {/* Right sidebar */}
+ <aside className="w-72 shrink-0 border-l border-border p-6">
+ <RoundTripCheck
+ parsed={outputParsed}
+ candidates={candidates}
+ parameterizeOk={parameterizeOk}
+ parameterizeError={parameterizeError}
+ />
+ </aside>
+ </div>
+ );
+});
+
+export const templateCaptureView = {
+ WrapView: ({ children }: { children: React.ReactNode; serverId: string; roomId: string }) => (
+ <>{children}</>
+ ),
+ TitlebarSlot: CaptureTitlebar,
+ MainPanel: CapturePanel,
+ canActivate: (params: unknown): GuardResult => {
+ const p = params as { serverId?: unknown; roomId?: unknown } | null;
+ if (!p || typeof p.serverId !== 'string' || typeof p.roomId !== 'string') {
+ return { ok: false, redirect: 'home' };
+ }
+ return { ok: true };
+ },
+} satisfies ViewDefinition<{ serverId: string; roomId: string }>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
index 165cb1c6d..ea7f4c836 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
@@ -7,7 +7,13 @@ import { ServerPage } 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 { prefillForSave } from '@renderer/features/templates/agent-template-data';
+import {
+ TEMPLATE_ACCESS_OPTIONS,
+ type TemplateAccess,
+ visibilityOf,
+} from '@renderer/features/templates/template-visibility';
import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { useModalContext } from '@renderer/lib/modal/modal-provider';
@@ -15,6 +21,8 @@ import { appState } from '@renderer/lib/stores/app-state';
import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
// ── Source step ─────────────────────────────────────────────────────────────
@@ -34,6 +42,7 @@ function SourceStep({
onFileSelect,
onSaveToServer,
saving,
+ editing,
}: {
yamlText: string;
onYamlChange: (text: string) => void;
@@ -42,6 +51,8 @@ function SourceStep({
onFileSelect: (name: string) => void;
onSaveToServer: () => void;
saving: boolean;
+ /** Set when the document belongs to a stored template: the actions become Cancel and Save changes. */
+ editing?: { onCancel: () => void; onSave: () => void; canSave: boolean };
}) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false);
@@ -147,22 +158,45 @@ function SourceStep({
</Alert>
)}
- <div className="flex items-center justify-end gap-2 pt-2">
- <Button variant="outline" disabled={!yamlText.trim() || saving} onClick={onSaveToServer}>
- <Save className="mr-1.5 size-3.5" />
- {saving ? 'Saving…' : 'Save to workspace'}
- </Button>
- <Button disabled={!yamlText.trim() || saving} onClick={onNext}>
- Next
- <ArrowRight className="ml-1.5 size-3.5" />
- </Button>
- </div>
+ {editing ? (
+ <div className="flex items-center justify-end gap-2 pt-2">
+ <Button variant="outline" disabled={saving} onClick={editing.onCancel}>
+ Cancel
+ </Button>
+ <Button disabled={!editing.canSave || saving} onClick={editing.onSave}>
+ <Save className="mr-1.5 size-3.5" />
+ {saving ? 'Saving…' : 'Save changes'}
+ </Button>
+ </div>
+ ) : (
+ <div className="flex items-center justify-end gap-2 pt-2">
+ <Button variant="outline" disabled={!yamlText.trim() || saving} onClick={onSaveToServer}>
+ <Save className="mr-1.5 size-3.5" />
+ {saving ? 'Saving…' : 'Save to workspace'}
+ </Button>
+ <Button disabled={!yamlText.trim() || saving} onClick={onNext}>
+ Next
+ <ArrowRight className="ml-1.5 size-3.5" />
+ </Button>
+ </div>
+ )}
</div>
);
}
// ── Main view ──────────────────────────────────────────────────────────────
+type EditingTemplate = {
+ id: string;
+ name: string;
+ description: string;
+ /** The stored listing label: agent, room or group. */
+ kind: string;
+ access: TemplateAccess;
+ /** Only the owner or an admin decides who may see or change a template. */
+ canChangeAccess: boolean;
+};
+
function useServerId(): string {
return useParams('templateImport').params.serverId;
}
@@ -174,7 +208,7 @@ const TemplateImportTitlebar = observer(function TemplateImportTitlebar() {
serverId={serverId}
icon={FileText}
label="Templates"
- item={{ label: 'Import' }}
+ item={{ label: useParams('templateImport').params.editingTemplate ? 'Edit' : 'Import' }}
onSectionClick={() => appState.navigation.navigate('templates', { serverId })}
/>
);
@@ -188,11 +222,15 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {
sourceName: initialName,
templateId: initialTemplateId,
edit: editing,
+ editingTemplate,
} = useParams('templateImport').params;
const [yamlText, setYamlText] = useState(initialYaml ?? '');
const [saving, setSaving] = useState(false);
const [parseError, setParseError] = useState<string | null>(null);
const [sourceName, setSourceName] = useState<string | null>(initialName ?? null);
+ const [name, setName] = useState(editingTemplate?.name ?? '');
+ const [description, setDescription] = useState(editingTemplate?.description ?? '');
+ const [access, setAccess] = useState<TemplateAccess>(editingTemplate?.access ?? 'shared');
// Parse before navigating so a syntax error is shown next to the editor,
// where it can be fixed, rather than on the Use page.
@@ -236,6 +274,40 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {
}
}, [yamlText, sourceName, serverId, showModal]);
+ const handleSaveChanges = useCallback(async () => {
+ if (!editingTemplate) return;
+ setSaving(true);
+ setParseError(null);
+ try {
+ // A document that does not parse could not be used by anyone afterwards.
+ await rpc.agentTemplates.parseAgents({ yamlText });
+ const coreYaml = await rpc.agentTemplates.serverDocument({ yamlText });
+ if (coreYaml) await rpc.roomTemplates.parse({ yamlText: coreYaml });
+ // The listing files a template by its stored label, so an edit that
+ // changes the document's shape carries the new label with it.
+ const kind = yamlText !== initialYaml ? await rpc.agentTemplates.kind({ yamlText }) : null;
+ // Each field is sent only when changed, so saving one cannot put back
+ // another that someone else changed meanwhile.
+ const saved = await rpc.switchServers.updateTemplate({
+ serverId,
+ templateId: editingTemplate.id,
+ ...(name.trim() !== editingTemplate.name.trim() ? { name: name.trim() } : {}),
+ ...(description.trim() !== editingTemplate.description.trim()
+ ? { description: description.trim() }
+ : {}),
+ ...(yamlText !== initialYaml ? { content: yamlText } : {}),
+ ...(kind !== null && kind !== editingTemplate.kind ? { kind } : {}),
+ ...(access !== editingTemplate.access ? visibilityOf(access) : {}),
+ });
+ toast({ title: `"${saved.name}" saved`, description: `Version ${saved.version}.` });
+ appState.navigation.navigate('templateDetail', { serverId, templateId: saved.id });
+ } catch (e) {
+ setParseError(failureText(e, 'Could not save the changes.'));
+ } finally {
+ setSaving(false);
+ }
+ }, [editingTemplate, yamlText, initialYaml, name, description, access, serverId]);
+
// When this page is opened with a document already chosen (a dropped file,
// a recent, a template id), there is nothing to edit here: go on to the
// Use page.
@@ -255,6 +327,73 @@ const TemplateImportPanel = observer(function TemplateImportPanel() {
}
}, [initialTemplateId, initialYaml, editing, serverId, handleParseAndAdvance]);
+ if (editingTemplate) {
+ const nothingChanged =
+ yamlText === initialYaml &&
+ name.trim() === editingTemplate.name &&
+ description.trim() === editingTemplate.description &&
+ access === editingTemplate.access;
+ return (
+ <ServerPage
+ title={`Edit ${editingTemplate.name}`}
+ description="The change reaches the workspace as soon as it is saved."
+ >
+ <div className="flex flex-col gap-4">
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="template-name">Name</FieldLabel>
+ <Input id="template-name" value={name} onChange={(e) => setName(e.target.value)} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="template-description">
+ Description <span className="text-foreground-muted">(optional)</span>
+ </FieldLabel>
+ <Input
+ id="template-description"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="What it is for, in a line"
+ />
+ </Field>
+ {editingTemplate.canChangeAccess && (
+ <Field>
+ <FieldLabel>Who can use it</FieldLabel>
+ <SegmentedControl
+ value={access}
+ onChange={setAccess}
+ options={TEMPLATE_ACCESS_OPTIONS}
+ ariaLabel="Who can use it"
+ className="w-max"
+ />
+ <p className="text-xs text-foreground-muted">
+ {TEMPLATE_ACCESS_OPTIONS.find((o) => o.value === access)?.hint}
+ </p>
+ </Field>
+ )}
+ </FieldGroup>
+ <SourceStep
+ yamlText={yamlText}
+ onYamlChange={setYamlText}
+ parseError={parseError}
+ onNext={handleParseAndAdvance}
+ onFileSelect={setSourceName}
+ onSaveToServer={handleSaveToServer}
+ saving={saving}
+ editing={{
+ onCancel: () =>
+ appState.navigation.navigate('templateDetail', {
+ serverId,
+ templateId: editingTemplate.id,
+ }),
+ onSave: () => void handleSaveChanges(),
+ canSave: !nothingChanged && name.trim().length > 0 && yamlText.trim().length > 0,
+ }}
+ />
+ </div>
+ </ServerPage>
+ );
+ }
+
return (
<ServerPage
title="Import a template"
@@ -286,6 +425,8 @@ export const templateImportView = {
templateId?: string;
/** Show `yamlText` in the editor instead of passing it on to the Use page. */
edit?: boolean;
+ /** The stored template `yamlText` belongs to. The page then saves changes to it. */
+ editingTemplate?: EditingTemplate;
}) => <>{children}</>,
TitlebarSlot: TemplateImportTitlebar,
MainPanel: TemplateImportPanel,
@@ -303,4 +444,5 @@ export const templateImportView = {
sourceName?: string;
templateId?: string;
edit?: boolean;
+ editingTemplate?: EditingTemplate;
}>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
index 0bc81fee9..0398d3a8d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
@@ -89,6 +89,11 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
kind,
creator,
ownerId: null,
+ version: 1,
+ readVisibility: 'public' as const,
+ writeVisibility: 'private' as const,
+ canEdit: false,
+ canManage: false,
})),
...onWorkspace,
];
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index af436450b..0e827fc81 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -91,7 +91,7 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
return (
<div className="h-full overflow-y-auto">
<div className="mx-auto flex w-full max-w-4xl flex-col gap-8 px-10 py-8">
- <RoomHeading room={room} />
+ <RoomHeading serverId={serverId} room={room} />
{/* Keyed on the room so the drafts below belong to the room on screen:
switching rooms starts a fresh form rather than carrying half-typed
text across. */}
@@ -154,8 +154,9 @@ const DeleteRoomSection = observer(function DeleteRoomSection({
);
});
-function RoomHeading({ room }: { room: RemoteRoomDetail }) {
+function RoomHeading({ serverId, room }: { serverId: string; room: RemoteRoomDetail }) {
const platform = bridgePlatformLabel(room.bridgeType);
+ const { navigate } = useNavigate();
return (
<div className="flex items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
@@ -166,19 +167,29 @@ function RoomHeading({ room }: { room: RemoteRoomDetail }) {
: 'Room with no messaging app'}
</p>
</div>
- {room.externalChannelUrl && (
- <div className="flex shrink-0 items-center gap-2">
- {room.bridgeDisplayName && (
- <span className="rounded-md bg-[var(--fill)] px-2.5 py-1.5 text-xs text-foreground-muted">
- {room.bridgeDisplayName}
- </span>
- )}
- <Button variant="outline" size="sm" onClick={() => openRoomChannel(room.id)}>
- <ExternalLink className="size-3.5" />
- Open in {platform}
- </Button>
- </div>
- )}
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}
+ >
+ <FileText className="size-3.5" />
+ Capture as template
+ </Button>
+ {room.externalChannelUrl && (
+ <>
+ {room.bridgeDisplayName && (
+ <span className="rounded-md bg-[var(--fill)] px-2.5 py-1.5 text-xs text-foreground-muted">
+ {room.bridgeDisplayName}
+ </span>
+ )}
+ <Button variant="outline" size="sm" onClick={() => openRoomChannel(room.id)}>
+ <ExternalLink className="size-3.5" />
+ Open in {platform}
+ </Button>
+ </>
+ )}
+ </div>
</div>
);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
index aac7d16b5..0d1a433ad 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
@@ -15,6 +15,8 @@ import {
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 { TEMPLATE_ACCESS_OPTIONS, type TemplateAccess, visibilityOf } from './template-visibility';
export type SaveTemplateArgs = {
serverId: string;
@@ -47,6 +49,7 @@ export function SaveTemplateModal({
const descriptionId = useId();
const [name, setName] = useState(initialName);
const [description, setDescription] = useState(initialDescription);
+ const [access, setAccess] = useState<TemplateAccess>('shared');
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -60,6 +63,7 @@ export function SaveTemplateModal({
description: description.trim(),
kind,
content,
+ ...visibilityOf(access),
});
toast({
title: `"${name.trim()}" is now on ${serverName ?? 'the server'}`,
@@ -95,8 +99,7 @@ export function SaveTemplateModal({
>
<DialogContentArea className="gap-4">
<p className="text-sm text-foreground-muted">
- Everyone on this workspace will find it under Templates.{' '}
- <Badge variant="outline">{kind} template</Badge>
+ Saved under Templates on this workspace. <Badge variant="outline">{kind} template</Badge>
</p>
<FieldGroup>
<Field>
@@ -120,6 +123,19 @@ export function SaveTemplateModal({
placeholder="What it is for, in a line"
/>
</Field>
+ <Field>
+ <FieldLabel>Who can use it</FieldLabel>
+ <SegmentedControl
+ value={access}
+ onChange={setAccess}
+ options={TEMPLATE_ACCESS_OPTIONS}
+ ariaLabel="Who can use it"
+ className="w-max"
+ />
+ <p className="text-xs text-foreground-muted">
+ {TEMPLATE_ACCESS_OPTIONS.find((o) => o.value === access)?.hint}
+ </p>
+ </Field>
</FieldGroup>
{error && (
<Alert variant="destructive">
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
index 6a955a1be..a078cdabf 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
@@ -7,6 +7,7 @@ import {
Download,
FileText,
Loader2,
+ Pencil,
Trash2,
} from 'lucide-react';
import { observer } from 'mobx-react-lite';
@@ -25,6 +26,7 @@ import { Button } from '@renderer/lib/ui/button';
import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';
import { cn } from '@renderer/utils/utils';
import { type LoadedTemplate, loadTemplateById } from './agent-template-data';
+import { accessLine, accessOf } from './template-visibility';
import { isRequired, paramLabel, typeLabel } from './use/use-template-model';
function useViewParams() {
@@ -213,7 +215,14 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
}
const mine = loaded.server !== null && me !== null && loaded.server.ownerId === me.id;
- const canDelete = loaded.server !== null && (mine || me?.role === 'admin');
+ // The server says what this user may do: it knows who administers the
+ // workspace, which the user's global role does not tell. An older server
+ // leaves the answer out, and the owner-or-admin guess stands in.
+ const canManage =
+ loaded.server !== null && (loaded.server.canManage ?? (mine || me?.role === 'admin'));
+ const canEdit =
+ loaded.server !== null &&
+ (loaded.server.canEdit ?? (canManage || loaded.server.writeVisibility === 'public'));
const singleAgent = loaded.kind === 'agent' ? (loaded.agents[0] ?? null) : null;
// In a single-agent document the room refers to the agent as `{agent}`. The
// Console fills that in with the agent's name, so it is not an input to list.
@@ -288,7 +297,9 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
: mine
? 'Yours'
: `Uploaded by ${loaded.server?.creator ?? 'someone'}`;
- const visibilityLine = loaded.server ? 'Shared with the workspace' : 'Shared with everyone';
+ const visibilityLine = loaded.server
+ ? accessLine(accessOf(loaded.server))
+ : 'Shared with everyone';
return (
<div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">
@@ -303,6 +314,12 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
<span>{ownerLine}</span>
<span>·</span>
<span>{visibilityLine}</span>
+ {loaded.server && loaded.server.version > 1 && (
+ <>
+ <span>·</span>
+ <span>Version {loaded.server.version}</span>
+ </>
+ )}
{loaded.copyOf && (
<>
<span>·</span>
@@ -347,7 +364,33 @@ const TemplateDetailPanel = observer(function TemplateDetailPanel() {
{busy === 'save' ? 'Saving…' : 'Save to workspace'}
</Button>
)}
- {canDelete && (
+ {canEdit && loaded.server && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy !== null}
+ onClick={() =>
+ navigate('templateImport', {
+ serverId,
+ yamlText: loaded.document,
+ edit: true,
+ editingTemplate: {
+ id: loaded.server!.id,
+ name: loaded.name,
+ description: loaded.description,
+ kind: loaded.server!.kind,
+ access: accessOf(loaded.server!),
+ canChangeAccess: canManage,
+ },
+ })
+ }
+ >
+ <Pencil className="size-3.5" />
+ Edit
+ </Button>
+ )}
+ {canManage && (
<Button
type="button"
variant="outline"
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-visibility.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/template-visibility.ts
new file mode 100644
index 000000000..7c638e551
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-visibility.ts
@@ -0,0 +1,40 @@
+import type { TemplateVisibility } from '@main/core/switch-servers/gateway-client';
+
+/** The three settings a template can have, as one choice rather than two flags. */
+export type TemplateAccess = 'shared' | 'open' | 'private';
+
+export const TEMPLATE_ACCESS_OPTIONS: { value: TemplateAccess; label: string; hint: string }[] = [
+ {
+ value: 'shared',
+ label: 'Shared',
+ hint: 'Everyone on the workspace can use it. You change it.',
+ },
+ { value: 'open', label: 'Open', hint: 'Everyone on the workspace can use it and change it.' },
+ { value: 'private', label: 'Private', hint: 'Only you and admins can see it.' },
+];
+
+export function accessOf(t: {
+ readVisibility: TemplateVisibility;
+ writeVisibility: TemplateVisibility;
+}): TemplateAccess {
+ if (t.readVisibility === 'private') return 'private';
+ return t.writeVisibility === 'public' ? 'open' : 'shared';
+}
+
+export function visibilityOf(access: TemplateAccess): {
+ readVisibility: TemplateVisibility;
+ writeVisibility: TemplateVisibility;
+} {
+ return {
+ readVisibility: access === 'private' ? 'private' : 'public',
+ writeVisibility: access === 'open' ? 'public' : 'private',
+ };
+}
+
+export function accessLine(access: TemplateAccess): string {
+ return access === 'private'
+ ? 'Only you and admins can see it'
+ : access === 'open'
+ ? 'Shared with the workspace, anyone can edit it'
+ : 'Shared with the workspace';
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx
index 9dd589359..6bc628882 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx
@@ -110,12 +110,14 @@ function summaryLine(s: TemplateSummary): string {
}
// The listing endpoint returns no document text, and the summary line
-// needs the document. Each card fetches its own once and keeps it for the
-// session.
+// needs the document. Each card fetches its own once per version of the
+// template and keeps it for the session.
const summaryCache = new Map<string, Promise<TemplateSummary>>();
function fetchSummary(serverId: string, item: TemplateListEntry): Promise<TemplateSummary> {
- const key = `${serverId}:${item.id}`;
+ // The version is part of the key, so an edit made elsewhere refreshes the
+ // card as soon as the listing reports it.
+ const key = `${serverId}:${item.id}:${item.server?.version ?? 0}`;
let pending = summaryCache.get(key);
if (!pending) {
pending = (async () => {
@@ -418,6 +420,33 @@ const TemplatesPanel = observer(function TemplatesPanel() {
const [dragging, setDragging] = useState(0);
const [reloadKey, setReloadKey] = useState(0);
const reload = useCallback(() => setReloadKey((k) => k + 1), []);
+ // The server searches name and description. The full listing stays loaded
+ // for the recents and for marking a built-in as saved; the search results
+ // replace it only for the workspace cards.
+ const [searchHits, setSearchHits] = useState<StoredTemplateSummary[] | null>(null);
+ useEffect(() => {
+ const q = query.trim();
+ if (q.length === 0) {
+ setSearchHits(null);
+ return;
+ }
+ let cancelled = false;
+ const timer = window.setTimeout(() => {
+ rpc.switchServers
+ .listTemplates({ serverId, q })
+ .then((hits) => {
+ if (!cancelled) setSearchHits(hits);
+ })
+ .catch(() => {
+ // The client-side match below still applies to what is loaded.
+ if (!cancelled) setSearchHits(null);
+ });
+ }, 250);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ };
+ }, [serverId, query, reloadKey]);
// An agent template needs a coding agent where its agents will run, and
// this computer is the default run location. Say at the top of the listing
@@ -468,7 +497,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {
server: byName.get(b.name) ?? null,
content: b.yamlText,
}));
- const onWorkspace: TemplateListEntry[] = templates.map((t) => ({
+ const onWorkspace: TemplateListEntry[] = (searchHits ?? templates).map((t) => ({
id: t.id,
kind: kindOf(t.kind),
name: t.name,
@@ -489,7 +518,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {
builtIn: onlyMine ? [] : builtIn.filter(matches),
onWorkspace: onWorkspace.filter((t) => matches(t) && (!onlyMine || mine(t))),
};
- }, [templates, query, kind, onlyMine, meId]);
+ }, [templates, searchHits, query, kind, onlyMine, meId]);
const handleUse = (item: TemplateListEntry) =>
navigate('templateUse', { serverId, templateId: item.id });
@@ -633,7 +662,7 @@ const TemplatesPanel = observer(function TemplatesPanel() {
<Section
title="On this workspace"
- subtitle="Saved here. Everyone on this workspace can see and use them; only the owner can change one."
+ subtitle="Saved here. Each one says who can use it and who can change it."
>
{onWorkspace.length > 0 ? (
<div className={grid}>{onWorkspace.map(card)}</div>
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.ts
index 557cee552..76dca5256 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
@@ -22,6 +22,7 @@ export const VIEW_IDS = [
'templates',
'templateDetail',
'templateUse',
+ 'templateCapture',
] as const;
export type ViewIdName = (typeof VIEW_IDS)[number];
diff --git a/console/packages/shared/src/index.ts b/console/packages/shared/src/index.ts
index 37608e9ed..01cff8701 100644
--- a/console/packages/shared/src/index.ts
+++ b/console/packages/shared/src/index.ts
@@ -20,3 +20,4 @@ export {
export { Emitter } from './emitter';
export { isDeepEqual } from './deep-equal';
export type { IDisposable, IInitializable, ILifecycle, Lease, Unsubscribe } from './lifecycle';
+export { parameterize, type ParamSubstitution } from './parameterize';
diff --git a/console/packages/shared/src/parameterize.test.ts b/console/packages/shared/src/parameterize.test.ts
new file mode 100644
index 000000000..50be37f33
--- /dev/null
+++ b/console/packages/shared/src/parameterize.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from 'vitest';
+import { parameterize, type ParamSubstitution } from './parameterize';
+
+const EXPORTED_YAML = `room:
+ name: local-deploy
+ description: Local deployment room
+ channel_type: channel_public
+ read_visibility: public
+ write_visibility: public
+ agents:
+ - agent-alpha
+ - agent-beta
+`;
+
+describe('parameterize', () => {
+ it('returns the input unchanged when there are no substitutions', () => {
+ expect(parameterize(EXPORTED_YAML, [])).toBe(EXPORTED_YAML);
+ });
+
+ it('replaces the room name and adds a params block', () => {
+ const result = parameterize(EXPORTED_YAML, [{ key: 'name', value: 'local-deploy' }]);
+ expect(result).toContain("name: '{name}'");
+ expect(result).toContain('params:\n');
+ expect(result).toContain(' default: local-deploy');
+ expect(result).toContain(' type: string');
+ expect(result).toMatch(/^params:/m);
+ expect(result).toMatch(/^room:/m);
+ });
+
+ it('replaces agent names in the sequence', () => {
+ const result = parameterize(EXPORTED_YAML, [{ key: 'agent_a', value: 'agent-alpha' }]);
+ expect(result).toContain("- '{agent_a}'");
+ expect(result).not.toContain('- agent-alpha');
+ });
+
+ it('handles multiple substitutions', () => {
+ const subs: ParamSubstitution[] = [
+ { key: 'name', value: 'local-deploy' },
+ { key: 'agent_a', value: 'agent-alpha' },
+ { key: 'agent_b', value: 'agent-beta' },
+ ];
+ const result = parameterize(EXPORTED_YAML, subs);
+ expect(result).toContain("name: '{name}'");
+ expect(result).toContain("- '{agent_a}'");
+ expect(result).toContain("- '{agent_b}'");
+ expect(result).toContain(' name:\n type: string\n default: local-deploy');
+ expect(result).toContain(' agent_a:\n type: string\n default: agent-alpha');
+ expect(result).toContain(' agent_b:\n type: string\n default: agent-beta');
+ });
+
+ it('includes description when provided', () => {
+ const result = parameterize(EXPORTED_YAML, [
+ { key: 'name', value: 'local-deploy', description: 'The room name' },
+ ]);
+ expect(result).toContain(' description: The room name');
+ });
+
+ it('replaces longer values first to avoid partial matches', () => {
+ const yaml = `room:
+ name: agent-alpha-room
+ agents:
+ - agent-alpha
+`;
+ const result = parameterize(yaml, [
+ { key: 'room_name', value: 'agent-alpha-room' },
+ { key: 'agent', value: 'agent-alpha' },
+ ]);
+ // The room name contains 'agent-alpha' as a substring, so the longer value
+ // is replaced first and the room name is not partially mangled.
+ expect(result).toContain("name: '{room_name}'");
+ expect(result).toContain("- '{agent}'");
+ });
+
+ it('quotes values containing single quotes', () => {
+ const yaml = `room:
+ name: it's-a-room
+`;
+ const result = parameterize(yaml, [{ key: 'name', value: "it's-a-room" }]);
+ expect(result).toContain("name: '{name}'");
+ // The default in the params block should have doubled single quotes.
+ expect(result).toContain("default: 'it''s-a-room'");
+ });
+
+ it('replaces occurrences in instruction text', () => {
+ const yaml = `room:
+ name: my-room
+ instructions: Welcome to my-room, the best room.
+`;
+ const result = parameterize(yaml, [{ key: 'name', value: 'my-room' }]);
+ expect(result).toContain("instructions: 'Welcome to {name}, the best room.'");
+ });
+
+ it('throws on invalid param name', () => {
+ expect(() => parameterize(EXPORTED_YAML, [{ key: '123bad', value: 'x' }])).toThrow(
+ 'Invalid param name'
+ );
+ });
+
+ it('throws on empty value', () => {
+ expect(() => parameterize(EXPORTED_YAML, [{ key: 'x', value: '' }])).toThrow('Empty value');
+ });
+
+ it('throws on duplicate keys', () => {
+ expect(() =>
+ parameterize(EXPORTED_YAML, [
+ { key: 'name', value: 'a' },
+ { key: 'name', value: 'b' },
+ ])
+ ).toThrow('Duplicate param key');
+ });
+
+ it('produces YAML that starts with params then room', () => {
+ const result = parameterize(EXPORTED_YAML, [{ key: 'name', value: 'local-deploy' }]);
+ const paramsIdx = result.indexOf('params:');
+ const roomIdx = result.indexOf('room:');
+ expect(paramsIdx).toBeLessThan(roomIdx);
+ expect(paramsIdx).toBe(0);
+ });
+
+ it('round-trips: parameterized YAML is valid for the server parser', () => {
+ // The server parser expects: top-level `params:` and `room:`, with
+ // placeholder values as quoted strings. This test verifies structure only —
+ // actual YAML parsing is the server's job.
+ const result = parameterize(EXPORTED_YAML, [{ key: 'name', value: 'local-deploy' }]);
+ // Has both top-level keys.
+ expect(result).toMatch(/^params:/m);
+ expect(result).toMatch(/^room:/m);
+ // Placeholder is quoted (safe for yaml.safe_load).
+ expect(result).toMatch(/'.*\{name\}.*'/);
+ });
+});
+
+describe('parameterize: block scalars', () => {
+ it('leaves the body of a | block alone, and still quotes a mapping value outside it', () => {
+ const yaml = [
+ 'room:',
+ ' name: alpha-room',
+ ' instructions: |',
+ ' Room rules:',
+ ' - Ask agent-alpha for help when stuck.',
+ ' - Respond with: {"ok": true}',
+ ' topic: agent-alpha',
+ ].join('\n');
+ const out = parameterize(yaml, [{ key: 'agent_a', value: 'agent-alpha' }]);
+ expect(out).toContain(' - Ask {agent_a} for help when stuck.');
+ expect(out).toContain(' - Respond with: {"ok": true}');
+ expect(out).toContain(" topic: '{agent_a}'");
+ });
+
+ it('recognises an indented block header with the chomping sign after the indent', () => {
+ const yaml = [
+ 'room:',
+ ' name: r',
+ ' instructions: |2-',
+ ' - Ask agent-alpha.',
+ ' topic: agent-alpha',
+ ].join('\n');
+ const out = parameterize(yaml, [{ key: 'a', value: 'agent-alpha' }]);
+ expect(out).toContain(' - Ask {a}.');
+ expect(out).toContain(" topic: '{a}'");
+ });
+});
+
+describe('parameterize: structure and keys', () => {
+ it('never touches a structural key, even when a value spells it', () => {
+ const yaml = ['room:', ' name: room', ' description: the room'].join('\n');
+ const out = parameterize(yaml, [{ key: 'n', value: 'room' }]);
+ expect(out).toContain('\nroom:\n');
+ expect(out).toContain(" name: '{n}'");
+ expect(out).toContain(" description: 'the {n}'");
+ });
+
+ it('quotes an alias key that becomes a placeholder', () => {
+ const yaml = [
+ 'room:',
+ ' name: r',
+ ' agents:',
+ ' - helper',
+ ' aliases:',
+ ' helper: buddy',
+ ].join('\n');
+ const out = parameterize(yaml, [{ key: 'a', value: 'helper' }]);
+ expect(out).toContain(" - '{a}'");
+ expect(out).toContain(" '{a}': buddy");
+ });
+
+ it('substitutes inside an already quoted value and keeps its quotes', () => {
+ const yaml = ['room:', " name: 'Ask helper: now'"].join('\n');
+ const out = parameterize(yaml, [{ key: 'a', value: 'helper' }]);
+ expect(out).toContain(" name: 'Ask {a}: now'");
+ });
+
+ it('quotes a default the loader would read as a number, boolean or null', () => {
+ const yaml = ['room:', ' name: r', ' description: 001'].join('\n');
+ const out = parameterize(yaml, [
+ { key: 'code', value: '001' },
+ { key: 'flag', value: 'true' },
+ { key: 'nothing', value: 'null' },
+ ]);
+ expect(out).toContain(" default: '001'");
+ expect(out).toContain(" default: 'true'");
+ expect(out).toContain(" default: 'null'");
+ });
+});
diff --git a/console/packages/shared/src/parameterize.ts b/console/packages/shared/src/parameterize.ts
new file mode 100644
index 000000000..b82022a4f
--- /dev/null
+++ b/console/packages/shared/src/parameterize.ts
@@ -0,0 +1,189 @@
+/**
+ * Turns exported room YAML into a parameterized template: literal values
+ * become `{key}` placeholders and a `params:` block is prepended, in the
+ * grammar the server interpolates on import (see `rooms_yaml.PLACEHOLDER_RE`).
+ */
+
+const PARAM_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+export type ParamSubstitution = {
+ /** The param name, matching `[A-Za-z_][A-Za-z0-9_]*`. */
+ key: string;
+ /** The literal value to replace with `{key}`. */
+ value: string;
+ /** Optional human description for the `params:` entry. */
+ description?: string;
+};
+
+/**
+ * Replace `substitutions` values with `{key}` placeholders and prepend a
+ * `params:` block with each substitution's type and default.
+ *
+ * Only scalar positions are touched: a mapping value, a mapping key (an
+ * alias map is keyed by agent name), a sequence item, and the text of a
+ * block scalar. The structure of the document is never a match, so a room
+ * called `room` does not lose its `room:` key. Longer values are replaced
+ * first so a value that is a substring of another cannot steal its match,
+ * and a key or value that now holds a bare `{` is single-quoted so
+ * `yaml.safe_load` reads it as text rather than a flow mapping.
+ */
+export function parameterize(yamlText: string, substitutions: ParamSubstitution[]): string {
+ if (substitutions.length === 0) return yamlText;
+
+ for (const s of substitutions) {
+ if (!PARAM_NAME_RE.test(s.key)) {
+ throw new Error(`Invalid param name: "${s.key}"`);
+ }
+ if (s.value === '') {
+ throw new Error(`Empty value for param "${s.key}"`);
+ }
+ }
+
+ // Check for duplicate keys.
+ const seen = new Set<string>();
+ for (const s of substitutions) {
+ if (seen.has(s.key)) throw new Error(`Duplicate param key: "${s.key}"`);
+ seen.add(s.key);
+ }
+
+ // Replace longest values first.
+ const sorted = [...substitutions].sort((a, b) => b.value.length - a.value.length);
+ const substitute = (text: string) =>
+ sorted.reduce((out, s) => out.split(s.value).join(`{${s.key}}`), text);
+
+ let result = rewriteScalars(yamlText, substitute);
+
+ // Build and prepend the params block.
+ const paramsBlock = buildParamsBlock(substitutions);
+ if (result.startsWith('room:')) {
+ result = paramsBlock + result;
+ } else {
+ result = result.replace(/^(room:)/m, paramsBlock + '$1');
+ }
+
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Apply `substitute` to every scalar of a YAML document dumped by Python's
+ * `yaml.dump(default_flow_style=False)`, whose lines come in these shapes:
+ *
+ * key: value (mapping entry)
+ * key: | (block scalar header; the body is the lines below,
+ * indented deeper, and is free text)
+ * - value (sequence item)
+ * - key: value (mapping entry inside a sequence item)
+ *
+ * A key or value that comes out holding a bare `{` is single-quoted. Keys
+ * are names of the format, not text, so they are left alone except inside
+ * an `aliases:` map, whose keys are agent names, and there a key is
+ * substituted only as a whole.
+ */
+function rewriteScalars(text: string, substitute: (s: string) => string): string {
+ // The indent of the `key: |` line whose block body is being walked, or
+ // null outside a block.
+ let blockIndent: number | null = null;
+ // The indent of the `aliases:` line whose entries are being walked, or null.
+ let aliasesIndent: number | null = null;
+ return text
+ .split('\n')
+ .map((line) => {
+ const indent = line.match(/^ */)?.[0].length ?? 0;
+ if (blockIndent !== null) {
+ if (line.trim() === '' || indent > blockIndent) return substitute(line);
+ blockIndent = null;
+ }
+ const item = line.match(/^(\s*-\s+)(.*)$/);
+ const prefix = item ? item[1] : '';
+ const rest = item ? item[2] : line;
+ if (aliasesIndent !== null && line.trim() !== '' && indent <= aliasesIndent) {
+ aliasesIndent = null;
+ }
+ const kv = rest.match(/^(\s*)([^\s#'"][^:]*?|'[^']*'|"[^"]*")(:)(\s+(.*)|)$/);
+ if (kv) {
+ const [, lead, key, colon, tail, val] = kv;
+ const inAliases = aliasesIndent !== null && indent > aliasesIndent;
+ const newKey = inAliases ? substituteWhole(key, substitute) : key;
+ if (key === 'aliases' && (val === undefined || val === '')) aliasesIndent = indent;
+ if (val === undefined || val === '')
+ return `${prefix}${lead}${newKey}${colon}${tail ?? ''}`;
+ if (isBlockHeader(val)) {
+ blockIndent = indent;
+ return `${prefix}${lead}${newKey}${colon}${tail}`;
+ }
+ return `${prefix}${lead}${newKey}${colon} ${substituteScalar(val, substitute)}`;
+ }
+ if (item) return `${prefix}${substituteScalar(rest, substitute)}`;
+ return line;
+ })
+ .join('\n');
+}
+
+/** A key is replaced only when it is exactly a value, and quoted if that leaves a `{`. */
+function substituteWhole(key: string, substitute: (s: string) => string): string {
+ const bare = key.replace(/^['"]|['"]$/g, '');
+ const next = substitute(bare);
+ if (next === bare) return key;
+ return next.includes('{') ? singleQuote(next) : next;
+}
+
+/** A scalar is substituted inside its quotes when it has them, and quoted when a `{` appears in a bare one. */
+function substituteScalar(val: string, substitute: (s: string) => string): string {
+ const quoted = val.match(/^(['"])(.*)\1(\s*#.*)?$/);
+ if (quoted) {
+ const [, q, inner, comment] = quoted;
+ const next = substitute(inner);
+ return `${q}${q === "'" ? next.replace(/(?<!')'(?!')/g, "''") : next}${q}${comment ?? ''}`;
+ }
+ const next = substitute(val);
+ return next.includes('{') ? singleQuote(next) : next;
+}
+
+/** `|`, `>`, and their chomping and indentation variants in either order (`|-`, `>+`, `|2`, `|2-`). */
+function isBlockHeader(val: string): boolean {
+ return /^[|>](?:[-+]?\d*|\d*[-+]?)$/.test(val.trim());
+}
+
+/** Single-quote a YAML scalar, escaping embedded single quotes by doubling. */
+function singleQuote(val: string): string {
+ return `'${val.replace(/'/g, "''")}'`;
+}
+
+function buildParamsBlock(subs: ParamSubstitution[]): string {
+ const lines: string[] = ['params:'];
+ for (const s of subs) {
+ lines.push(` ${s.key}:`);
+ lines.push(' type: string');
+ lines.push(` default: ${yamlScalar(s.value)}`);
+ if (s.description) {
+ lines.push(` description: ${yamlScalar(s.description)}`);
+ }
+ }
+ lines.push('');
+ return lines.join('\n');
+}
+
+/**
+ * Emit a YAML scalar, quoting when needed: special characters, and anything
+ * the loader would read as something other than text (`true`, `null`, `001`,
+ * `1.5`), so a default comes back as the string it was.
+ */
+function yamlScalar(val: string): string {
+ if (val === '') return "''";
+ if (/[:{}[\],&*?|>'"%@`#!]/.test(val) || val.includes('\n')) {
+ return singleQuote(val);
+ }
+ if (
+ /^(?:true|false|yes|no|on|off|null|~|[-+]?(?:\d[\d_]*)?(?:\.\d*)?(?:e[-+]?\d+)?|0x[0-9a-f]+|0o[0-7]+|[-+]?\.(?:inf|nan))$/i.test(
+ val
+ )
+ ) {
+ return singleQuote(val);
+ }
+ if (val !== val.trim()) return singleQuote(val);
+ return val;
+}
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index 25d536cef..d979164c7 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -975,6 +975,15 @@ class Template(TenantScoped, Base):
name: Mapped[str] = mapped_column(Text, nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
kind: Mapped[str] = mapped_column(Text, nullable=False)
+ # Who may see and who may change it, as for references and packages
+ # (see ``authz.can``). The defaults are a template shared with the
+ # workspace and changed by its owner or an admin.
+ read_visibility: Mapped[str] = mapped_column(
+ Text, nullable=False, server_default="public"
+ )
+ write_visibility: Mapped[str] = mapped_column(
+ Text, nullable=False, server_default="private"
+ )
content: Mapped[str] = mapped_column(Text, nullable=False)
version: Mapped[int] = mapped_column(Integer, nullable=False, server_default="1")
created_at: Mapped[str] = mapped_column(
diff --git a/core/switch_core/db/stores/template_store.py b/core/switch_core/db/stores/template_store.py
index b8d898db7..d6c43bfe6 100644
--- a/core/switch_core/db/stores/template_store.py
+++ b/core/switch_core/db/stores/template_store.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from dataclasses import dataclass
from sqlalchemy import ColumnElement, func, or_, select
@@ -42,6 +43,8 @@ class TemplateListing:
name: str
description: str
kind: str
+ read_visibility: str
+ write_visibility: str
version: int
size_bytes: int
created_at: object
@@ -78,19 +81,28 @@ class TemplateStore:
self,
session: AsyncSession,
*,
+ viewer_id: str,
+ is_admin: bool,
query: str | None = None,
kind: str | None = None,
owner_id: str | None = None,
) -> list[TemplateListing]:
- """The catalogue, newest first, without the documents.
-
- Every template in the tenant, whoever uploaded it: ownership governs
- who may change or remove one, not who may see it. The tenant boundary
- is the database's to enforce, not this query's — row-level security
- filters it, so a filter here would be a second answer to a question
- already answered, and the wrong place to notice if the two disagreed.
+ """The catalogue as ``viewer_id`` may see it, newest first, without
+ the documents: every shared template, plus the viewer's own private
+ ones, and everything for an admin.
+
+ The tenant boundary is the database's to enforce, not this query's:
+ row-level security filters it, so a filter here would be a second
+ answer to a question already answered, and the wrong place to notice
+ if the two disagreed.
"""
conditions: list[ColumnElement[bool]] = []
+ if not is_admin:
+ conditions.append(
+ or_(
+ Template.read_visibility == "public", Template.owner_id == viewer_id
+ )
+ )
if query:
needle = _like_needle(query)
conditions.append(
@@ -111,6 +123,8 @@ class TemplateStore:
Template.name,
Template.description,
Template.kind,
+ Template.read_visibility,
+ Template.write_visibility,
Template.version,
# Bytes, not characters — `length()` would undercount anything
# outside ASCII and disagree with the upload limit.
@@ -136,9 +150,17 @@ class TemplateStore:
description: str | None = None,
kind: str | None = None,
content: str | None = None,
+ read_visibility: str | None = None,
+ write_visibility: str | None = None,
+ guard: Callable[[Template], None] | None = None,
) -> Template:
"""Change a stored template. Replacing the content bumps ``version``.
+ ``guard`` is called on the row once it is locked and may raise to
+ refuse the change. Authorization belongs here rather than on a row
+ read earlier: an access change committed before the lock is taken
+ is seen here and not by an earlier read.
+
Metadata-only edits leave the revision alone: the document someone
fetched is still the document they would fetch now.
@@ -159,6 +181,8 @@ class TemplateStore:
)
if template is None:
raise ValueError(f"Template not found: {template_id}")
+ if guard is not None:
+ guard(template)
if name is not None and name != template.name:
# Asked before anything is mutated: a flush that fails the unique
@@ -183,6 +207,10 @@ class TemplateStore:
template.description = description
if kind is not None:
template.kind = kind
+ if read_visibility is not None:
+ template.read_visibility = read_visibility
+ if write_visibility is not None:
+ template.write_visibility = write_visibility
# Read off the object now: after a failed flush, touching it again can
# lazy-load against a session that is no longer in a state to answer.
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index bc67cfe2e..d8178781c 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1092,6 +1092,13 @@ class TemplateSummary(BaseModel):
name: str
description: str
kind: str
+ read_visibility: str
+ write_visibility: str
+ # What the caller may do with it, so a client shows Edit and Remove only
+ # where the server would say yes. Admin here means the tenant's, which a
+ # client cannot tell from the user's global role.
+ can_edit: bool
+ can_manage: bool
version: int
size_bytes: int
created_at: str
@@ -1120,6 +1127,9 @@ class TemplateCreateRequest(BaseModel):
name: str = Field(min_length=1, max_length=TEMPLATE_NAME_MAX)
description: str = Field(default="", max_length=TEMPLATE_DESCRIPTION_MAX)
kind: str = Field(default="room", min_length=1, max_length=TEMPLATE_KIND_MAX)
+ # Shared with the workspace and changed by the owner or an admin, unless said otherwise.
+ read_visibility: str = "public"
+ write_visibility: str = "private"
content: str = Field(min_length=1)
@@ -1130,6 +1140,8 @@ class TemplateUpdateRequest(BaseModel):
description: str | None = Field(default=None, max_length=TEMPLATE_DESCRIPTION_MAX)
kind: str | None = Field(default=None, min_length=1, max_length=TEMPLATE_KIND_MAX)
content: str | None = Field(default=None, min_length=1)
+ read_visibility: str | None = None
+ write_visibility: str | None = None
class TemplateDeleteResponse(BaseModel):
diff --git a/core/switch_core/gateway/templates.py b/core/switch_core/gateway/templates.py
index b1505708f..967b62aff 100644
--- a/core/switch_core/gateway/templates.py
+++ b/core/switch_core/gateway/templates.py
@@ -21,7 +21,15 @@ from urllib.parse import quote
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.authz import Principal, require_manage
+from switch_core.authz import (
+ Action,
+ Principal,
+ can,
+ can_manage,
+ require,
+ require_manage,
+ validate_visibility_pair,
+)
from switch_core.config import SwitchConfig
from switch_core.db.models import Template, User
from switch_core.db.stores.template_store import (
@@ -94,7 +102,9 @@ def _content_disposition(name: str) -> str:
return f"attachment; filename=\"{stem}.yaml\"; filename*=UTF-8''{encoded}"
-def _summary(row: TemplateListing, owner_name: str | None) -> TemplateSummary:
+def _summary(
+ row: TemplateListing, owner_name: str | None, principal: Principal
+) -> TemplateSummary:
return TemplateSummary(
id=row.id,
owner_id=row.owner_id,
@@ -102,6 +112,10 @@ def _summary(row: TemplateListing, owner_name: str | None) -> TemplateSummary:
name=row.name,
description=row.description,
kind=row.kind,
+ read_visibility=row.read_visibility,
+ write_visibility=row.write_visibility,
+ can_edit=can(principal, "write", row),
+ can_manage=can_manage(principal, row.owner_id),
version=row.version,
size_bytes=row.size_bytes,
created_at=str(row.created_at),
@@ -109,7 +123,9 @@ def _summary(row: TemplateListing, owner_name: str | None) -> TemplateSummary:
)
-def _detail(template: Template, owner_name: str | None) -> TemplateDetail:
+def _detail(
+ template: Template, owner_name: str | None, principal: Principal
+) -> TemplateDetail:
return TemplateDetail(
id=template.id,
owner_id=template.owner_id,
@@ -117,6 +133,10 @@ def _detail(template: Template, owner_name: str | None) -> TemplateDetail:
name=template.name,
description=template.description,
kind=template.kind,
+ read_visibility=template.read_visibility,
+ write_visibility=template.write_visibility,
+ can_edit=can(principal, "write", template),
+ can_manage=can_manage(principal, template.owner_id),
version=template.version,
size_bytes=_size_bytes(template.content),
created_at=str(template.created_at),
@@ -174,43 +194,69 @@ def _require_within_size_limit(content: str, config: SwitchConfig) -> None:
)
-async def _load_for_management(
+async def _load_for(
+ action: Action,
session: AsyncSession,
store: TemplateStore,
template_id: str,
user: User,
is_admin: bool,
) -> Template:
- """Fetch a template the caller is allowed to change, or fail saying why."""
+ """Fetch a template, refusing unless the caller may ``action`` it.
+
+ A private template the caller may not read is reported as not found,
+ so the listing and the detail route agree on what exists for them.
+ """
template = await store.get(session, template_id)
if template is None:
raise HTTPException(
status_code=404, detail=f"Template not found: {template_id}"
)
+ principal = Principal(user.id, is_admin)
try:
- require_manage(
- Principal(user.id, is_admin),
- template.owner_id,
- )
+ require(principal, "read", template)
except PermissionError as e:
- raise HTTPException(status_code=403, detail=str(e)) from e
+ raise HTTPException(
+ status_code=404, detail=f"Template not found: {template_id}"
+ ) from e
+ if action != "read":
+ try:
+ require(principal, action, template)
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
return template
+def _require_visibility(read_visibility: str, write_visibility: str) -> None:
+ try:
+ validate_visibility_pair(read_visibility, write_visibility)
+ except ValueError as e:
+ raise HTTPException(status_code=422, detail=str(e)) from e
+
+
@router.get("/templates")
async def list_templates(
session: Annotated[AsyncSession, Depends(get_session)],
template_store: Annotated[TemplateStore, Depends(get_template_store)],
user_store: Annotated[UserStore, Depends(get_user_store)],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
q: Annotated[str | None, Query()] = None,
kind: Annotated[str | None, Query()] = None,
owner_id: Annotated[str | None, Query()] = None,
) -> list[TemplateSummary]:
"""Browse the catalogue. `q` matches name or description, case-insensitively."""
- rows = await template_store.list_all(session, query=q, kind=kind, owner_id=owner_id)
+ rows = await template_store.list_all(
+ session,
+ viewer_id=user.id,
+ is_admin=is_admin,
+ query=q,
+ kind=kind,
+ owner_id=owner_id,
+ )
names = await _owner_names(session, user_store, {r.owner_id for r in rows})
- return [_summary(r, names.get(r.owner_id)) for r in rows]
+ principal = Principal(user.id, is_admin)
+ return [_summary(r, names.get(r.owner_id), principal) for r in rows]
@router.post("/templates", status_code=201)
@@ -221,9 +267,11 @@ async def create_template(
user_store: Annotated[UserStore, Depends(get_user_store)],
config: Annotated[SwitchConfig, Depends(get_config)],
user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> TemplateDetail:
_require_within_size_limit(req.content, config)
_require_storable(req.content)
+ _require_visibility(req.read_visibility, req.write_visibility)
try:
template = await template_store.create(
session,
@@ -233,6 +281,8 @@ async def create_template(
description=req.description,
kind=req.kind,
content=req.content,
+ read_visibility=req.read_visibility,
+ write_visibility=req.write_visibility,
),
)
except TemplateNameTaken as e:
@@ -244,7 +294,11 @@ async def create_template(
emit_safely(
current_telemetry(), "template_created", {"template_kind": _kind(req.kind)}
)
- return _detail(template, await _owner_name(session, user_store, user.id))
+ return _detail(
+ template,
+ await _owner_name(session, user_store, user.id),
+ Principal(user.id, is_admin),
+ )
@router.post("/templates/validate")
@@ -292,14 +346,17 @@ async def get_template(
session: Annotated[AsyncSession, Depends(get_session)],
template_store: Annotated[TemplateStore, Depends(get_template_store)],
user_store: Annotated[UserStore, Depends(get_user_store)],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> TemplateDetail:
- template = await template_store.get(session, template_id)
- if template is None:
- raise HTTPException(
- status_code=404, detail=f"Template not found: {template_id}"
- )
- return _detail(template, await _owner_name(session, user_store, template.owner_id))
+ template = await _load_for(
+ "read", session, template_store, template_id, user, is_admin
+ )
+ return _detail(
+ template,
+ await _owner_name(session, user_store, template.owner_id),
+ Principal(user.id, is_admin),
+ )
@router.get("/templates/{template_id}/content", response_model=None)
@@ -307,14 +364,13 @@ async def get_template_content(
template_id: str,
session: Annotated[AsyncSession, Depends(get_session)],
template_store: Annotated[TemplateStore, Depends(get_template_store)],
- _user: Annotated[User, Depends(get_current_user)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> Response:
"""The stored document itself, byte for byte, with no envelope around it."""
- template = await template_store.get(session, template_id)
- if template is None:
- raise HTTPException(
- status_code=404, detail=f"Template not found: {template_id}"
- )
+ template = await _load_for(
+ "read", session, template_store, template_id, user, is_admin
+ )
return Response(
content=template.content.encode("utf-8"),
media_type="application/x-yaml",
@@ -338,7 +394,35 @@ async def patch_template(
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> TemplateDetail:
- await _load_for_management(session, template_store, template_id, user, is_admin)
+ current = await _load_for(
+ "write", session, template_store, template_id, user, is_admin
+ )
+ principal = Principal(user.id, is_admin)
+ changes_access = req.read_visibility is not None or req.write_visibility is not None
+ if changes_access:
+ # Who may see or change a template is decided by its owner or an
+ # admin, not by an editor: an open template must not be closed, or
+ # opened wider, by someone who may only edit its document.
+ try:
+ require_manage(principal, current.owner_id)
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
+ _require_visibility(
+ current.read_visibility
+ if req.read_visibility is None
+ else req.read_visibility,
+ current.write_visibility
+ if req.write_visibility is None
+ else req.write_visibility,
+ )
+
+ def still_allowed(locked: Template) -> None:
+ # Checked again on the locked row: the owner may have closed the
+ # template since the check above.
+ require(principal, "write", locked)
+ if changes_access:
+ require_manage(principal, locked.owner_id)
+
if req.content is not None:
_require_within_size_limit(req.content, config)
_require_storable(req.content)
@@ -350,7 +434,12 @@ async def patch_template(
description=req.description,
kind=req.kind,
content=req.content,
+ read_visibility=req.read_visibility,
+ write_visibility=req.write_visibility,
+ guard=still_allowed,
)
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
except TemplateNameTaken as e:
raise HTTPException(status_code=409, detail=str(e)) from e
except ValueError as e:
@@ -358,7 +447,11 @@ async def patch_template(
# delete that landed in between — gone, not in conflict.
raise HTTPException(status_code=404, detail=str(e)) from e
await session.commit()
- return _detail(template, await _owner_name(session, user_store, template.owner_id))
+ return _detail(
+ template,
+ await _owner_name(session, user_store, template.owner_id),
+ Principal(user.id, is_admin),
+ )
@router.delete("/templates/{template_id}")
@@ -369,8 +462,8 @@ async def delete_template(
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
) -> TemplateDeleteResponse:
- template = await _load_for_management(
- session, template_store, template_id, user, is_admin
+ template = await _load_for(
+ "delete", session, template_store, template_id, user, is_admin
)
kind, age = _kind(template.kind), _age_days(template.created_at)
try:
diff --git a/core/switch_core/migrations/versions/c4d8e2a1f6b3_templates_visibility.py b/core/switch_core/migrations/versions/c4d8e2a1f6b3_templates_visibility.py
new file mode 100644
index 000000000..62dcdd64d
--- /dev/null
+++ b/core/switch_core/migrations/versions/c4d8e2a1f6b3_templates_visibility.py
@@ -0,0 +1,39 @@
+"""a template can be private to its owner, or open for anyone to edit
+
+Revision ID: c4d8e2a1f6b3
+Revises: b8f2d0c41e57
+Create Date: 2026-09-18 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "c4d8e2a1f6b3"
+down_revision: str | None = "b8f2d0c41e57"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ # The defaults give an existing template the access it had: seen by the
+ # whole workspace, changed by its owner or an admin.
+ op.add_column(
+ "templates",
+ sa.Column(
+ "read_visibility", sa.Text(), nullable=False, server_default="public"
+ ),
+ )
+ op.add_column(
+ "templates",
+ sa.Column(
+ "write_visibility", sa.Text(), nullable=False, server_default="private"
+ ),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("templates", "write_visibility")
+ op.drop_column("templates", "read_visibility")
diff --git a/core/tests/switch_core/db/stores/test_template_store.py b/core/tests/switch_core/db/stores/test_template_store.py
index 44ec391ca..72f50f02f 100644
--- a/core/tests/switch_core/db/stores/test_template_store.py
+++ b/core/tests/switch_core/db/stores/test_template_store.py
@@ -129,7 +129,7 @@ class TestTemplateStoreListing:
session, owner_id=owner.id, name="coffee", content="☕" * 10
)
- (row,) = await _STORE.list_all(session)
+ (row,) = await _STORE.list_all(session, viewer_id="", is_admin=True)
assert row.size_bytes == 30
assert not hasattr(row, "content")
@@ -143,7 +143,10 @@ class TestTemplateStoreListing:
await _make_template(session, owner_id=alice.id, name="alice-room")
await _make_template(session, owner_id=bob.id, name="bob-room")
- listed = {t.name for t in await _STORE.list_all(session)}
+ listed = {
+ t.name
+ for t in await _STORE.list_all(session, viewer_id="", is_admin=True)
+ }
assert listed == {"alice-room", "bob-room"}
async def test_search_matches_name_and_description(
@@ -164,7 +167,12 @@ class TestTemplateStoreListing:
session, owner_id=owner.id, name="other", description="nothing here"
)
- hits = {t.name for t in await _STORE.list_all(session, query="deploy")}
+ hits = {
+ t.name
+ for t in await _STORE.list_all(
+ session, viewer_id="", is_admin=True, query="deploy"
+ )
+ }
assert hits == {"deploy-room", "unrelated"}
async def test_search_treats_wildcards_as_literal_text(
@@ -176,7 +184,12 @@ class TestTemplateStoreListing:
await _make_template(session, owner_id=owner.id, name="100%-coverage")
await _make_template(session, owner_id=owner.id, name="plain")
- hits = {t.name for t in await _STORE.list_all(session, query="%")}
+ hits = {
+ t.name
+ for t in await _STORE.list_all(
+ session, viewer_id="", is_admin=True, query="%"
+ )
+ }
assert hits == {"100%-coverage"}
async def test_filters_by_kind_and_owner(
@@ -191,11 +204,19 @@ class TestTemplateStoreListing:
)
await _make_template(session, owner_id=bob.id, name="b-room", kind="room")
- by_kind = {t.name for t in await _STORE.list_all(session, kind="room")}
+ by_kind = {
+ t.name
+ for t in await _STORE.list_all(
+ session, viewer_id="", is_admin=True, kind="room"
+ )
+ }
assert by_kind == {"a-room", "b-room"}
by_owner = {
- t.name for t in await _STORE.list_all(session, owner_id=alice.id)
+ t.name
+ for t in await _STORE.list_all(
+ session, viewer_id="", is_admin=True, owner_id=alice.id
+ )
}
assert by_owner == {"a-room", "a-group"}
@@ -224,7 +245,7 @@ class TestTemplateStoreNaming:
await _make_template(session, owner_id=owner.id, name="deploy-room")
await _make_template(session, owner_id=owner.id, name="something-else")
- assert len(await _STORE.list_all(session)) == 2
+ assert len(await _STORE.list_all(session, viewer_id="", is_admin=True)) == 2
async def test_two_owners_may_share_a_name(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -235,7 +256,7 @@ class TestTemplateStoreNaming:
await _make_template(session, owner_id=alice.id, name="deploy-room")
await _make_template(session, owner_id=bob.id, name="deploy-room")
- assert len(await _STORE.list_all(session)) == 2
+ assert len(await _STORE.list_all(session, viewer_id="", is_admin=True)) == 2
class TestTemplateStoreUpdate:
@@ -415,7 +436,7 @@ class TestTemplateStoreDelete:
await _STORE.delete(session, created.id)
assert await _STORE.get(session, created.id) is None
- assert await _STORE.list_all(session) == []
+ assert await _STORE.list_all(session, viewer_id="", is_admin=True) == []
async def test_delete_of_a_missing_template_raises(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -423,3 +444,31 @@ class TestTemplateStoreDelete:
async with session_factory() as session:
with pytest.raises(ValueError, match="Template not found"):
await _STORE.delete(session, "nope")
+
+
+class TestGuard:
+ async def test_a_guard_that_refuses_leaves_the_row_as_it_was(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """A guard that raises leaves the content and the version as they were."""
+ async with session_factory() as session:
+ alice = await _make_user(session, "alice")
+ created = await _make_template(
+ session, owner_id=alice.id, name="t", content="a"
+ )
+ await session.commit()
+ template_id = created.id
+
+ def refuse(_row: Template) -> None:
+ raise PermissionError("closed since")
+
+ with pytest.raises(PermissionError):
+ await _STORE.update_fields(
+ session, template_id, content="b", guard=refuse
+ )
+ await session.rollback()
+
+ async with session_factory() as session:
+ reloaded = await _STORE.get(session, template_id)
+ assert reloaded is not None
+ assert (reloaded.content, reloaded.version) == ("a", 1)
diff --git a/core/tests/switch_core/gateway/test_template_routes.py b/core/tests/switch_core/gateway/test_template_routes.py
index 4b42d6330..cdad2c8b6 100644
--- a/core/tests/switch_core/gateway/test_template_routes.py
+++ b/core/tests/switch_core/gateway/test_template_routes.py
@@ -86,6 +86,7 @@ async def _create(
_USER_STORE,
config or _config(),
user, # type: ignore[arg-type]
+ await _is_admin(session, user), # type: ignore[arg-type]
)
@@ -107,6 +108,7 @@ class TestUploadAndFetch:
_TEMPLATE_STORE,
_USER_STORE,
owner,
+ await _is_admin(session, owner),
)
assert fetched.content == _AWKWARD_DOCUMENT
@@ -115,6 +117,7 @@ class TestUploadAndFetch:
session,
_TEMPLATE_STORE,
owner,
+ await _is_admin(session, owner),
)
assert raw.body.decode("utf-8") == _AWKWARD_DOCUMENT
assert raw.media_type == "application/x-yaml"
@@ -160,7 +163,14 @@ class TestUploadAndFetch:
await session.commit()
with pytest.raises(HTTPException) as exc:
- await get_template("nope", session, _TEMPLATE_STORE, _USER_STORE, owner)
+ await get_template(
+ "nope",
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ owner,
+ await _is_admin(session, owner),
+ )
assert exc.value.status_code == 404
@@ -198,7 +208,12 @@ class TestSizeLimit:
content="room: " + "x" * 101,
config=_config(template_max_bytes=100),
)
- assert await _TEMPLATE_STORE.list_all(session) == []
+ assert (
+ await _TEMPLATE_STORE.list_all(
+ session, viewer_id=owner.id, is_admin=False
+ )
+ == []
+ )
async def test_the_limit_counts_bytes_so_multibyte_text_cannot_slip_past(
self, session_factory: async_sessionmaker[AsyncSession]
@@ -233,7 +248,11 @@ class TestCatalogue:
# Listed identically whoever is asking.
for caller in (alice, bob):
listed = await list_templates(
- session, _TEMPLATE_STORE, _USER_STORE, caller
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ caller,
+ await _is_admin(session, caller),
)
assert {t.name for t in listed} == {"alice-room", "bob-room"}
assert {t.owner_name for t in listed} == {"alice", "bob"}
@@ -246,7 +265,13 @@ class TestCatalogue:
await session.commit()
await _create(session, owner, name="t", content=_AWKWARD_DOCUMENT)
- listed = await list_templates(session, _TEMPLATE_STORE, _USER_STORE, owner)
+ listed = await list_templates(
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ owner,
+ await _is_admin(session, owner),
+ )
assert not hasattr(listed[0], "content")
assert listed[0].size_bytes == len(_AWKWARD_DOCUMENT.encode("utf-8"))
@@ -261,7 +286,12 @@ class TestCatalogue:
await _create(session, owner, name="unrelated", description="x")
hits = await list_templates(
- session, _TEMPLATE_STORE, _USER_STORE, owner, q="deploy"
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ owner,
+ await _is_admin(session, owner),
+ q="deploy",
)
assert {t.name for t in hits} == {"deploy-room", "other"}
@@ -275,7 +305,12 @@ class TestCatalogue:
await _create(session, owner, name="b", kind="group")
hits = await list_templates(
- session, _TEMPLATE_STORE, _USER_STORE, owner, kind="group"
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ owner,
+ await _is_admin(session, owner),
+ kind="group",
)
assert {t.name for t in hits} == {"b"}
@@ -341,6 +376,7 @@ class TestOwnership:
_TEMPLATE_STORE,
_USER_STORE,
bob,
+ await _is_admin(session, bob),
)
assert fetched.content == _AWKWARD_DOCUMENT
@@ -508,3 +544,163 @@ class TestUpdate:
await _is_admin(session, alice),
)
assert exc.value.status_code == 409
+
+
+class TestVisibility:
+ async def test_a_private_template_is_listed_and_fetched_only_by_its_owner(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await add_user(session, name="alice")
+ bob = await add_user(session, name="bob")
+ await session.commit()
+ created = await create_template(
+ TemplateCreateRequest(
+ name="mine", content="room:\n name: n\n", read_visibility="private"
+ ),
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ _config(),
+ alice,
+ await _is_admin(session, alice),
+ )
+ for who, expected in ((alice, {"mine"}), (bob, set())):
+ listed = await list_templates(
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ who,
+ await _is_admin(session, who),
+ )
+ assert {t.name for t in listed} == expected
+ with pytest.raises(HTTPException) as exc:
+ await get_template(
+ created.id, # type: ignore[attr-defined]
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ bob,
+ await _is_admin(session, bob),
+ )
+ assert exc.value.status_code == 404
+
+ async def test_anyone_may_edit_an_open_template_but_not_close_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await add_user(session, name="alice")
+ bob = await add_user(session, name="bob")
+ await session.commit()
+ created = await create_template(
+ TemplateCreateRequest(
+ name="open", content="room:\n name: n\n", write_visibility="public"
+ ),
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ _config(),
+ alice,
+ await _is_admin(session, alice),
+ )
+ edited = await patch_template(
+ created.id, # type: ignore[attr-defined]
+ TemplateUpdateRequest(content="room:\n name: changed\n"),
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ _config(),
+ bob,
+ await _is_admin(session, bob),
+ )
+ assert edited.version == 2
+ with pytest.raises(HTTPException) as exc:
+ await patch_template(
+ created.id, # type: ignore[attr-defined]
+ TemplateUpdateRequest(write_visibility="private"),
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ _config(),
+ bob,
+ await _is_admin(session, bob),
+ )
+ assert exc.value.status_code == 403
+
+ async def test_a_writable_template_must_be_readable(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await add_user(session, name="alice")
+ await session.commit()
+ with pytest.raises(HTTPException) as exc:
+ await create_template(
+ TemplateCreateRequest(
+ name="odd",
+ content="room:\n name: n\n",
+ read_visibility="private",
+ write_visibility="public",
+ ),
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ _config(),
+ alice,
+ await _is_admin(session, alice),
+ )
+ assert exc.value.status_code == 422
+
+ async def test_an_empty_visibility_is_refused_not_ignored(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await add_user(session, name="alice")
+ await session.commit()
+ created = await _create(session, alice, name="t")
+ with pytest.raises(HTTPException) as exc:
+ await patch_template(
+ created.id, # type: ignore[attr-defined]
+ TemplateUpdateRequest(read_visibility=""),
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ _config(),
+ alice,
+ await _is_admin(session, alice),
+ )
+ assert exc.value.status_code == 422
+
+ async def test_each_row_says_what_the_caller_may_do(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ async with session_factory() as session:
+ alice = await add_user(session, name="alice")
+ bob = await add_user(session, name="bob")
+ await session.commit()
+ await create_template(
+ TemplateCreateRequest(
+ name="open", content="room:\n name: n\n", write_visibility="public"
+ ),
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ _config(),
+ alice,
+ await _is_admin(session, alice),
+ )
+ (row,) = await list_templates(
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ bob,
+ await _is_admin(session, bob),
+ )
+ assert (row.can_edit, row.can_manage) == (True, False)
+ (own,) = await list_templates(
+ session,
+ _TEMPLATE_STORE,
+ _USER_STORE,
+ alice,
+ await _is_admin(session, alice),
+ )
+ assert (own.can_edit, own.can_manage) == (True, True)
diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.py
index 62d71a67b..7816272a3 100644
--- a/core/tests/switch_core/test_rooms_yaml.py
+++ b/core/tests/switch_core/test_rooms_yaml.py
@@ -2236,3 +2236,49 @@ async def test_provision_reports_a_kickoff_that_raises(env, monkeypatch):
assert result.failed_attachments == [
{"kind": "kickoff", "id": "kickoff", "error": "admin client is gone"}
]
+
+
+# ── capture export round trip ─────────────────────────────────────────────
+
+
+async def test_export_parameterize_round_trip(env):
+ """Export → parameterize (name) → re-parse with new input → same structure.
+
+ Mirrors the client-side parameterize transform: replace a literal value with
+ a ``{key}`` placeholder, add a ``params:`` block, and import the result with
+ an input supplying a different value.
+ """
+ import re
+
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "Capture me"
+ description: "room to capture"
+ agents: ["claude-code.alice"]
+ """
+ )
+ result = await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+
+ yaml_text = await _svc(env).export(result.room_id)
+
+ parameterized = yaml_text.replace("Capture me", "{room_name}")
+ parameterized = re.sub(
+ r"^(\s*name:\s+)(\{room_name\})$",
+ r"\1'{room_name}'",
+ parameterized,
+ flags=re.MULTILINE,
+ )
+ parameterized = (
+ "params:\n room_name:\n type: string\n default: Capture me\n"
+ + parameterized
+ )
+
+ reparsed, _ = _svc(env).parse(parameterized, inputs={"room_name": "Cloned room"})
+ assert reparsed.name == "Cloned room"
+ assert reparsed.description == "room to capture"
+ assert sorted(reparsed.agents) == ["claude-code.alice"]
+
+ reparsed_default, _ = _svc(env).parse(parameterized)
+ assert reparsed_default.name == "Capture me"
diff --git a/gateway/src/components/AccessControls.tsx b/gateway/src/components/AccessControls.tsx
index 2e03d44bc..2e7d4114c 100644
--- a/gateway/src/components/AccessControls.tsx
+++ b/gateway/src/components/AccessControls.tsx
@@ -27,6 +27,9 @@ interface AccessSelectProps {
onChange: (level: AccessLevel) => void;
disabled?: boolean;
label?: string;
+ /** Helper text per level, where the shared wording does not fit the
+ * resource (a template is used, not attached). */
+ helpers?: Partial<Record<AccessLevel, string>>;
sx?: SxProps<Theme>;
}
@@ -37,6 +40,7 @@ export function AccessSelect({
onChange,
disabled,
label = "Access",
+ helpers,
sx,
}: AccessSelectProps) {
return (
@@ -46,7 +50,7 @@ export function AccessSelect({
value={value}
onChange={(e) => onChange(e.target.value as AccessLevel)}
disabled={disabled}
- helperText={ACCESS_META[value].helper}
+ helperText={helpers?.[value] ?? ACCESS_META[value].helper}
sx={sx}
>
{ACCESS_LEVELS.map((lvl) => (
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 065666d9d..423aec0e3 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1570,6 +1570,11 @@ export interface TemplateSummary {
name: string;
description: string;
kind: string;
+ read_visibility: "public" | "private";
+ write_visibility: "public" | "private";
+ /** What the signed-in user may do with it, as the server judges it. */
+ can_edit: boolean;
+ can_manage: boolean;
version: number;
size_bytes: number;
created_at: string;
@@ -1585,6 +1590,8 @@ export interface TemplateCreateInput {
description: string;
kind: string;
content: string;
+ read_visibility?: "public" | "private";
+ write_visibility?: "public" | "private";
}
export interface TemplateUpdateInput {
@@ -1592,18 +1599,38 @@ export interface TemplateUpdateInput {
description?: string;
kind?: string;
content?: string;
+ read_visibility?: "public" | "private";
+ write_visibility?: "public" | "private";
}
export interface TemplateDeleteResult {
deleted_id: string;
}
-export async function fetchTemplates(): Promise<TemplateSummary[] | null> {
- return fetchJson<TemplateSummary[]>("/templates");
+export interface TemplateFilter {
+ /** Matched by the server against name and description. */
+ q?: string;
+ kind?: string;
+ owner_id?: string;
+}
+
+/** The templates the signed-in user may see, narrowed on the server. */
+export async function fetchTemplates(
+ filter: TemplateFilter = {},
+): Promise<TemplateSummary[] | null> {
+ const params = new URLSearchParams();
+ const q = filter.q?.trim();
+ if (q) params.set("q", q);
+ if (filter.kind) params.set("kind", filter.kind);
+ if (filter.owner_id) params.set("owner_id", filter.owner_id);
+ const qs = params.toString();
+ return fetchJson<TemplateSummary[]>(`/templates${qs ? `?${qs}` : ""}`);
}
-export async function fetchTemplate(id: string): Promise<TemplateDetail | null> {
- return fetchJson<TemplateDetail>(`/templates/${id}`);
+/** One template, or an error carrying the server's reason (403, 404, or the
+ * network), which the page shows as it is. */
+export async function fetchTemplate(id: string): Promise<TemplateDetail> {
+ return jsonRequest<TemplateDetail>(`/templates/${id}`, "GET");
}
export async function createTemplate(
@@ -1632,7 +1659,11 @@ export async function fetchTemplateContent(id: string): Promise<string> {
const body = await res.json().catch(() => null);
throw new Error(body?.detail ?? `${res.status} ${res.statusText}`);
}
- return res.text();
+ // Decoded without BOM stripping: `text()` drops a leading byte order mark,
+ // and the download promises the stored bytes.
+ return new TextDecoder("utf-8", { ignoreBOM: true }).decode(
+ await res.arrayBuffer(),
+ );
}
export interface TemplateFinding {
diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.ts
index 2f24101a8..7f44e31ac 100644
--- a/gateway/src/data/hooks.ts
+++ b/gateway/src/data/hooks.ts
@@ -59,6 +59,7 @@ import {
fetchRoomReferences,
fetchRooms,
fetchTemplates,
+ type TemplateFilter,
fetchUsers,
} from "./api";
@@ -337,6 +338,13 @@ export function usePackageDocuments(
return useQuery(fetcher);
}
-export function useTemplates(): UseQueryResult<TemplateSummary[]> {
- return useQuery(fetchTemplates);
+export function useTemplates(
+ filter: TemplateFilter = {},
+): UseQueryResult<TemplateSummary[]> {
+ const { q, kind, owner_id } = filter;
+ const fetcher = useCallback(
+ () => fetchTemplates({ q, kind, owner_id }),
+ [q, kind, owner_id],
+ );
+ return useQuery(fetcher);
}
diff --git a/gateway/src/pages/resources/CreateTemplateDialog.tsx b/gateway/src/pages/resources/CreateTemplateDialog.tsx
index 0929edb27..a5ab9d94c 100644
--- a/gateway/src/pages/resources/CreateTemplateDialog.tsx
+++ b/gateway/src/pages/resources/CreateTemplateDialog.tsx
@@ -11,8 +11,11 @@ import {
TextField,
} from "@mui/material";
import { useRef, useState } from "react";
+import { AccessSelect } from "../../components/AccessControls";
import { createTemplate } from "../../data/api";
+import { type AccessLevel, fromAccessLevel } from "../../data/visibility";
import TemplateFindings from "./TemplateFindings";
+import { TEMPLATE_ACCESS_HELPERS } from "./templateAccess";
import { MAX_DOCUMENT_BYTES, formatBytes } from "./templateFormat";
import { useTemplateValidation } from "./useTemplateValidation";
@@ -30,6 +33,9 @@ export default function CreateTemplateDialog({
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [kind, setKind] = useState("room");
+ // Read-only, the registry's own default: the workspace can use it, the
+ // owner or an admin changes it.
+ const [access, setAccess] = useState<AccessLevel>("read_only");
const [content, setContent] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -42,6 +48,7 @@ export default function CreateTemplateDialog({
setName("");
setDescription("");
setKind("room");
+ setAccess("read_only");
setContent("");
setError(null);
};
@@ -83,6 +90,7 @@ export default function CreateTemplateDialog({
description,
kind: kind.trim(),
content,
+ ...fromAccessLevel(access),
});
reset();
onCreated(created.id);
@@ -98,6 +106,7 @@ export default function CreateTemplateDialog({
kind.trim().length > 0 &&
content.length > 0 &&
!submitting &&
+ !checking &&
// Only a document the server would refuse outright. Every other finding
// is advice, and a form that gated on advice would be the checker
// deciding what may be stored.
@@ -131,6 +140,12 @@ export default function CreateTemplateDialog({
disabled={submitting}
helperText="What this template provisions — room, group, agent."
/>
+ <AccessSelect
+ value={access}
+ onChange={setAccess}
+ disabled={submitting}
+ helpers={TEMPLATE_ACCESS_HELPERS}
+ />
<Stack direction="row" spacing={1} alignItems="center">
<Button
startIcon={<UploadFileIcon />}
diff --git a/gateway/src/pages/resources/ResourceFiltersBar.tsx b/gateway/src/pages/resources/ResourceFiltersBar.tsx
index 5fa59f173..d04e7877b 100644
--- a/gateway/src/pages/resources/ResourceFiltersBar.tsx
+++ b/gateway/src/pages/resources/ResourceFiltersBar.tsx
@@ -27,6 +27,7 @@ interface Props {
types?: TypeOption[];
/** What this axis is called on the resource being listed. */
typeLabel?: string;
+ searchPlaceholder?: string;
}
export default function ResourceFiltersBar({
@@ -39,6 +40,7 @@ export default function ResourceFiltersBar({
onTypeChange,
types,
typeLabel = "Type",
+ searchPlaceholder,
}: Props) {
const hasType = types !== undefined && onTypeChange !== undefined;
@@ -46,7 +48,7 @@ export default function ResourceFiltersBar({
<Stack direction="row" spacing={2} alignItems="center" sx={{ mb: 2 }}>
<TextField
size="small"
- placeholder="Search by name…"
+ placeholder={searchPlaceholder ?? "Search by name…"}
value={search}
onChange={(e) => onSearchChange(e.target.value)}
sx={{ minWidth: 240 }}
diff --git a/gateway/src/pages/resources/TemplateDetailPage.tsx b/gateway/src/pages/resources/TemplateDetailPage.tsx
index 47642299a..c12c1298d 100644
--- a/gateway/src/pages/resources/TemplateDetailPage.tsx
+++ b/gateway/src/pages/resources/TemplateDetailPage.tsx
@@ -22,9 +22,15 @@ import {
fetchTemplateContent,
updateTemplate,
} from "../../data/api";
-import { useAuth } from "../../data/AuthContext";
+import { AccessChip, AccessSelect } from "../../components/AccessControls";
+import {
+ type AccessLevel,
+ fromAccessLevel,
+ toAccessLevel,
+} from "../../data/visibility";
import { EM_DASH, MONO_SX, formatDateTime } from "../../theme/hootFormat";
import DeleteTemplateDialog from "./DeleteTemplateDialog";
+import { TEMPLATE_ACCESS_HELPERS } from "./templateAccess";
import TemplateFindings from "./TemplateFindings";
import { formatBytes, templateFilename } from "./templateFormat";
import { useTemplateValidation } from "./useTemplateValidation";
@@ -34,7 +40,6 @@ const LIST_URL = "/resources?tab=templates";
export default function TemplateDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
- const { user } = useAuth();
const [template, setTemplate] = useState<TemplateDetail | null>(null);
const [loading, setLoading] = useState(true);
const [fetchError, setFetchError] = useState<string | null>(null);
@@ -44,12 +49,20 @@ export default function TemplateDetailPage() {
if (!id) return;
let cancelled = false;
setLoading(true);
- fetchTemplate(id).then((t) => {
- if (cancelled) return;
- if (t) setTemplate(t);
- else setFetchError("Template not found");
- setLoading(false);
- });
+ setFetchError(null);
+ fetchTemplate(id)
+ .then((t) => {
+ if (cancelled) return;
+ setTemplate(t);
+ setLoading(false);
+ })
+ .catch((e: unknown) => {
+ if (cancelled) return;
+ // The server's reason, shown as is: a private template the caller may
+ // not see and a server that is down are different problems.
+ setFetchError(e instanceof Error ? e.message : "Could not load this template");
+ setLoading(false);
+ });
return () => {
cancelled = true;
};
@@ -76,8 +89,11 @@ export default function TemplateDetailPage() {
);
}
- const canMutate =
- !!user && (user.id === template.owner_id || user.role === "admin");
+ // The server says what this user may do. The user's global role would not:
+ // a workspace admin whose global role is plain "user" may still manage
+ // every template here, and an open template is edited by anyone.
+ const canEdit = template.can_edit;
+ const canManage = template.can_manage;
return (
<Box>
@@ -96,10 +112,11 @@ export default function TemplateDetailPage() {
<Divider />
<DocumentSection
template={template}
- canMutate={canMutate}
+ canEdit={canEdit}
+ canManage={canManage}
onSaved={setTemplate}
/>
- {canMutate && (
+ {canManage && (
<>
<Divider />
<DangerSection onDelete={() => setDeleteOpen(true)} />
@@ -132,6 +149,9 @@ function InfoSection({ template }: { template: TemplateDetail }) {
value={template.owner_name ?? template.owner_id}
mono={!template.owner_name}
/>
+ <Typography variant="body2" color="text.secondary">
+ <strong>Access:</strong> <AccessChip pair={template} />
+ </Typography>
<InfoLine label="Revision" value={String(template.version)} />
<InfoLine label="Size" value={formatBytes(template.size_bytes)} />
<InfoLine label="Created" value={formatDateTime(template.created_at)} />
@@ -167,16 +187,20 @@ function InfoLine({
function DocumentSection({
template,
- canMutate,
+ canEdit,
+ canManage,
onSaved,
}: {
template: TemplateDetail;
- canMutate: boolean;
+ canEdit: boolean;
+ /** Only the owner or an admin changes who may see or edit it. */
+ canManage: boolean;
onSaved: (updated: TemplateDetail) => void;
}) {
const [name, setName] = useState(template.name);
const [description, setDescription] = useState(template.description);
const [kind, setKind] = useState(template.kind);
+ const [access, setAccess] = useState<AccessLevel>(toAccessLevel(template));
const [content, setContent] = useState(template.content);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -184,7 +208,7 @@ function DocumentSection({
const [copied, setCopied] = useState(false);
// Only while the document is editable — a reader cannot act on the findings.
const { result: validation, checking } = useTemplateValidation(content, {
- enabled: canMutate,
+ enabled: canEdit,
});
const dirty = useMemo(
@@ -192,22 +216,31 @@ function DocumentSection({
name !== template.name ||
description !== template.description ||
kind !== template.kind ||
- content !== template.content,
- [name, description, kind, content, template],
+ content !== template.content ||
+ access !== toAccessLevel(template),
+ [name, description, kind, content, access, template],
);
const handleSave = async () => {
setSaving(true);
setError(null);
try {
+ // Only what changed is sent, so an edit to the name or the access
+ // cannot put back a document someone else saved meanwhile.
const updated = await updateTemplate(template.id, {
- name,
- description,
- kind,
- content,
+ ...(name !== template.name ? { name } : {}),
+ ...(description !== template.description ? { description } : {}),
+ ...(kind !== template.kind ? { kind } : {}),
+ ...(content !== template.content ? { content } : {}),
+ // Sent only by someone allowed to change it; the server refuses it otherwise.
+ ...(canManage && access !== toAccessLevel(template) ? fromAccessLevel(access) : {}),
});
onSaved(updated);
+ setName(updated.name);
+ setDescription(updated.description);
+ setKind(updated.kind);
setContent(updated.content);
+ setAccess(toAccessLevel(updated));
} catch (e) {
setError(e instanceof Error ? e.message : "Failed to save");
} finally {
@@ -273,12 +306,9 @@ function DocumentSection({
</Stack>
{exportError && <Alert severity="error">{exportError}</Alert>}
{copied && <Alert severity="success">Document copied to the clipboard.</Alert>}
- {!canMutate && (
- // Said outright rather than left to the greyed-out fields. Every
- // template on the server is visible to everyone, so reading someone
- // else's is the ordinary case here, not the exception it is for the
- // resources next door — and a disabled field on its own only tells you
- // something is wrong once you have already tried to type in it.
+ {!canEdit && (
+ // Reading someone else's shared template is the ordinary case here,
+ // and a disabled field alone reads as a page that failed to load.
<Alert severity="info">
This template belongs to {template.owner_name ?? "another user"}. You
can copy or download it; only its owner or an admin can change it.
@@ -288,13 +318,13 @@ function DocumentSection({
label="Name"
value={name}
onChange={(e) => setName(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
/>
<TextField
label="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={2}
helperText="Shown in the catalogue, and searched alongside the name."
@@ -303,14 +333,21 @@ function DocumentSection({
label="Kind"
value={kind}
onChange={(e) => setKind(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
+ sx={{ maxWidth: 320 }}
+ />
+ <AccessSelect
+ value={access}
+ onChange={setAccess}
+ disabled={!canManage || saving}
+ helpers={TEMPLATE_ACCESS_HELPERS}
sx={{ maxWidth: 320 }}
/>
<TextField
label="Document"
value={content}
onChange={(e) => setContent(e.target.value)}
- disabled={!canMutate || saving}
+ disabled={!canEdit || saving}
multiline
minRows={16}
slotProps={{ input: { sx: { fontFamily: "monospace" } } }}
@@ -322,7 +359,7 @@ function DocumentSection({
<Button
variant="contained"
onClick={handleSave}
- disabled={!canMutate || !dirty || saving || !!validation?.blocked}
+ disabled={!canEdit || !dirty || saving || checking || !!validation?.blocked}
startIcon={saving ? <CircularProgress size={16} /> : undefined}
>
Save
diff --git a/gateway/src/pages/resources/TemplatesTab.tsx b/gateway/src/pages/resources/TemplatesTab.tsx
index 5572686cb..0fe8bb71f 100644
--- a/gateway/src/pages/resources/TemplatesTab.tsx
+++ b/gateway/src/pages/resources/TemplatesTab.tsx
@@ -2,6 +2,7 @@ import { Alert, Box, Chip, CircularProgress } from "@mui/material";
import type { GridColDef } from "@mui/x-data-grid";
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router";
+import { AccessChip } from "../../components/AccessControls";
import DataTable from "../../components/DataTable";
import type { TemplateSummary } from "../../data/api";
import { useTemplates } from "../../data/hooks";
@@ -15,46 +16,49 @@ interface Props {
export default function TemplatesTab({ refreshKey }: Props) {
const navigate = useNavigate();
- const { data: templates, loading, error, refetch } = useTemplates();
const [search, setSearch] = useState("");
+ // The server searches name and description. The request waits until
+ // typing has paused for a moment.
+ const [searchSent, setSearchSent] = useState("");
+ useEffect(() => {
+ const timer = window.setTimeout(() => setSearchSent(search.trim()), 250);
+ return () => window.clearTimeout(timer);
+ }, [search]);
const [ownerId, setOwnerId] = useState<string>("");
const [kind, setKind] = useState<string>("");
+ // Every filter is the server's. The whole catalogue is fetched once more,
+ // unfiltered, so the owner and kind options do not shrink to what the
+ // current search happens to match and hide the value that is selected.
+ const { data: catalogue, refetch: refetchCatalogue } = useTemplates();
+ const {
+ data: templates,
+ loading,
+ error,
+ refetch,
+ } = useTemplates({ q: searchSent, kind, owner_id: ownerId });
useEffect(() => {
refetch();
+ refetchCatalogue();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refreshKey]);
const owners = useMemo(() => {
const m = new Map<string, string>();
- for (const t of templates ?? []) {
+ for (const t of catalogue ?? []) {
m.set(t.owner_id, t.owner_name ?? t.owner_id);
}
return [...m.entries()].map(([id, name]) => ({ id, name }));
- }, [templates]);
+ }, [catalogue]);
// Kinds are free text on the server, so the filter offers whatever is
// actually in the registry rather than a list this page would have to grow.
const kinds = useMemo(() => {
- const seen = new Set((templates ?? []).map((t) => t.kind));
+ const seen = new Set((catalogue ?? []).map((t) => t.kind));
return [...seen].sort().map((k) => ({ value: k, label: k }));
- }, [templates]);
+ }, [catalogue]);
- const filtered = useMemo(() => {
- const q = search.trim().toLowerCase();
- return (templates ?? []).filter((t) => {
- if (ownerId && t.owner_id !== ownerId) return false;
- if (kind && t.kind !== kind) return false;
- if (
- q &&
- !t.name.toLowerCase().includes(q) &&
- !t.description.toLowerCase().includes(q)
- ) {
- return false;
- }
- return true;
- });
- }, [templates, search, ownerId, kind]);
+ const filtered = templates ?? [];
const columns = useMemo<GridColDef<TemplateSummary>[]>(
() => [
@@ -73,6 +77,12 @@ export default function TemplatesTab({ refreshKey }: Props) {
<Chip size="small" variant="outlined" label={value as string} />
),
},
+ {
+ field: "read_visibility",
+ headerName: "Access",
+ width: 110,
+ renderCell: ({ row }) => <AccessChip pair={row} />,
+ },
{
field: "owner_name",
headerName: "Owner",
@@ -110,6 +120,7 @@ export default function TemplatesTab({ refreshKey }: Props) {
onTypeChange={setKind}
types={kinds}
typeLabel="Kind"
+ searchPlaceholder="Search by name or description…"
/>
{error && (
diff --git a/gateway/src/pages/resources/templateAccess.ts b/gateway/src/pages/resources/templateAccess.ts
new file mode 100644
index 000000000..281361cd4
--- /dev/null
+++ b/gateway/src/pages/resources/templateAccess.ts
@@ -0,0 +1,8 @@
+import type { AccessLevel } from "../../data/visibility";
+
+/** The access levels as they apply to a template: it is used, not attached. */
+export const TEMPLATE_ACCESS_HELPERS: Record<AccessLevel, string> = {
+ private: "Only you and admins can see it.",
+ read_only: "Everyone on the workspace can use it; only you and admins can change it.",
+ public: "Everyone on the workspace can use it and change it.",
+};
diff --git a/gateway/src/pages/resources/useTemplateValidation.ts b/gateway/src/pages/resources/useTemplateValidation.ts
index 963033db9..2eb75315c 100644
--- a/gateway/src/pages/resources/useTemplateValidation.ts
+++ b/gateway/src/pages/resources/useTemplateValidation.ts
@@ -19,13 +19,18 @@ export function useTemplateValidation(
const latest = useRef(0);
useEffect(() => {
+ // Bumped on every change, including a clear: a request still in flight
+ // for the document that was on screen a moment ago must not land.
+ const token = ++latest.current;
if (!enabled || content.trim().length === 0) {
setResult(null);
setChecking(false);
return;
}
- const token = ++latest.current;
+ // A verdict belongs to the document it was given for. Once that document
+ // changes, holding it would keep Save disabled by findings nobody can see.
+ setResult(null);
setChecking(true);
const timer = setTimeout(() => {
validateTemplate(content)