Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(switchdash): cascade server API-URL edits to member agent configs (CHOO-1431) (#30)
Louis Amaudruz0af400c9a0a8
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.db.test.tsnew file mode 100644index 000000000..887ec2b8f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.db.test.ts@@ -0,0 +1,180 @@+import { promises as nodeFs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { openFixture } from '@tooling/utils/db';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { agents, locations, switchServers } from '@main/db/schema';+import { propagateServerApiUrl } from './propagate-server-api-url';+import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+}));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++// The propagation module imports the SSH stack for the remote path. This test+// exercises only local agents, so stub those out to keep it from loading (and+// to fail loud if a remote write is attempted unexpectedly).+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({+ ensureSshConnected: vi.fn(() => {+ throw new Error('remote path not expected in this test');+ }),+}));+vi.mock('@main/core/fs/impl/ssh-fs', () => ({+ SshFileSystem: class {},+}));+vi.mock('@main/core/locations/location-transport', () => ({+ sshConnectionIdForHost: (host: string) => host,+}));++async function writeSettings(dir: string, contents: Record<string, unknown>): Promise<void> {+ const file = path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH);+ await nodeFs.mkdir(path.dirname(file), { recursive: true });+ await nodeFs.writeFile(file, JSON.stringify(contents, null, 2), 'utf8');+}++async function readEnv(dir: string): Promise<Record<string, unknown>> {+ const raw = await nodeFs.readFile(path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH), 'utf8');+ return (JSON.parse(raw) as { env: Record<string, unknown> }).env;+}++describe('propagateServerApiUrl', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;+ let tmpRoot: string;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ tmpRoot = await nodeFs.mkdtemp(path.join(os.tmpdir(), 'switchdash-propagate-'));++ await fixture.db.insert(switchServers).values([+ {+ id: 'pilot',+ name: 'Pilot',+ gatewayUrl: 'https://pilot-gateway.example.com',+ apiUrl: 'https://old-api.example.com',+ },+ {+ id: 'other',+ name: 'Other',+ gatewayUrl: 'https://other-gateway.example.com',+ apiUrl: 'https://other-api.example.com',+ },+ ]);+ });++ afterEach(async () => {+ fixture.close();+ mocks.db = undefined;+ await nodeFs.rm(tmpRoot, { recursive: true, force: true });+ });++ it('rewrites the endpoint for provisioned member agents, preserves the token, and updates the DB mirror', async () => {+ const dir = path.join(tmpRoot, 'provisioned');+ await writeSettings(dir, {+ permissions: { allow: ['Bash'] },+ env: {+ EXISTING_KEY: 'keep-me',+ SWITCH_API_ENDPOINT: 'https://old-api.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'switch-agent-1',+ },+ });+ await fixture.db.insert(locations).values({ id: 'loc-1', name: 'Local', sshHost: '', dir });+ await fixture.db.insert(agents).values({+ id: 'agent-1',+ locationId: 'loc-1',+ name: 'provisioned-agent',+ providerId: 'claude',+ apiEndpoint: 'https://old-api.example.com',+ serverId: 'pilot',+ });++ const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');++ expect(results).toEqual([+ {+ agentId: 'agent-1',+ agentName: 'provisioned-agent',+ location: 'local',+ outcome: 'updated',+ },+ ]);++ // On disk: only the endpoint changed; token, id, other keys preserved.+ expect(await readEnv(dir)).toEqual({+ EXISTING_KEY: 'keep-me',+ SWITCH_API_ENDPOINT: 'https://new-api.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'switch-agent-1',+ });++ // DB mirror follows the file.+ const [row] = await fixture.db+ .select({ apiEndpoint: agents.apiEndpoint })+ .from(agents)+ .where(eq(agents.id, 'agent-1'));+ expect(row?.apiEndpoint).toBe('https://new-api.example.com');+ });++ it('reports an unprovisioned agent as not-provisioned without writing a file', async () => {+ const dir = path.join(tmpRoot, 'unprovisioned');+ await nodeFs.mkdir(dir, { recursive: true });+ await fixture.db.insert(locations).values({ id: 'loc-2', name: 'Local2', sshHost: '', dir });+ await fixture.db.insert(agents).values({+ id: 'agent-2',+ locationId: 'loc-2',+ name: 'bare-agent',+ providerId: 'claude',+ apiEndpoint: null,+ serverId: 'pilot',+ });++ const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');++ expect(results).toEqual([+ {+ agentId: 'agent-2',+ agentName: 'bare-agent',+ location: 'local',+ outcome: 'not-provisioned',+ },+ ]);+ // No settings file was created.+ await expect(nodeFs.access(path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH))).rejects.toThrow();+ });++ it('only touches agents linked to the edited server', async () => {+ const dir = path.join(tmpRoot, 'other-server');+ await writeSettings(dir, {+ env: {+ SWITCH_API_ENDPOINT: 'https://other-api.example.com',+ SWITCH_API_TOKEN: 'other-token',+ SWITCH_AGENT_ID: 'switch-agent-other',+ },+ });+ await fixture.db.insert(locations).values({ id: 'loc-3', name: 'Local3', sshHost: '', dir });+ await fixture.db.insert(agents).values({+ id: 'agent-3',+ locationId: 'loc-3',+ name: 'other-agent',+ providerId: 'claude',+ apiEndpoint: 'https://other-api.example.com',+ serverId: 'other',+ });++ const results = await propagateServerApiUrl('pilot', 'https://new-api.example.com');++ // 'pilot' has no agents -> empty result, and the 'other' agent's file is untouched.+ expect(results).toEqual([]);+ expect((await readEnv(dir)).SWITCH_API_ENDPOINT).toBe('https://other-api.example.com');+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.ts b/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.tsnew file mode 100644index 000000000..3fe2df075--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.ts@@ -0,0 +1,142 @@+import { promises as nodeFs } from 'node:fs';+import path from 'node:path';+import { eq } from 'drizzle-orm';+import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';+import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';+import { db } from '@main/db/client';+import { agents } from '@main/db/schema';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';+import type { AgentApiUrlPropagation } from '@shared/core/switch-servers/switch-servers';+import { getAgentLocation } from './agent-location';+import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';+import { updateAgent } from './updateAgent';+import { mapAgentRowToAgent } from './utils';+import { mergeSwitchApiEndpoint } from './write-switch-settings';++// Remote hosts are POSIX; use a forward-slash literal rather than the+// platform-dependent SWITCH_SETTINGS_RELATIVE_PATH (which emits backslashes when+// switchdash runs on Windows). Matches write-remote-switch-settings.ts.+const REMOTE_SETTINGS_PATH = '.claude/settings.local.json';++/**+ * Rewrite one local agent's `SWITCH_API_ENDPOINT`, preserving its token and+ * every other key. Returns whether the file was updated (false = not a+ * provisioned Switch agent, so nothing to do).+ */+async function propagateLocal(dir: string, apiEndpoint: string): Promise<boolean> {+ const settingsPath = path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH);++ let existingRaw: string | null = null;+ try {+ existingRaw = await nodeFs.readFile(settingsPath, 'utf8');+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ // Absent file/dir -> unprovisioned agent. Any other read failure must+ // propagate rather than be mistaken for "no config".+ if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;+ }++ const merged = mergeSwitchApiEndpoint(existingRaw, apiEndpoint);+ if (merged === null) return false;+ await nodeFs.writeFile(settingsPath, merged, 'utf8');+ return true;+}++/**+ * Rewrite one remote agent's `SWITCH_API_ENDPOINT` over SFTP, preserving its+ * token and every other key. Returns whether the file was updated.+ */+async function propagateRemote(+ sshHost: string,+ remoteRepoDir: string,+ apiEndpoint: string+): Promise<boolean> {+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);+ const fs = new SshFileSystem(proxy, remoteRepoDir);+ try {+ let existingRaw: string | null = null;+ try {+ ({ content: existingRaw } = await fs.read(REMOTE_SETTINGS_PATH));+ } catch (error) {+ // Absent file -> unprovisioned agent. A transport failure (dead SSH+ // connection) must propagate rather than look like "no config".+ if (!(error instanceof FileSystemError && error.code === FileSystemErrorCodes.NOT_FOUND)) {+ throw error;+ }+ }++ const merged = mergeSwitchApiEndpoint(existingRaw, apiEndpoint);+ if (merged === null) return false;+ const result = await fs.write(REMOTE_SETTINGS_PATH, merged);+ if (!result.success) {+ throw new Error(`failed to write remote Switch settings: ${result.error ?? 'unknown error'}`);+ }+ return true;+ } finally {+ fs.close();+ }+}++/** Cascade a server API-URL edit to a single member agent, mapping any failure+ * to a `failed` outcome so one bad agent never aborts the rest. */+async function propagateToAgent(+ agent: Agent,+ apiEndpoint: string+): Promise<AgentApiUrlPropagation> {+ try {+ const location = await getAgentLocation(agent);+ const sshHost = location.sshHost;+ const isRemote = sshHost !== null;+ const updated = isRemote+ ? await propagateRemote(sshHost, location.dir, apiEndpoint)+ : await propagateLocal(location.dir, apiEndpoint);++ if (updated) {+ // Keep the DB mirror in step with what is now on disk.+ await updateAgent({ agentId: agent.id, apiEndpoint });+ }+ return {+ agentId: agent.id,+ agentName: agent.name,+ location: isRemote ? 'remote' : 'local',+ outcome: updated ? 'updated' : 'not-provisioned',+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log.error('switch-agents: failed to propagate server API URL to agent', {+ agentId: agent.id,+ error: message,+ });+ return {+ agentId: agent.id,+ agentName: agent.name,+ // Location lookup itself may have thrown; report best-effort.+ location: 'local',+ outcome: 'failed',+ error: message,+ };+ }+}++/**+ * Cascade a server's new API URL to every agent linked to it, rewriting each+ * agent's on-disk `SWITCH_API_ENDPOINT` (local dir or remote SSH host) and the+ * DB mirror. Agents keep their token; unprovisioned agents are skipped, not+ * clobbered. Returns a per-agent summary — failures are reported, never+ * swallowed — so the caller can surface which agents changed and which need a+ * running session restarted to pick up the new endpoint.+ */+export async function propagateServerApiUrl(+ serverId: string,+ apiEndpoint: string+): Promise<AgentApiUrlPropagation[]> {+ const rows = await db.select().from(agents).where(eq(agents.serverId, serverId));+ const results: AgentApiUrlPropagation[] = [];+ for (const row of rows) {+ results.push(await propagateToAgent(mapAgentRowToAgent(row), apiEndpoint));+ }+ return results;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.tsindex 511f9b861..d61de7d60 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -4,7 +4,7 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { detectSwitchAgent } from './detect';import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';-import { writeSwitchSettings } from './write-switch-settings';+import { mergeSwitchApiEndpoint, writeSwitchSettings } from './write-switch-settings';let dir: string;@@ -86,3 +86,48 @@ describe('writeSwitchSettings', () => {});});});++describe('mergeSwitchApiEndpoint', () => {+ it('rewrites only SWITCH_API_ENDPOINT, preserving token, id, and other keys', () => {+ const existing = JSON.stringify({+ permissions: { allow: ['Bash'] },+ hooks: { PostToolUse: [{ command: 'x' }] },+ env: {+ EXISTING_KEY: 'keep-me',+ SWITCH_API_ENDPOINT: 'https://old.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'agent-123',+ },+ });++ const merged = mergeSwitchApiEndpoint(existing, 'https://new.example.com');+ expect(merged).not.toBeNull();+ const parsed = JSON.parse(merged as string) as Record<string, unknown>;++ // Endpoint changed; token, id, and every other key untouched.+ expect(parsed.env).toEqual({+ EXISTING_KEY: 'keep-me',+ SWITCH_API_ENDPOINT: 'https://new.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'agent-123',+ });+ expect(parsed.permissions).toEqual({ allow: ['Bash'] });+ expect(parsed.hooks).toEqual({ PostToolUse: [{ command: 'x' }] });+ });++ it('returns null for a file that is not a provisioned Switch agent', () => {+ // Absent file.+ expect(mergeSwitchApiEndpoint(null, 'https://new.example.com')).toBeNull();+ // Unparseable.+ expect(mergeSwitchApiEndpoint('{not json', 'https://new.example.com')).toBeNull();+ // No env block.+ expect(mergeSwitchApiEndpoint('{}', 'https://new.example.com')).toBeNull();+ // Partial creds (no token) -> not provisioned, skip rather than half-write.+ expect(+ mergeSwitchApiEndpoint(+ JSON.stringify({ env: { SWITCH_API_ENDPOINT: 'https://old', SWITCH_AGENT_ID: 'a' } }),+ 'https://new.example.com'+ )+ ).toBeNull();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.tsindex ad1de79a1..3915200a9 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts@@ -71,6 +71,57 @@ export function mergeSwitchSettings(return `${JSON.stringify(merged, null, 2)}\n`;}+/**+ * Update ONLY `SWITCH_API_ENDPOINT` in an already-provisioned settings file,+ * returning the new file text — or `null` when the file is not a provisioned+ * Switch agent (missing/unparseable, or its `env` lacks the full `SWITCH_*`+ * credential block). Used to cascade a server's API-URL edit to its agents+ * without ever reading or rewriting the agent's `SWITCH_API_TOKEN`: the token,+ * agent id, permissions, and every other key are left byte-for-byte untouched.+ *+ * Returning `null` (rather than writing) for an unprovisioned file is deliberate+ * — the caller skips it instead of creating a token-less config that would look+ * configured but can't authenticate.+ *+ * Pure: takes the existing file text (or null when absent/unreadable) and+ * returns the text to write. Shared by the local and remote (SFTP) propagation+ * paths so both produce byte-identical files.+ */+export function mergeSwitchApiEndpoint(+ existingRaw: string | null,+ apiEndpoint: string+): string | null {+ if (existingRaw === null) return null;++ let parsed: unknown;+ try {+ parsed = JSON.parse(existingRaw);+ } catch {+ return null;+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;++ const existing = parsed as Record<string, unknown>;+ const env =+ existing.env && typeof existing.env === 'object' && !Array.isArray(existing.env)+ ? (existing.env as Record<string, unknown>)+ : null;++ // Only a fully provisioned agent (endpoint + token + id all present) is+ // propagated to; anything else is "not a Switch agent here" -> skip.+ if (+ !env ||+ typeof env.SWITCH_API_ENDPOINT !== 'string' ||+ typeof env.SWITCH_API_TOKEN !== 'string' ||+ typeof env.SWITCH_AGENT_ID !== 'string'+ ) {+ return null;+ }++ const merged = { ...existing, env: { ...env, SWITCH_API_ENDPOINT: apiEndpoint } };+ return `${JSON.stringify(merged, null, 2)}\n`;+}+/*** Write the `SWITCH_*` env block into a local directory's* `.claude/settings.local.json`, the same file the switch-connectordiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.tsindex d3f2faab6..c9b2f1b1b 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts@@ -1,5 +1,6 @@import type { Result } from '@switchdash/shared';import { suggestAgentDefaults } from '@main/core/agents/agent-defaults';+import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { writeRemoteSwitchSettings } from '@main/core/agents/write-remote-switch-settings';import { writeSwitchSettings } from '@main/core/agents/write-switch-settings';@@ -24,6 +25,7 @@ import type {SwitchAuthConfig,SwitchServer,UpdateServerParams,+ UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';import { createRPCController } from '@shared/lib/ipc/rpc';import { type LoginError, oidcLogin, passwordLogin } from './auth';@@ -115,10 +117,21 @@ export const switchServersController = createRPCController({return server;},- updateServer: async (params: UpdateServerParams): Promise<SwitchServer> => {+ updateServer: async (params: UpdateServerParams): Promise<UpdateServerResult> => {+ const previous = await requireServer(params.id);const server = await updateServer(params);await resolveAgentServers();- return server;++ // The API URL is what an agent's SWITCH_API_ENDPOINT points at. When it+ // changes, cascade it to every member agent's stored config so they don't+ // keep authenticating against the stale endpoint (CHOO-1431). Compare the+ // saved (normalised) values so a no-op edit doesn't rewrite configs.+ const apiUrlChanged = previous.apiUrl !== server.apiUrl;+ const propagatedAgents = apiUrlChanged+ ? await propagateServerApiUrl(server.id, server.apiUrl)+ : [];++ return { server, propagation: { apiUrlChanged, agents: propagatedAgents } };},removeServer: (serverId: string): Promise<void> => removeServer(serverId),diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsxindex 75841a544..1819ac519 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsx@@ -1,6 +1,7 @@import { CircleCheck, HardDrive, Server, TriangleAlert } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useEffect, useRef, useState } from 'react';+import { toast } from '@renderer/lib/hooks/use-toast';import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';import { Button } from '@renderer/lib/ui/button';@@ -14,9 +15,38 @@ import {import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { Spinner } from '@renderer/lib/ui/spinner';+import type { ServerApiUrlPropagation } from '@shared/core/switch-servers/switch-servers';import { localServerStore } from './local-server-store';import { switchServersStore } from './switch-servers-store';+/**+ * Turn a server-API-URL cascade into a user-facing toast: confirm how many+ * agents were re-pointed (and that running sessions need a restart), and flag+ * any that failed so the edit never looks cleanly done when it wasn't.+ */+function notifyPropagation(propagation: ServerApiUrlPropagation): void {+ if (!propagation.apiUrlChanged) return;+ const updated = propagation.agents.filter((a) => a.outcome === 'updated');+ const failed = propagation.agents.filter((a) => a.outcome === 'failed');++ if (failed.length > 0) {+ toast({+ title: `Couldn't update ${failed.length} agent config${failed.length === 1 ? '' : 's'}`,+ description: `${failed.map((a) => a.agentName).join(', ')}. ${updated.length} other${updated.length === 1 ? '' : 's'} updated. Check the agent's host is reachable and retry.`,+ variant: 'destructive',+ });+ return;+ }++ if (updated.length > 0) {+ toast({+ title: `Updated ${updated.length} agent config${updated.length === 1 ? '' : 's'}`,+ description:+ 'Each agent now points at the new API URL. Restart any running sessions to pick it up.',+ });+ }+}+type Props = BaseModalProps<void> & {/** Prefill the gateway URL. */initialGatewayUrl?: string;@@ -373,17 +403,26 @@ const RemoteServerStep = observer(function RemoteServerStep({if (!isValid) return;setSubmitting(true);setError(null);- const saved =- isEdit && serverId- ? await switchServersStore.updateServer(serverId, trimmedName, trimmedGateway, trimmedApi)- : await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);- if (!saved) {- setError(- switchServersStore.error ??- (isEdit ? 'Could not save the server.' : 'Could not add the server.')+ if (isEdit && serverId) {+ const result = await switchServersStore.updateServer(+ serverId,+ trimmedName,+ trimmedGateway,+ trimmedApi);- setSubmitting(false);- return;+ if (!result) {+ setError(switchServersStore.error ?? 'Could not save the server.');+ setSubmitting(false);+ return;+ }+ notifyPropagation(result.propagation);+ } else {+ const saved = await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);+ if (!saved) {+ setError(switchServersStore.error ?? 'Could not add the server.');+ setSubmitting(false);+ return;+ }}onSuccess();}, [isValid, isEdit, serverId, trimmedName, trimmedGateway, trimmedApi, onSuccess]);diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.tsindex c852b09fc..7d8c02202 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts@@ -4,6 +4,7 @@ import type {ServerConnectionStatus,SwitchAuthConfig,SwitchServer,+ UpdateServerResult,} from '@shared/core/switch-servers/switch-servers';/**@@ -150,15 +151,15 @@ export class SwitchServersStore {name: string,gatewayUrl: string,apiUrl: string- ): Promise<SwitchServer | null> {+ ): Promise<UpdateServerResult | null> {this.clearError();try {- const updated = await rpc.switchServers.updateServer({ id, name, gatewayUrl, apiUrl });+ const result = await rpc.switchServers.updateServer({ id, name, gatewayUrl, apiUrl });const servers = await rpc.switchServers.listServers();runInAction(() => {this.servers = servers;});- return updated;+ return result;} catch (cause) {this.setError(cause);return null;diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.tsindex ec7561a67..14b01ce50 100644--- a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -40,6 +40,40 @@ export type UpdateServerParams = {apiUrl: string;};+/**+ * What happened to one agent when a server's API URL was cascaded to its+ * members. `updated` — the agent's `SWITCH_API_ENDPOINT` was rewritten.+ * `not-provisioned` — the agent has no Switch credentials on disk yet, so there+ * was nothing to update (skipped, not an error). `failed` — the rewrite threw+ * (e.g. an unreachable SSH host); `error` carries why.+ */+export type AgentApiUrlPropagationOutcome = 'updated' | 'not-provisioned' | 'failed';++/** Per-agent result of a server-API-URL cascade. */+export type AgentApiUrlPropagation = {+ agentId: string;+ agentName: string;+ /** Where the agent's config lives: a local dir vs. an SSH host. */+ location: 'local' | 'remote';+ outcome: AgentApiUrlPropagationOutcome;+ /** Present only when `outcome === 'failed'`. */+ error?: string;+};++/** Summary of cascading a server's API-URL edit to its member agents. */+export type ServerApiUrlPropagation = {+ /** True when the API URL actually changed, so propagation ran. When false the+ * `agents` list is empty (the edit was name/gateway-only). */+ apiUrlChanged: boolean;+ agents: AgentApiUrlPropagation[];+};++/** Result of editing a server: the saved record plus the agent-config cascade. */+export type UpdateServerResult = {+ server: SwitchServer;+ propagation: ServerApiUrlPropagation;+};+/** Which login methods a gateway offers — read unauthenticated from* `GET /gateway/auth/config` so the UI shows the right options. */export type SwitchAuthConfig = {