Skip to content

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

fix(console): audit and fix the user-facing error messages (CHOO-2060) (#245)

Louis Amaudruzad0570da6591
diff --git a/console/apps/switch-console-desktop/.oxlintrc.json b/console/apps/switch-console-desktop/.oxlintrc.json
index d4c2f857a..9c6455f72 100644
--- a/console/apps/switch-console-desktop/.oxlintrc.json
+++ b/console/apps/switch-console-desktop/.oxlintrc.json
@@ -76,6 +76,7 @@
{
"files": ["src/renderer/**/*.{ts,tsx}"],
"rules": {
+ "switch-console/no-raw-error-text": "error",
"no-restricted-imports": [
"error",
{
@@ -93,7 +94,14 @@
"files": ["**/*.test.{ts,tsx}"],
"rules": {
"typescript/no-explicit-any": "off",
- "switch-console/no-tooling-imports": "off"
+ "switch-console/no-tooling-imports": "off",
+ "switch-console/no-raw-error-text": "off"
+ }
+ },
+ {
+ "files": ["src/renderer/lib/errors/describe-failure.ts"],
+ "rules": {
+ "switch-console/no-raw-error-text": "off"
}
}
]
diff --git a/console/apps/switch-console-desktop/src/main/core/locations/location-runtime-factory.ts b/console/apps/switch-console-desktop/src/main/core/locations/location-runtime-factory.ts
index 175c05410..6cee0cebb 100644
--- a/console/apps/switch-console-desktop/src/main/core/locations/location-runtime-factory.ts
+++ b/console/apps/switch-console-desktop/src/main/core/locations/location-runtime-factory.ts
@@ -13,6 +13,7 @@ import { type LocationRuntimeFactoryResult } from '@main/core/locations/location
import { preflightRemoteSession } from '@main/core/sessions/remote-session-preflight';
import { appSettingsService } from '@main/core/settings/settings-service';
import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
+import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-connection-manager';
import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';
import { resolveLocalAutomationShellWithSystemFallback } from '@main/core/terminal-shell/resolver';
import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';
@@ -255,6 +256,7 @@ export async function buildAgentRuntime(
host: transport.host,
workDir: transport.dir,
credsRelPaths: opts.credsRelPaths,
+ isAuthSuspended: () => sshConnectionManager.isAuthSuspended(transport.connectionId),
});
// Remote sessions always run under tmux — it persists the agent's PTY and
// is the pane the sidecar injects into and reattaches to.
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.test.ts b/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.test.ts
index 6f84e65c5..da8c17390 100644
--- a/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.test.ts
@@ -18,6 +18,9 @@ function makeDeps(opts: {
endpointReachable?: boolean;
workDirMissing?: boolean;
channelExhausted?: boolean;
+ transportDown?: boolean;
+ authSuspended?: boolean;
+ endpoint?: string;
}) {
const missing = opts.missingBinaries ?? [];
const nodeVersion = opts.nodeVersion ?? 'v18.19.0';
@@ -29,6 +32,11 @@ function makeDeps(opts: {
if (opts.channelExhausted) {
throw Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 2 });
}
+ if (opts.transportDown) {
+ throw Object.assign(new Error('SSH transport failure: SSH connection is not available'), {
+ transportFailure: true,
+ });
+ }
if (opts.workDirMissing) throw new Error('cd: no such file or directory');
const lines = [
...missing.map((b) => `missing ${b}`),
@@ -37,15 +45,27 @@ function makeDeps(opts: {
return { stdout: lines.join('\n'), stderr: '' };
}
if (command === 'node') {
- if (opts.endpointReachable === false) throw new Error('ECONNREFUSED');
+ // Captured remote stderr keeps its trailing newline, which is what put
+ // the stray space into `TypeError: fetch failed . The sidecar polls…`.
+ if (opts.endpointReachable === false) throw new Error('TypeError: fetch failed\n');
return { stdout: '', stderr: '' };
}
return { stdout: '', stderr: '' };
});
+ const credsFile =
+ opts.endpoint && opts.credsFile
+ ? JSON.stringify({
+ env: {
+ SWITCH_API_ENDPOINT: opts.endpoint,
+ SWITCH_API_TOKEN: 'tok',
+ SWITCH_AGENT_ID: 'agent-1',
+ },
+ })
+ : opts.credsFile;
const fs = {
read: vi.fn(async (_path: string) => {
- if (opts.credsFile == null) throw new Error('no such file');
- return { content: opts.credsFile };
+ if (credsFile == null) throw new Error('no such file');
+ return { content: credsFile };
}),
};
return {
@@ -55,6 +75,7 @@ function makeDeps(opts: {
host: 'box',
workDir: '/home/agent/repo',
credsRelPaths: ['.switch/agents/agent-1.json', '.claude/settings.local.json'],
+ isAuthSuspended: () => opts.authSuspended ?? false,
exec,
};
}
@@ -135,6 +156,53 @@ describe('preflightRemoteSession', () => {
it('fails loud when the host cannot reach the Switch endpoint', async () => {
const deps = makeDeps({ credsFile: CREDS_FILE, endpointReachable: false });
- await expect(preflightRemoteSession(deps)).rejects.toThrow(/cannot reach the Switch endpoint/);
+ await expect(preflightRemoteSession(deps)).rejects.toThrow(/could not reach Switch at/);
+ });
+
+ it('keeps captured probe output out of the sentence, and trims it', async () => {
+ const deps = makeDeps({ credsFile: CREDS_FILE, endpointReachable: false });
+ const error = await preflightRemoteSession(deps).catch((e: Error) => e);
+ const message = (error as Error).message;
+ // The raw exception belongs in the parenthetical, not spliced mid-sentence,
+ // and the trailing newline must not survive as a space before punctuation.
+ expect(message).toContain('(probe: TypeError: fetch failed)');
+ expect(message).not.toMatch(/ \./);
+ });
+
+ it('names the real cause for a loopback endpoint instead of blaming egress', async () => {
+ const deps = makeDeps({
+ credsFile: CREDS_FILE,
+ endpoint: 'http://localhost:8000',
+ endpointReachable: false,
+ });
+ const error = await preflightRemoteSession(deps).catch((e: Error) => e);
+ const message = (error as Error).message;
+ // A remote host resolving localhost reaches itself, so the old advice —
+ // open network egress — could never have worked.
+ expect(message).toContain('means the host itself');
+ expect(message).not.toMatch(/egress/i);
+ expect(message).toMatch(/re-run remote setup/);
+ });
+
+ it('promises the automatic reconnect only when one is actually coming', async () => {
+ const reconnecting = makeDeps({ credsFile: CREDS_FILE, transportDown: true });
+ await expect(preflightRemoteSession(reconnecting)).rejects.toThrow(
+ /reconnecting in the background/
+ );
+ });
+
+ it('does not tell the user to wait when SSH auth was rejected', async () => {
+ const suspended = makeDeps({
+ credsFile: CREDS_FILE,
+ transportDown: true,
+ authSuspended: true,
+ });
+ const error = await preflightRemoteSession(suspended).catch((e: Error) => e);
+ const message = (error as Error).message;
+ // The reconnect loop is stopped for a rejected credential, so waiting is
+ // advice for something that is never going to happen.
+ expect(message).toMatch(/will not retry on its own/);
+ expect(message).not.toMatch(/reconnecting/i);
+ expect(message).toMatch(/Fix the credentials/);
});
});
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.ts b/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.ts
index 62d35e426..78092ab88 100644
--- a/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/remote-session-preflight.ts
@@ -58,12 +58,45 @@ export interface RemotePreflightFs {
read(path: string): Promise<{ content: string }>;
}
+/**
+ * Addresses that mean "the machine this resolves on". A remote host handed one
+ * of these is being pointed at itself, never at the machine running Switch
+ * Console — so no amount of egress will make the endpoint reachable.
+ */
+const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0', '[::]']);
+
+function isLoopbackEndpoint(endpoint: string): boolean {
+ try {
+ return LOOPBACK_HOSTNAMES.has(new URL(endpoint).hostname.toLowerCase());
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A captured failure, fit to sit in a parenthetical.
+ *
+ * Command output arrives with its trailing newline attached; interpolated
+ * straight into a sentence that produced the stray space before the full stop
+ * in `… TypeError: fetch failed . The sidecar polls …`.
+ */
+function probeDetail(error: unknown): string {
+ const raw = error instanceof Error ? error.message : String(error);
+ return raw.replace(/\s+/g, ' ').trim();
+}
+
export interface RemotePreflightDeps {
ctx: RemotePreflightExec;
fs: RemotePreflightFs;
log: CredentialsLogger;
host: string;
workDir: string;
+ /**
+ * Whether the host's SSH connection is down because authentication was
+ * rejected. That state does not auto-recover, so it changes the advice given
+ * for a transport failure from "wait" to "fix the credentials".
+ */
+ isAuthSuspended: () => boolean;
/** Candidate creds files (relative to the working dir) to check, in priority
* order — the agent's neutral `.switch/agents/<name>.json` first, then the
* legacy `.claude/settings.local.json`. The first that parses is used. */
@@ -72,7 +105,7 @@ export interface RemotePreflightDeps {
export async function preflightRemoteSession(deps: RemotePreflightDeps): Promise<void> {
const [hostReady, endpoint] = await Promise.allSettled([
- assertHostReady(deps.ctx, deps.workDir, deps.host, deps.log),
+ assertHostReady(deps.ctx, deps.workDir, deps.host, deps.log, deps.isAuthSuspended),
readRemoteEndpoint(deps),
]);
if (hostReady.status === 'rejected') throw hostReady.reason;
@@ -87,13 +120,14 @@ async function assertHostReady(
ctx: RemotePreflightExec,
workDir: string,
host: string,
- log: CredentialsLogger
+ log: CredentialsLogger,
+ isAuthSuspended: () => boolean
): Promise<void> {
let stdout: string;
try {
({ stdout } = await ctx.exec('sh', ['-c', HOST_READY_SCRIPT]));
} catch (error) {
- const detail = error instanceof Error ? error.message : String(error);
+ const detail = probeDetail(error);
const cause = error instanceof Error ? error.cause : undefined;
// A channel-open REFUSAL (the server answered "no") usually means session
// exhaustion; do not blame sshd MaxSessions for every transport failure —
@@ -110,13 +144,21 @@ async function assertHostReady(
);
}
if (isTransportFailure(error)) {
+ const authSuspended = isAuthSuspended();
log.warn('preflightRemoteSession: SSH transport failed on host-ready probe', {
workDir,
host,
detail,
+ authSuspended,
});
+ // Only the reconnecting states get told to wait. A rejected credential
+ // never becomes accepted on its own, and the reconnect loop is stopped
+ // for exactly that reason, so promising a recovery here would leave the
+ // user waiting for something that is not coming.
throw new Error(
- `the SSH connection to host '${host}' is not usable right now (${detail}). Switch Console reconnects automatically — retry in a few seconds.`
+ authSuspended
+ ? `SSH authentication to host '${host}' was rejected, so the connection is stopped. It will not retry on its own. Fix the credentials for '${host}' — the key or agent your SSH config uses for it — then start the session again. (${detail})`
+ : `The SSH connection to host '${host}' dropped. Switch Console is reconnecting in the background; start the session again in a few seconds. (${detail})`
);
}
log.warn('preflightRemoteSession: host-ready probe failed', { workDir, host, detail });
@@ -185,10 +227,18 @@ async function assertEndpointReachable(
try {
await ctx.exec('node', ['-e', REACHABILITY_SCRIPT, apiEndpoint]);
} catch (error) {
+ const detail = probeDetail(error);
+ // A loopback endpoint is not an egress problem and never becomes one: the
+ // address resolves on the host to the host, so the probe is asking the VM
+ // to call itself. The old message quoted the endpoint and still sent the
+ // user to their firewall, where there was nothing to find.
+ if (isLoopbackEndpoint(apiEndpoint)) {
+ throw new Error(
+ `Host '${host}' is configured to reach Switch at ${apiEndpoint}, which on that host means the host itself — not the machine running Switch Console. No firewall change will make this work. Set this agent's Switch endpoint to an address '${host}' can resolve, such as the Switch server's LAN or public address, then re-run remote setup for it. (probe: ${detail})`
+ );
+ }
throw new Error(
- `remote host '${host}' cannot reach the Switch endpoint ${apiEndpoint}: ${
- error instanceof Error ? error.message : String(error)
- }. The sidecar polls from the host, so it needs network egress to Switch.`
+ `Host '${host}' could not reach Switch at ${apiEndpoint}. The sidecar polls Switch from the host, so '${host}' itself needs network access to that address — reaching it from this machine is not enough. Check the host's outbound access and that the endpoint is correct for it. (probe: ${detail})`
);
}
}
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/session-service.ts b/console/apps/switch-console-desktop/src/main/core/sessions/session-service.ts
index ecca13480..9d42d2001 100644
--- a/console/apps/switch-console-desktop/src/main/core/sessions/session-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/session-service.ts
@@ -46,6 +46,17 @@ export type SessionLifecycleHooks = {
'session:runtime-ready': (sessionId: string, result: ProvisionResult) => void | Promise<void>;
};
+/**
+ * A session cannot start while its agent's location is closed. The condition is
+ * a normal one — the user closed the agent — and is undone by reopening it, so
+ * the message names the agent and the remedy. The location id it replaces was
+ * an internal key the user could not have looked up anywhere.
+ */
+function notOpenMessage(agentName: string | undefined): string {
+ const subject = agentName ? `The agent "${agentName}"` : 'This session’s agent';
+ return `${subject} is not open, so its session cannot start. Open it from the sidebar and try again.`;
+}
+
export class SessionService implements Hookable<SessionLifecycleHooks> {
private readonly _hooks = new HookCore<SessionLifecycleHooks>((name, e) =>
log.error(`SessionService: ${String(name)} hook error`, e)
@@ -104,7 +115,9 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {
): Promise<Result<ProvisionResult, TeardownSessionError>> {
const session = await this._loadSession(sessionId);
const location = locationManager.getLocation(session.agentLocationId);
- if (!location) throw new Error(`Location not open: ${session.agentLocationId}`);
+ // Recoverable in one click, so say which agent and what to do rather than
+ // handing the user the location's id, which appears nowhere they can act on.
+ if (!location) throw new Error(notOpenMessage(session.session.agentName));
// Idempotency: session is already live — return current state.
if (sessionRuntimeManager.getAgent(sessionId)) {
@@ -147,7 +160,7 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {
private async _registerAndPersist(sessionId: string, data: SessionRuntimeResult): Promise<void> {
const location = locationManager.getLocation(data.locationId);
- if (!location) throw new Error(`Location not open: ${data.locationId}`);
+ if (!location) throw new Error(notOpenMessage(undefined));
await sessionRuntimeManager.registerSession(sessionId, data, location.ctx);
diff --git a/console/apps/switch-console-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts b/console/apps/switch-console-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts
index 880949f8e..cfb82cad8 100644
--- a/console/apps/switch-console-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts
+++ b/console/apps/switch-console-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts
@@ -248,6 +248,18 @@ export class SshConnectionManager extends EventEmitter {
return this.records.get(id)?.proxy.isConnected ?? false;
}
+ /**
+ * True when the connection is down because authentication was rejected.
+ *
+ * Distinct from every other down state, because it is the one the reconnect
+ * loop deliberately does not run for: a rejected credential never becomes
+ * accepted by waiting. Anything explaining the outage to a user has to know
+ * the difference, or it will promise a recovery that is not coming.
+ */
+ isAuthSuspended(id: string): boolean {
+ return this.records.get(id)?.state === 'suspended';
+ }
+
/** IDs of all tracked connections (connected, reconnecting, or suspended). */
getConnectionIds(): string[] {
return Array.from(this.records.keys());
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts
index 8506d667b..3db499561 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/auth.ts
@@ -56,7 +56,7 @@ export async function passwordLogin(
} catch (cause) {
return err({
kind: 'failed',
- message: `Could not reach ${server.gatewayUrl}: ${cause instanceof Error ? cause.message : String(cause)}`,
+ message: `Could not reach ${server.gatewayUrl}. Check that the address is right and that the server is running. (${cause instanceof Error ? cause.message : String(cause)})`,
});
}
@@ -64,10 +64,14 @@ export async function passwordLogin(
return err({ kind: 'invalid_credentials', message: 'Invalid email or password.' });
}
if (!response.ok) {
+ // A failing gateway may answer with an HTML error page rather than a
+ // sentence; unbounded, that lands in the form as a wall of markup.
const detail = await response.text().catch(() => '');
return err({
kind: 'failed',
- message: `Login failed (${response.status})${detail ? `: ${detail}` : ''}`,
+ message: `${server.gatewayUrl} rejected the sign-in with HTTP ${response.status}. That is a problem on the server, not with your credentials.${
+ detail ? ` (${detail.replace(/\s+/g, ' ').trim().slice(0, 200)})` : ''
+ }`,
});
}
diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.ts
index fb9b2a578..412befce0 100644
--- a/console/apps/switch-console-desktop/src/main/index.ts
+++ b/console/apps/switch-console-desktop/src/main/index.ts
@@ -37,6 +37,7 @@ import { viewStateService } from './core/view-state/view-state-service';
import { initializeDatabase } from './db/initialize';
import { logAppExit, logAppStart, registerAppDiagnostics } from './lib/app-diagnostics';
import {
+ getLogFilePath,
initializeFileLogger,
registerProcessErrorLogging,
registerRendererLogHandler,
@@ -110,9 +111,22 @@ void app.whenReady().then(async () => {
}
} catch (error) {
log.error('Failed to initialize database:', error);
+ // The one failure with no UI to fall back on: the app is about to quit, so
+ // whatever the user needs to act has to be in this box. Name the likely
+ // causes and where the log is, then the raw error under its own heading.
+ const logPath = getLogFilePath();
dialog.showErrorBox(
- 'Database Initialization Failed',
- `${PRODUCT_NAME} could not start because the database failed to initialize.\n\n${error instanceof Error ? error.message : String(error)}`
+ `${PRODUCT_NAME} could not open its database`,
+ [
+ `${PRODUCT_NAME} cannot start without it, so it is closing.`,
+ '',
+ 'The usual causes are another copy of the app already running, a full disk, or the database file having been moved or made read-only. Closing the other copy and reopening is worth trying first.',
+ logPath ? `\nFull details are in the log: ${logPath}` : '',
+ '',
+ `Error: ${error instanceof Error ? error.message : String(error)}`,
+ ]
+ .filter((line) => line !== '')
+ .join('\n')
);
app.quit();
return;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
index e064a1e49..f71ad5023 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
@@ -13,6 +13,7 @@ import {
} from '@renderer/features/remote-hosts/host-readiness-notice';
import { policyHasDeadRule } from '@renderer/features/switch-servers/addressing-policy-editor';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
@@ -253,12 +254,16 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
return;
}
if (result.kind === 'invalid-name') {
- toast({ title: 'Invalid agent name', description: result.message, variant: 'destructive' });
+ toast({
+ title: 'That agent name cannot be used',
+ description: result.message,
+ variant: 'destructive',
+ });
return;
}
if (result.kind === 'error') {
toast({
- title: 'Failed to register agent',
+ title: 'The agent could not be registered on the server. Nothing was created.',
description: result.message,
variant: 'destructive',
});
@@ -305,11 +310,11 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
log.error(error);
setCloseGuard(false);
setSubmitState('idle');
- toast({
- title: 'Failed to add agent',
- description: String(error),
- variant: 'destructive',
- });
+ const { headline, detail } = describeFailure(
+ error,
+ 'Could not add the agent. Nothing was created — check the directory is reachable and writable, then try again.'
+ );
+ toast({ title: headline, description: detail ?? undefined, variant: 'destructive' });
}
};
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
index a142a9bb4..e1bf11047 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/location-titlebar.tsx
@@ -14,6 +14,7 @@ import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { OpenInMenu } from '@renderer/lib/components/titlebar/open-in-menu';
import { Titlebar } from '@renderer/lib/components/titlebar/Titlebar';
import { TitlebarBreadcrumb } from '@renderer/lib/components/titlebar/titlebar-breadcrumb';
+import { resetAgentErrorText } from '@renderer/lib/errors/reset-agent-error';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
@@ -137,8 +138,9 @@ const AgentActionsMenu = observer(function AgentActionsMenu({
void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {
loading: `Resetting ${label}…`,
success: `${label} was reset`,
- error: (error) =>
- `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,
+ error: (error) => {
+ return resetAgentErrorText(error);
+ },
});
},
})
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
index 58024a795..abe4197e0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-page-header.tsx
@@ -3,6 +3,7 @@ import { observer } from 'mobx-react-lite';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIconPicker } from '@renderer/lib/components/agent-icon-picker';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useParams } from '@renderer/lib/layout/navigation-provider';
@@ -55,9 +56,10 @@ export const AgentPageHeader = observer(function AgentPageHeader() {
await rpc.switchServers.updateAgentIcon({ serverId, agentId: switchAgentId, iconUrl });
await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });
} catch (cause) {
+ const { headline, detail } = describeFailure(cause, "Could not change the agent's icon.");
toast({
- title: "Could not change the agent's icon",
- description: cause instanceof Error ? cause.message : String(cause),
+ title: headline,
+ description: detail ?? undefined,
variant: 'destructive',
});
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
index e80e56300..bf7ccd733 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section.tsx
@@ -7,6 +7,7 @@ import {
policyHasDeadRule,
} from '@renderer/features/switch-servers/addressing-policy-editor';
import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { log } from '@renderer/utils/logger';
@@ -115,7 +116,7 @@ function AddressingPolicyRow({
setError(null);
},
onError: (err) => {
- setError(err instanceof Error ? err.message : 'Failed to save policy');
+ setError(failureText(err, 'Could not save the addressing policy.'));
log.error('Failed to update addressing policy', { agentId, error: err });
},
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
index 263319926..c010b76ef 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
@@ -18,6 +18,7 @@ import {
} from '@renderer/features/locations/components/agent-model-catalogue';
import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';
import { isProvisioned } from '@renderer/features/sessions/stores/session-store';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { Button } from '@renderer/lib/ui/button';
@@ -125,9 +126,10 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti
},
onError: (error) => {
log.error('Failed to save agent advanced configuration', { agentId, error });
+ const { headline, detail } = describeFailure(error, 'Could not save the configuration.');
toast({
- title: 'Failed to save configuration',
- description: String(error),
+ title: headline,
+ description: detail ?? undefined,
variant: 'destructive',
});
// A save can fail after the row was written — pushing the change to a
@@ -173,9 +175,10 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti
agentId,
error,
});
+ const { headline, detail } = describeFailure(error, 'Could not restart the session.');
toast({
- title: 'Failed to restart the session',
- description: String(error),
+ title: headline,
+ description: detail ?? undefined,
variant: 'destructive',
});
},
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx
index 3aa021ab1..bc53689f0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/hooks/use-confirm-delete-agent.tsx
@@ -1,5 +1,6 @@
import { useQueryClient } from '@tanstack/react-query';
import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
@@ -50,9 +51,10 @@ export function useConfirmDeleteAgent() {
onDeleted?.();
} catch (error) {
log.error('Failed to remove agent', { agentId: resolvedAgentId, error });
+ const { headline, detail } = describeFailure(error, 'Could not remove the agent.');
toast({
- title: 'Failed to remove agent',
- description: error instanceof Error ? error.message : String(error),
+ title: headline,
+ description: detail ?? undefined,
variant: 'destructive',
});
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
index a368e8bce..37be9b07f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/stores/location-manager.ts
@@ -1,5 +1,6 @@
import { err, ok } from '@switch-console/shared';
import { makeObservable, observable, runInAction } from 'mobx';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
import { viewStateCache } from '@renderer/lib/stores/view-state-cache';
@@ -262,7 +263,7 @@ export class LocationManagerStore {
const current = this.locations.get(locationId);
if (current && isUnmountedLocation(current)) {
current.phase = 'error';
- current.error = error instanceof Error ? error.message : String(error);
+ current.error = failureText(error, 'Could not open this location.');
current.errorCode = undefined;
}
});
@@ -378,7 +379,7 @@ export class LocationManagerStore {
const store = this.locations.get(id);
if (store && isUnregisteredLocation(store)) {
store.phase = 'error';
- store.error = error instanceof Error ? error.message : String(error);
+ store.error = failureText(error, 'Could not add this location.');
}
});
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/add-host-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/add-host-modal.tsx
index f42320623..52cbf54f0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/add-host-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/add-host-modal.tsx
@@ -10,6 +10,7 @@
import { useMutation, useQuery } from '@tanstack/react-query';
import { Plus } from 'lucide-react';
import { useMemo, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
@@ -142,7 +143,9 @@ export function AddHostModal({ onboarded, onAdded, onClose }: AddHostModalProps)
</Field>
{mutation.isError && (
- <p className="text-destructive text-xs">{(mutation.error as Error).message}</p>
+ <p className="text-destructive text-xs">
+ {failureText(mutation.error, 'Could not add the host.')}
+ </p>
)}
</FieldGroup>
</DialogContentArea>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
index dc54a5b61..6b316f2c4 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
@@ -23,6 +23,7 @@ import { observer } from 'mobx-react-lite';
import { useEffect, useMemo, useState } from 'react';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
import { PageHeader } from '@renderer/lib/components/page-header';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { Button } from '@renderer/lib/ui/button';
@@ -190,22 +191,22 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
*/}
{installStep.isError && (
<p className="text-destructive text-xs">
- Could not install: {(installStep.error as Error).message}
+ {failureText(installStep.error, 'Could not install.')}
</p>
)}
{updateStep.isError && (
<p className="text-destructive text-xs">
- Could not update: {(updateStep.error as Error).message}
+ {failureText(updateStep.error, 'Could not update.')}
</p>
)}
{recheck.isError && (
<p className="text-destructive text-xs">
- Could not check this host: {(recheck.error as Error).message}
+ {failureText(recheck.error, 'Could not check this host.')}
</p>
)}
{prepare.isError && (
<p className="text-destructive text-xs">
- Could not work out what this host needs: {(prepare.error as Error).message}
+ {failureText(prepare.error, 'Could not work out what this host needs.')}
</p>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/rename-session-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/sessions/rename-session-modal.tsx
index 5a80b12e6..ee7a91dc1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/rename-session-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/rename-session-modal.tsx
@@ -2,6 +2,7 @@ import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
import { useSessionSettings } from '@renderer/features/sessions/hooks/useSessionSettings';
import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
@@ -88,7 +89,7 @@ export const RenameSessionModal = observer(function RenameSessionModal({
}
onSuccess();
} catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to rename session');
+ setError(failureText(e, 'Could not rename the session.'));
setIsSubmitting(false);
}
}, [isValid, sessionManager, sessionId, normalizedName, onSuccess]);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts
index f024d2172..40c1b6fba 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts
@@ -2,6 +2,7 @@ import { makeObservable, observable, runInAction, toJS } from 'mobx';
import { toast } from 'sonner';
import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
import type { LocationSettingsStore } from '@renderer/features/locations/stores/location-settings-store';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import {
@@ -233,7 +234,7 @@ export class SessionManagerStore {
const result = await rpc.sessions
.createSession(JSON.parse(JSON.stringify(toJS(params))) as typeof params)
.catch((e: unknown) => {
- const message = e instanceof Error ? e.message : String(e);
+ const message = failureText(e, 'Could not create the session.');
clearOptimisticInitialWorking();
runInAction(() => {
const current = this.sessions.get(params.id);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
index 1ee67530f..da42d7ea1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
@@ -14,6 +14,7 @@ import {
} from '@renderer/features/sessions/stores/session-selectors';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { resetAgentErrorText } from '@renderer/lib/errors/reset-agent-error';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
@@ -233,8 +234,9 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {
loading: `Resetting ${label}…`,
success: `${label} was reset`,
- error: (error) =>
- `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,
+ error: (error) => {
+ return resetAgentErrorText(error);
+ },
});
},
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
index 416f6bd00..88f685605 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -5,6 +5,7 @@ import { HostTroubleIndicator } from '@renderer/features/remote-hosts/host-troub
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
@@ -88,8 +89,7 @@ export const RoomAgentRow = observer(function RoomAgentRow({
{
loading: `Removing ${label} from ${roomLabel}…`,
success: `${label} was removed from ${roomLabel}`,
- error: (error) =>
- `Failed to remove from room: ${error instanceof Error ? error.message : String(error)}`,
+ error: (error) => failureText(error, `Could not remove ${label} from ${roomLabel}.`),
}
);
};
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
index 1e5154cd7..af6a21d01 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
@@ -4,6 +4,7 @@ import { useCallback, useState } from 'react';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
@@ -101,7 +102,7 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
await switchRoomsStore.refreshRoomState();
onSuccess();
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not add the agent to the selected rooms.'));
} finally {
setIsSubmitting(false);
setCloseGuard(false);
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 0a16d7e48..1fb1a0ed6 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
@@ -5,6 +5,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
@@ -88,7 +89,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
await switchRoomsStore.refreshRoomState();
onSuccess();
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not add the agents to this room.'));
} finally {
setIsSubmitting(false);
setCloseGuard(false);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx
index cc11e5e75..2e45b88da 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/DeleteRoomModal.tsx
@@ -3,6 +3,7 @@ import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
@@ -49,7 +50,7 @@ export const DeleteRoomModal = observer(function DeleteRoomModal({
await switchRoomsStore.deleteRoom(serverId, roomId);
onSuccess();
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not delete the room.'));
setIsDeleting(false);
} finally {
setCloseGuard(false);
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 76fab8ccd..aeb5be6ce 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
@@ -6,6 +6,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { describeFailure, failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
@@ -68,10 +69,14 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
}
if (query.isError) {
+ const settingsReadFailure = describeFailure(
+ query.error,
+ 'Could not read this room’s settings.'
+ );
return (
<PanelNotice
- title="Couldn’t read this room’s settings"
- detail={errorText(query.error)}
+ title={settingsReadFailure.headline}
+ detail={settingsReadFailure.detail ?? undefined}
action={
<Button variant="outline" size="sm" onClick={() => void query.refetch()}>
<RefreshCw className="size-3" />
@@ -214,7 +219,7 @@ function GeneralSection({ serverId, room }: { serverId: string; room: RemoteRoom
queryClient.setQueryData(roomDetailKey(serverId, room.id), updated);
setState({ phase: 'saved' });
} catch (cause) {
- setState({ phase: 'failed', message: errorText(cause) });
+ setState({ phase: 'failed', message: failureText(cause, 'Could not save the change.') });
}
}
@@ -438,7 +443,7 @@ const AddAgentPanel = observer(function AddAgentPanel({
});
await onAdded();
} catch (cause) {
- setError(errorText(cause));
+ setError(failureText(cause, 'Could not add the agent to this room.'));
} finally {
setBusyId(null);
}
@@ -589,7 +594,3 @@ function agentKindFor(
const knownType = remoteById.get(switchAgentId)?.knownAgentType ?? null;
return providerDisplayName(providerId) ?? providerDisplayName(knownType) ?? 'agent';
}
-
-function errorText(cause: unknown): string {
- return cause instanceof Error ? cause.message : String(cause);
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx
index 4e9ad9554..bb989ae7c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-embed-layer.tsx
@@ -2,6 +2,7 @@ import { ExternalLink, Loader2, MessagesSquare, RefreshCw } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useEffect, useRef, useState } from 'react';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { useTheme } from '@renderer/lib/hooks/useTheme';
import { rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
@@ -100,7 +101,10 @@ export const RoomEmbedLayer = observer(function RoomEmbedLayer() {
setStates((prev) =>
new Map(prev).set(roomId, {
phase: 'error',
- message: cause instanceof Error ? cause.message : String(cause),
+ message: failureText(
+ cause,
+ 'Could not show this room inside Switch Console. Open it in the messaging app instead.'
+ ),
})
);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.test.ts
index da526dd41..4051ebca9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.test.ts
@@ -32,7 +32,13 @@ describe('session → room connections', () => {
const store = new SwitchRoomsStore();
store.ensureLoaded();
- await vi.waitFor(() => expect(store.seedError).toBe('ipc down'));
+ // The banner says what could not be read; the raw reason is kept with it
+ // rather than being the whole message.
+ await vi.waitFor(() =>
+ expect(store.seedError).toBe(
+ 'Could not read which Switch rooms these sessions are connected to. (ipc down)'
+ )
+ );
getConnections.mockResolvedValue([{ sessionId: 'sess-2', roomId: 'room-b' }]);
store.ensureLoaded();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts
index 83f36fd05..e0b7b698c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts
@@ -1,4 +1,5 @@
import { makeAutoObservable, runInAction } from 'mobx';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import { sessionRoomChangedChannel } from '@shared/core/switch-rooms/switchRoomEvents';
@@ -51,7 +52,10 @@ export class SwitchRoomsStore {
.catch((cause: unknown) => {
runInAction(() => {
this.loaded = false;
- this.seedError = cause instanceof Error ? cause.message : String(cause);
+ this.seedError = failureText(
+ cause,
+ 'Could not read which Switch rooms these sessions are connected to.'
+ );
});
});
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
index ffe81bb5c..bd873ac5e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
@@ -351,8 +351,8 @@ const LocalSetupStep = observer(function LocalSetupStep({
{store.error && !dockerUnavailable && !running && (
<Alert variant="destructive">
- <AlertTitle>Setup failed</AlertTitle>
- <AlertDescription>{store.error}</AlertDescription>
+ <AlertTitle>{store.error}</AlertTitle>
+ {store.errorDetail && <AlertDescription>{store.errorDetail}</AlertDescription>}
</Alert>
)}
@@ -584,8 +584,8 @@ const RemoteHostSetupStep = observer(function RemoteHostSetupStep({
{store.error && !dockerUnavailable && !running && (
<Alert variant="destructive">
- <AlertTitle>Setup failed</AlertTitle>
- <AlertDescription>{store.error}</AlertDescription>
+ <AlertTitle>{store.error}</AlertTitle>
+ {store.errorDetail && <AlertDescription>{store.errorDetail}</AlertDescription>}
</Alert>
)}
@@ -696,7 +696,7 @@ const ExternalServerStep = observer(function ExternalServerStep({
trimmedApi
);
if (!result) {
- setError(switchServersStore.error ?? 'Could not save the server.');
+ setError(switchServersStore.errorText ?? 'Could not save the server.');
setSubmitting(false);
return;
}
@@ -708,7 +708,7 @@ const ExternalServerStep = observer(function ExternalServerStep({
} else {
const saved = await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);
if (!saved) {
- setError(switchServersStore.error ?? 'Could not add the server.');
+ setError(switchServersStore.errorText ?? 'Could not add the server.');
setSubmitting(false);
return;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsx
index bb76cf125..ddc4f6314 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/BundledChatSignIn.tsx
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
import { Check, Copy, ExternalLink, Eye, EyeOff, KeyRound } from 'lucide-react';
import { useCallback, useState } from 'react';
import { BridgeIcon } from '@renderer/lib/components/bridge-icon';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { openExternalUrl } from '@renderer/lib/open-external';
import { Button } from '@renderer/lib/ui/button';
@@ -156,10 +157,7 @@ export function BundledChatSignIn({
<Spinner className="size-3.5" />
) : signInQuery.isError ? (
<p className="text-destructive text-xs">
- Could not read the sign-in details:{' '}
- {signInQuery.error instanceof Error
- ? signInQuery.error.message
- : String(signInQuery.error)}
+ {failureText(signInQuery.error, 'Could not read the sign-in details.')}
</p>
) : signIn?.kind === 'unavailable' ? (
<p className="text-xs text-foreground-muted">{signIn.reason}</p>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
index a523fa703..e879cdf4e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx
@@ -4,6 +4,7 @@ import { observer } from 'mobx-react-lite';
import { useCallback, useMemo, useState } from 'react';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel, bridgeSetupDocsUrl } from '@renderer/lib/components/bridge-platform';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { openExternalUrl } from '@renderer/lib/open-external';
@@ -135,7 +136,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
directorySearchSupported: selectedType.directorySearchSupported,
});
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not connect the messaging app.'));
} finally {
setIsSubmitting(false);
setCloseGuard(false);
@@ -198,7 +199,7 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
</Select>
{typesQuery.isError && (
<p className="text-destructive mt-1 text-xs">
- Could not load the available messaging apps: {errorText(typesQuery.error)}
+ {failureText(typesQuery.error, 'Could not load the available messaging apps.')}
</p>
)}
</Field>
@@ -319,10 +320,6 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod
);
});
-function errorText(cause: unknown): string {
- return cause instanceof Error ? cause.message : String(cause);
-}
-
/** Turn a failed attach into something the user can act on. */
function messageFor(result: Exclude<CreateBridgeResult, { kind: 'created' }>): string {
switch (result.kind) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
index 7d59d4358..5b11aad50 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
@@ -9,6 +9,7 @@ import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { sidebarStore } from '@renderer/lib/stores/app-state';
@@ -162,7 +163,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
onSuccess({ roomId: result.room.id });
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not create the room.'));
} finally {
setIsSubmitting(false);
setCloseGuard(false);
@@ -241,7 +242,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
)}
{bridgesQuery.isError && (
<p className="text-destructive text-xs">
- Could not load messaging apps: {errorText(bridgesQuery.error)}
+ {failureText(bridgesQuery.error, 'Could not load messaging apps.')}
</p>
)}
</section>
@@ -514,17 +515,13 @@ function handleOf(identity: LinkedIdentity): string {
return username.startsWith('@') ? username : `@${username}`;
}
-function errorText(cause: unknown): string {
- return cause instanceof Error ? cause.message : String(cause);
-}
-
/** Turn a failed create into something the user can act on. */
function messageFor(result: { kind: string; message?: string }): string {
switch (result.kind) {
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
case 'bridge-unavailable':
- return `The messaging app is not available: ${result.message ?? 'unknown reason'}`;
+ return result.message ?? 'The messaging app is not available.';
default:
return result.message ?? 'Could not create the room.';
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsx
index f532e56c6..893a93fc1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DeleteServerModal.tsx
@@ -58,7 +58,7 @@ export const DeleteServerModal = observer(function DeleteServerModal({
if (ok) {
onSuccess();
} else {
- setError(switchServersStore.error ?? 'Failed to delete server.');
+ setError(switchServersStore.errorText ?? 'Could not delete the server.');
setIsDeleting(false);
}
}, [server, typeConfirmed, serverId, onSuccess]);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
index 46cef34e4..bd431f6f9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/DisconnectMessagingAppModal.tsx
@@ -1,6 +1,7 @@
import { TriangleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
@@ -56,13 +57,13 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessaging
try {
const result = await rpc.switchServers.deleteBridge({ serverId, bridgeId });
if (result.kind !== 'deleted') {
- setError(failureText(result));
+ setError(messageFor(result));
setIsDeleting(false);
return;
}
onSuccess();
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not disconnect the messaging app.'));
setIsDeleting(false);
}
}, [typeConfirmed, serverId, bridgeId, onSuccess]);
@@ -124,7 +125,7 @@ export const DisconnectMessagingAppModal = observer(function DisconnectMessaging
});
/** Turn a refused disconnect into something the user can act on. */
-function failureText(result: Exclude<DeleteBridgeResult, { kind: 'deleted' }>): string {
+function messageFor(result: Exclude<DeleteBridgeResult, { kind: 'deleted' }>): string {
switch (result.kind) {
case 'unauthenticated':
return 'Your session for this server expired. Sign in again, then retry.';
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx
index 2a7526330..44cf62f54 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx
@@ -94,8 +94,8 @@ export const LocalServerControls = observer(function LocalServerControls() {
{store.error && !dockerUnavailable && (
<Alert variant="destructive">
- <AlertTitle>Something went wrong</AlertTitle>
- <AlertDescription>{store.error}</AlertDescription>
+ <AlertTitle>{store.error}</AlertTitle>
+ {store.errorDetail && <AlertDescription>{store.errorDetail}</AlertDescription>}
</Alert>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
index 4d5cad1c7..cfefc480e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/MessagingAppsCard.tsx
@@ -15,6 +15,7 @@ import { observer } from 'mobx-react-lite';
import { useEffect, useMemo, useState } from 'react';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
@@ -164,9 +165,7 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
}
await queryClient.invalidateQueries({ queryKey: ['remote-bridges', serverId] });
} catch (cause) {
- setToggleError(
- `Could not update ${bridge.displayName}: ${cause instanceof Error ? cause.message : String(cause)}`
- );
+ setToggleError(failureText(cause, `Could not update ${bridge.displayName}.`));
} finally {
setSavingBridgeId(null);
}
@@ -256,17 +255,19 @@ export const MessagingAppsCard = observer(function MessagingAppsCard({
{identitiesError !== null && (
<p className="text-destructive mt-2 text-xs">
- Could not load your linked accounts:{' '}
- {identitiesError instanceof Error ? identitiesError.message : String(identitiesError)}
+ {failureText(
+ identitiesError,
+ 'Could not load which messaging accounts are linked to you, so this list may be incomplete.'
+ )}
</p>
)}
{bridgesQuery.isError ? (
<p className="text-destructive mt-3 text-xs">
- Could not load messaging apps:{' '}
- {bridgesQuery.error instanceof Error
- ? bridgesQuery.error.message
- : String(bridgesQuery.error)}
+ {failureText(
+ bridgesQuery.error,
+ 'Could not load this server’s messaging apps. Re-check the server, or reload the page.'
+ )}
</p>
) : bridges.length === 0 && !bridgesQuery.isLoading ? (
<p className="mt-3 text-xs text-foreground-muted">
@@ -373,7 +374,7 @@ export function MessagingAppRow({
});
onReleased();
} catch (cause) {
- setReleaseError(cause instanceof Error ? cause.message : String(cause));
+ setReleaseError(failureText(cause, 'Could not unlink this account.'));
} finally {
setReleasing(false);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
index 8a40d8c70..47e7a340c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
@@ -110,8 +110,8 @@ export const RemoteServerControls = observer(function RemoteServerControls({
{store.error && !dockerUnavailable && (
<Alert variant="destructive">
- <AlertTitle>Something went wrong</AlertTitle>
- <AlertDescription>{store.error}</AlertDescription>
+ <AlertTitle>{store.error}</AlertTitle>
+ {store.errorDetail && <AlertDescription>{store.errorDetail}</AlertDescription>}
</Alert>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RenameServerModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RenameServerModal.tsx
index e757a5f6a..8310724be 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RenameServerModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RenameServerModal.tsx
@@ -43,7 +43,7 @@ export const RenameServerModal = observer(function RenameServerModal({
if (ok) {
onSuccess();
} else {
- setError(switchServersStore.error ?? 'Failed to rename server.');
+ setError(switchServersStore.errorText ?? 'Could not rename the server.');
setIsSubmitting(false);
}
}, [isValid, serverId, trimmed, onSuccess]);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
index bfd2be4a7..82521709e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/bridge-identity-search.tsx
@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { CircleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { useDebounce } from '@renderer/lib/hooks/useDebounce';
import { rpc } from '@renderer/lib/ipc';
import { useModalContext } from '@renderer/lib/modal/modal-provider';
@@ -94,7 +95,7 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
refreshIdentities();
onClaimed(result.identity);
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not link this account.'));
} finally {
setClaiming(null);
setCloseGuard(false);
@@ -119,7 +120,7 @@ export const BridgeIdentitySearch = observer(function BridgeIdentitySearch({
refreshIdentities();
await queryClient.invalidateQueries({ queryKey: ['bridge-directory', serverId, bridgeId] });
} catch (cause) {
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(failureText(cause, 'Could not unlink this account.'));
} finally {
setReleasing(null);
setCloseGuard(false);
@@ -209,8 +210,7 @@ function DirectoryResults({
if (fetchError) {
return (
<p className="text-destructive text-xs">
- Could not search the directory:{' '}
- {fetchError instanceof Error ? fetchError.message : String(fetchError)}
+ {failureText(fetchError, 'Could not search the directory.')}
</p>
);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
index 5c72b98a5..cd328f741 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/link-accounts-step.tsx
@@ -4,6 +4,7 @@ import { observer } from 'mobx-react-lite';
import { useState } from 'react';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
@@ -134,8 +135,7 @@ function BridgeList({
return (
<div className="flex flex-col items-start gap-3">
<p className="text-destructive text-sm">
- Could not read this server’s messaging apps:{' '}
- {error instanceof Error ? error.message : String(error)}
+ {failureText(error, 'Could not read this server’s messaging apps.')}
</p>
<Button variant="outline" size="sm" onClick={onRetry}>
Retry
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts
index 7fafd8945..ab0fb2a4c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts
@@ -1,5 +1,6 @@
import { makeAutoObservable, runInAction } from 'mobx';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import type {
DockerAvailability,
@@ -39,7 +40,10 @@ export class LocalServerStore {
docker: DockerAvailability | null = null;
/** True while a start/stop/reset RPC is in flight. */
busy = false;
+ /** The sentence the page leads with. Never raw exception text. */
error: string | null = null;
+ /** Diagnostics for the same failure, rendered under `error` rather than in it. */
+ errorDetail: string | null = null;
/** Live `docker compose` output tail during a start. */
logs: string[] = [];
@@ -54,6 +58,12 @@ export class LocalServerStore {
makeAutoObservable(this, { pendingLines: false, flushTimer: false });
}
+ /** Headline and detail as one string, for the modals that have a single slot. */
+ get errorText(): string | null {
+ if (!this.error) return null;
+ return this.errorDetail ? `${this.error} (${this.errorDetail})` : this.error;
+ }
+
get phase(): LocalServerStatus['phase'] {
return this.status?.phase ?? 'stopped';
}
@@ -92,7 +102,7 @@ export class LocalServerStore {
this.status = status;
});
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not read the server status.');
}
}
@@ -136,7 +146,7 @@ export class LocalServerStore {
this.docker = docker;
});
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not check Docker availability.');
}
}
@@ -149,6 +159,7 @@ export class LocalServerStore {
runInAction(() => {
this.busy = true;
this.error = null;
+ this.errorDetail = null;
this.logs = [];
});
try {
@@ -170,7 +181,7 @@ export class LocalServerStore {
await switchServersStore.init();
}
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not start the server.');
} finally {
// The command has finished, so nothing more will arrive to trigger a
// flush — the tail's last lines are the ones that say how it went.
@@ -185,11 +196,12 @@ export class LocalServerStore {
runInAction(() => {
this.busy = true;
this.error = null;
+ this.errorDetail = null;
});
try {
await rpc.localSwitchServer.stop();
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not stop the server.');
} finally {
runInAction(() => {
this.busy = false;
@@ -201,6 +213,7 @@ export class LocalServerStore {
runInAction(() => {
this.busy = true;
this.error = null;
+ this.errorDetail = null;
});
try {
// The reset deletes the stack's agents itself — their server-side
@@ -210,7 +223,7 @@ export class LocalServerStore {
await agentsStore.load();
await switchServersStore.init();
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not reset the server.');
} finally {
runInAction(() => {
this.busy = false;
@@ -218,9 +231,17 @@ export class LocalServerStore {
}
}
- private setError(cause: unknown): void {
+ /**
+ * `error` is rendered directly in banners, so it goes through the shared
+ * boundary rather than carrying whatever was thrown. The fallback is
+ * per-action: the store knows which request failed, and the failure itself
+ * usually does not.
+ */
+ private setError(cause: unknown, fallback: string): void {
+ const { headline, detail } = describeFailure(cause, fallback);
runInAction(() => {
- this.error = cause instanceof Error ? cause.message : String(cause);
+ this.error = headline;
+ this.errorDetail = detail;
});
}
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts
index e4960d27e..d066f7adc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts
@@ -1,6 +1,7 @@
import { makeAutoObservable, runInAction } from 'mobx';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import type {
DockerAvailability,
@@ -43,7 +44,10 @@ export class RemoteServerStore {
private readonly logsByHost = new Map<string, string[]>();
private readonly dockerByHost = new Map<string, DockerAvailability>();
private readonly busyHosts = new Set<string>();
+ /** The sentence the page leads with. Never raw exception text. */
error: string | null = null;
+ /** Diagnostics for the same failure, rendered under `error` rather than in it. */
+ errorDetail: string | null = null;
private off: (() => void) | null = null;
private offLog: (() => void) | null = null;
@@ -55,6 +59,12 @@ export class RemoteServerStore {
makeAutoObservable(this, { pendingByHost: false, flushTimer: false });
}
+ /** Headline and detail as one string, for the modals that have a single slot. */
+ get errorText(): string | null {
+ if (!this.error) return null;
+ return this.errorDetail ? `${this.error} (${this.errorDetail})` : this.error;
+ }
+
private queueLine(sshHost: string, line: string): void {
const pending = this.pendingByHost.get(sshHost) ?? [];
pending.push(line);
@@ -140,7 +150,7 @@ export class RemoteServerStore {
for (const status of statuses) this.statuses.set(status.sshHost, status);
});
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not read the server statuses.');
}
}
@@ -160,7 +170,7 @@ export class RemoteServerStore {
const docker = await rpc.remoteSwitchServer.detectDocker(sshHost);
runInAction(() => this.dockerByHost.set(sshHost, docker));
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not check Docker availability.');
}
}
@@ -168,6 +178,7 @@ export class RemoteServerStore {
runInAction(() => {
this.busyHosts.add(sshHost);
this.error = null;
+ this.errorDetail = null;
this.logsByHost.set(sshHost, []);
});
try {
@@ -193,7 +204,7 @@ export class RemoteServerStore {
await switchServersStore.init();
}
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not start the server.');
} finally {
runInAction(() => this.busyHosts.delete(sshHost));
}
@@ -203,11 +214,12 @@ export class RemoteServerStore {
runInAction(() => {
this.busyHosts.add(sshHost);
this.error = null;
+ this.errorDetail = null;
});
try {
await rpc.remoteSwitchServer.stop(sshHost);
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not stop the server.');
} finally {
runInAction(() => this.busyHosts.delete(sshHost));
}
@@ -217,6 +229,7 @@ export class RemoteServerStore {
runInAction(() => {
this.busyHosts.add(sshHost);
this.error = null;
+ this.errorDetail = null;
});
try {
// The reset deletes the stack's agents itself — their server-side
@@ -226,15 +239,23 @@ export class RemoteServerStore {
await agentsStore.load();
await switchServersStore.init();
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not reset the server.');
} finally {
runInAction(() => this.busyHosts.delete(sshHost));
}
}
- private setError(cause: unknown): void {
+ /**
+ * `error` is rendered directly in banners, so it goes through the shared
+ * boundary rather than carrying whatever was thrown. The fallback is
+ * per-action: the store knows which request failed, and the failure itself
+ * usually does not.
+ */
+ private setError(cause: unknown, fallback: string): void {
+ const { headline, detail } = describeFailure(cause, fallback);
runInAction(() => {
- this.error = cause instanceof Error ? cause.message : String(cause);
+ this.error = headline;
+ this.errorDetail = detail;
});
}
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
index 5c78f6ae8..6680b64e0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
@@ -7,6 +7,7 @@ import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { getLocationStore } from '@renderer/features/locations/stores/location-selectors';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+import { resetAgentErrorText } from '@renderer/lib/errors/reset-agent-error';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
@@ -157,8 +158,9 @@ const AgentCard = observer(function AgentCard({
void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {
loading: `Resetting ${label}…`,
success: `${label} was reset`,
- error: (error) =>
- `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,
+ error: (error) => {
+ return resetAgentErrorText(error);
+ },
});
},
})
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx
index d15ad1384..41dc531f4 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-sign-in.tsx
@@ -47,7 +47,7 @@ export function useServerSignIn(serverId: string): ServerSignIn {
setError(null);
try {
const ok = await run();
- if (!ok) setError(switchServersStore.error ?? 'Could not sign in.');
+ if (!ok) setError(switchServersStore.errorText ?? 'Could not sign in.');
return ok;
} finally {
setSubmitting(false);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
index 5ea29536a..eb2e1fcbb 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
@@ -374,7 +374,9 @@ describe('agent memberships', () => {
]);
expect(store.roomsFor('srv-a', 'agent-1')).toBeUndefined();
- expect(store.errorFor('srv-a', 'agent-1')).toBe('nope');
+ expect(store.errorFor('srv-a', 'agent-1')).toBe(
+ 'Could not load the rooms this agent belongs to. (nope)'
+ );
expect(store.roomsFor('srv-a', 'agent-2')?.[0].roomId).toBe('room-b');
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
index ec61244d2..345702c77 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
@@ -1,4 +1,5 @@
import { makeAutoObservable, runInAction } from 'mobx';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import type {
RemoteAgentRoom,
@@ -306,7 +307,7 @@ export class SwitchRoomsStore {
runInAction(() => {
this.roomListErrors.set(
server.id,
- cause instanceof Error ? cause.message : String(cause)
+ failureText(cause, `Could not load the rooms on ${server.name}.`)
);
});
}
@@ -479,7 +480,7 @@ export class SwitchRoomsStore {
return rooms;
} catch (cause) {
runInAction(() => {
- this.errors.set(k, cause instanceof Error ? cause.message : String(cause));
+ this.errors.set(k, failureText(cause, 'Could not load the rooms this agent belongs to.'));
});
return null;
} finally {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
index 9bdfe810a..3fbdae62f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
@@ -1,5 +1,6 @@
import { makeAutoObservable, runInAction } from 'mobx';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import type {
ServerConnectionStatus,
@@ -39,12 +40,21 @@ export class SwitchServersStore {
loadingServers = false;
/** Server ids with an in-flight status refresh. */
readonly refreshing = new Set<string>();
+ /** The sentence the page leads with. Never raw exception text. */
error: string | null = null;
+ /** Diagnostics for the same failure, rendered under `error` rather than in it. */
+ errorDetail: string | null = null;
constructor() {
makeAutoObservable(this);
}
+ /** Headline and detail as one string, for the modals that have a single slot. */
+ get errorText(): string | null {
+ if (!this.error) return null;
+ return this.errorDetail ? `${this.error} (${this.errorDetail})` : this.error;
+ }
+
/** Whether this server is managed on a host the reachability manager has
* marked unreachable — nothing it serves can be fetched until that clears. */
isHostBlocked(serverId: string): boolean {
@@ -78,6 +88,7 @@ export class SwitchServersStore {
runInAction(() => {
this.loadingServers = true;
this.error = null;
+ this.errorDetail = null;
});
try {
const [servers, activeServerId] = await Promise.all([
@@ -91,7 +102,7 @@ export class SwitchServersStore {
await this.ensureActiveServer();
await this.refreshAllStatuses();
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not load your Switch servers.');
} finally {
runInAction(() => {
this.loadingServers = false;
@@ -234,7 +245,7 @@ export class SwitchServersStore {
await this.refreshStatus(created.id);
return created;
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not add the server.');
return null;
}
}
@@ -254,7 +265,7 @@ export class SwitchServersStore {
});
return result;
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not save the server.');
return null;
}
}
@@ -269,7 +280,7 @@ export class SwitchServersStore {
});
return true;
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not rename the server.');
return false;
}
}
@@ -296,7 +307,7 @@ export class SwitchServersStore {
}
}
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not shut down the server’s stack, so it was not deleted.');
return false;
}
await this.removeServer(serverId);
@@ -321,7 +332,7 @@ export class SwitchServersStore {
});
await this.ensureActiveServer();
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not remove the server.');
}
}
@@ -333,7 +344,7 @@ export class SwitchServersStore {
this.activeServerId = serverId;
});
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not switch to that server.');
}
}
@@ -343,6 +354,7 @@ export class SwitchServersStore {
if (!result.success) {
runInAction(() => {
this.error = result.error.message;
+ this.errorDetail = null;
});
return false;
}
@@ -358,6 +370,7 @@ export class SwitchServersStore {
if (result.error.kind !== 'cancelled') {
runInAction(() => {
this.error = result.error.message;
+ this.errorDetail = null;
});
}
return false;
@@ -372,19 +385,28 @@ export class SwitchServersStore {
await rpc.switchServers.logout(serverId);
await this.refreshStatus(serverId);
} catch (cause) {
- this.setError(cause);
+ this.setError(cause, 'Could not sign out of the server.');
}
}
private clearError(): void {
runInAction(() => {
this.error = null;
+ this.errorDetail = null;
});
}
- private setError(cause: unknown): void {
+ /**
+ * `error` is rendered directly in banners and modals, so it goes through the
+ * shared boundary rather than carrying whatever was thrown. The fallback is
+ * per-action: the store knows which request failed, and the failure itself
+ * usually does not.
+ */
+ private setError(cause: unknown, fallback: string): void {
+ const { headline, detail } = describeFailure(cause, fallback);
runInAction(() => {
- this.error = cause instanceof Error ? cause.message : String(cause);
+ this.error = headline;
+ this.errorDetail = detail;
});
}
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
index 17f6adac0..bfd73fcab 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
@@ -260,8 +260,8 @@ const ServerMainPanel = observer(function ServerMainPanel() {
{store.error && (
<Alert variant="destructive">
- <AlertTitle>Something went wrong</AlertTitle>
- <AlertDescription>{store.error}</AlertDescription>
+ <AlertTitle>{store.error}</AlertTitle>
+ {store.errorDetail && <AlertDescription>{store.errorDetail}</AlertDescription>}
</Alert>
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.ts b/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.ts
index 3aa399b6a..9ce4b00aa 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/commands/app-commands.ts
@@ -72,11 +72,7 @@ function createAppCommandProvider(): CommandProvider {
execute() {
void toggleAppTheme().then((result) => {
if (result.success) return;
- toast({
- title: 'Theme not changed',
- description: result.error.message,
- variant: 'destructive',
- });
+ toast({ title: result.error.message, variant: 'destructive' });
});
},
});
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsx
index fd2b1009d..3d3df80a7 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/error-boundary.tsx
@@ -1,4 +1,5 @@
import React from 'react';
+import { log } from '@renderer/utils/logger';
import { rpc } from '../ipc';
import { Button } from '../ui/button';
@@ -11,12 +12,20 @@ type ErrorBoundaryProps = {
children?: React.ReactNode;
};
+/**
+ * The crash screen is the user's whole account of a failure that took the app
+ * with it, so the raw message stays — demoted out of the lead sentence, but
+ * present, and selectable so it can be pasted into a bug report.
+ */
function ErrorFallback({ message, onReload }: { message: string; onReload: () => void }) {
return (
<div className="flex h-screen w-screen items-center justify-center bg-background p-6">
<div className="bg-card text-card-foreground max-w-xl rounded-md border border-border p-6 shadow-sm">
- <h1 className="mb-2 text-lg font-semibold">Something went wrong</h1>
- <p className="text-muted-foreground mb-4 text-sm break-all">{message}</p>
+ <h1 className="mb-2 text-lg font-semibold">Switch Console hit an error and stopped</h1>
+ <p className="text-muted-foreground mb-4 text-sm">Reloading usually recovers it.</p>
+ <p className="text-muted-foreground mb-4 font-mono text-xs break-all select-text">
+ {message}
+ </p>
<Button variant="default" onClick={onReload}>
Reload
</Button>
@@ -26,15 +35,25 @@ function ErrorFallback({ message, onReload }: { message: string; onReload: () =>
}
export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
- constructor(props: ErrorBoundaryProps) {
- super(props);
- this.state = { hasError: false, error: null };
- }
+ state: ErrorBoundaryState = { hasError: false, error: null };
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
+ /**
+ * Without this the crash existed only on screen: React reports it to the
+ * console, which is not the file log, so the one failure most worth having a
+ * record of left none.
+ */
+ componentDidCatch(error: Error, info: React.ErrorInfo) {
+ log.error('Renderer crashed', {
+ event: 'renderer_crash',
+ error: { name: error.name, message: error.message, stack: error.stack },
+ componentStack: info.componentStack,
+ });
+ }
+
handleReload = () => {
void rpc.viewState.reset().finally(() => {
try {
@@ -45,7 +64,7 @@ export class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoun
render() {
if (!this.state.hasError) return this.props.children as React.ReactElement;
- const message = this.state.error?.message || 'An unexpected error occurred.';
+ const message = this.state.error?.message || 'No further detail was reported.';
return <ErrorFallback message={message} onReload={this.handleReload} />;
}
}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.test.ts
index 0c23ab19b..84e4e1b68 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.test.ts
@@ -220,12 +220,35 @@ describe('OpenInMenu', () => {
expect(mocks.updateOpenIn).toHaveBeenCalledWith({ default: 'cursor' });
expect(mocks.toast).toHaveBeenCalledWith({
- title: 'Open in Cursor failed',
+ title: 'Could not open this folder in Cursor',
description: 'Cursor is unavailable',
variant: 'destructive',
});
});
+ it('says what to check when the launch fails with no reason given', async () => {
+ mocks.openIn.mockResolvedValueOnce({ success: false });
+
+ await act(async () => {
+ root.render(React.createElement(OpenInMenu, { path: 'C:/repo' }));
+ });
+
+ await act(async () => {
+ container
+ .querySelector('[data-testid="open-in-option-cursor"]')!
+ .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ // "Application not available." named no application and suggested nothing.
+ expect(mocks.toast).toHaveBeenCalledWith({
+ title: 'Could not open this folder in Cursor',
+ description: 'Cursor may not be installed, or its command-line launcher may not be on PATH.',
+ variant: 'destructive',
+ });
+ });
+
it('disables unavailable dropdown apps after availability loads', async () => {
mocks.openInApps.availability = {
finder: true,
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.tsx
index 2f68721b2..118bf9299 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/titlebar/open-in-menu.tsx
@@ -2,6 +2,7 @@ import { useHotkey } from '@tanstack/react-hotkeys';
import { ChevronDown } from 'lucide-react';
import React, { useCallback, useMemo } from 'react';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { useToast } from '@renderer/lib/hooks/use-toast';
import {
getEffectiveHotkey,
@@ -57,17 +58,19 @@ export const OpenInMenu: React.FC<OpenInMenuProps> = ({
});
if (!res?.success) {
toast({
- title: `Open in ${label} failed`,
- description: res?.error || 'Application not available.',
+ title: `Could not open this folder in ${label}`,
+ description:
+ res?.error ||
+ `${label} may not be installed, or its command-line launcher may not be on PATH.`,
variant: 'destructive',
});
}
- } catch (e: unknown) {
- toast({
- title: `Open in ${label} failed`,
- description: e instanceof Error ? e.message : String(e),
- variant: 'destructive',
- });
+ } catch (cause: unknown) {
+ const { headline, detail } = describeFailure(
+ cause,
+ `Could not open this folder in ${label}.`
+ );
+ toast({ title: headline, description: detail ?? undefined, variant: 'destructive' });
}
},
[isRemote, labels, path, sshConnectionId, toast]
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts
new file mode 100644
index 000000000..de2ab368d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+import { RpcError } from '@shared/lib/ipc/rpc-error';
+import { describeFailure, failureText } from './describe-failure';
+
+function rpcError(code: string, message: string, data?: Record<string, unknown>): RpcError {
+ return new RpcError({
+ __switchConsoleRpcError: true,
+ code,
+ message,
+ data,
+ } as unknown as ConstructorParameters<typeof RpcError>[0]);
+}
+
+describe('describeFailure', () => {
+ it('leads with the caller sentence and demotes the raw error to detail', () => {
+ const result = describeFailure(
+ new Error('EACCES: permission denied, open ...'),
+ 'Could not save the agent’s settings.'
+ );
+ expect(result.headline).toBe('Could not save the agent’s settings.');
+ expect(result.detail).toBe('EACCES: permission denied, open ...');
+ });
+
+ it('never drops the detail — it moves it', () => {
+ const result = describeFailure(new Error('socket hang up'), 'Could not reset the agent.');
+ expect(result.detail).toContain('socket hang up');
+ });
+
+ it('says nothing more than the fallback when there is nothing more to say', () => {
+ expect(describeFailure(new Error(' '), 'Could not do the thing.')).toEqual({
+ headline: 'Could not do the thing.',
+ detail: null,
+ });
+ });
+
+ it('recognises an expired session and gives the action, not the status', () => {
+ const result = describeFailure(
+ rpcError('GatewayError', 'GET /rooms failed: 401', { kind: 'unauthorized', status: 401 }),
+ 'Could not load the rooms.'
+ );
+ expect(result.headline).toBe(
+ 'Your session for this server expired. Sign in again, then retry.'
+ );
+ expect(result.detail).toBeNull();
+ });
+
+ it('turns an unreachable gateway into something a user can check', () => {
+ const result = describeFailure(
+ rpcError('GatewayError', 'fetch failed', { kind: 'network' }),
+ 'Could not load the rooms.'
+ );
+ expect(result.headline).toMatch(/Could not reach the server/);
+ expect(result.detail).toBe('fetch failed');
+ });
+
+ it("prefers the gateway's own explanation when it reads as a sentence", () => {
+ const result = describeFailure(
+ rpcError('GatewayError', 'POST /rooms failed: 409', {
+ kind: 'http',
+ status: 409,
+ detail: 'A room with that name already exists on this server.',
+ }),
+ 'Could not create the room.'
+ );
+ expect(result.headline).toBe('A room with that name already exists on this server.');
+ expect(result.detail).toBe('HTTP 409');
+ });
+
+ it('does not promote a raw exception fragment into the headline', () => {
+ const result = describeFailure(
+ rpcError('GatewayError', 'boom', {
+ kind: 'http',
+ status: 500,
+ detail: 'TypeError: x is not a function',
+ }),
+ 'Could not create the room.'
+ );
+ expect(result.headline).toBe('Could not create the room.');
+ expect(result.detail).toContain('TypeError: x is not a function');
+ });
+
+ it('tells the user an auth-suspended host will not recover on its own', () => {
+ const result = describeFailure(
+ rpcError('HostUnreachableError', 'SSH authentication to box failed', {
+ reachability: {
+ sshHost: 'box',
+ status: 'suspended',
+ lastError: 'All configured authentication methods failed',
+ },
+ }),
+ 'Could not reach the host.'
+ );
+ expect(result.headline).toMatch(/will not keep retrying on its own/);
+ expect(result.headline).toContain('box');
+ expect(result.detail).toBe('All configured authentication methods failed');
+ });
+
+ it('tells the user an unreachable host is still being probed', () => {
+ const result = describeFailure(
+ rpcError('HostUnreachableError', 'Host box is unreachable', {
+ reachability: { sshHost: 'box', status: 'unreachable', lastError: 'ETIMEDOUT' },
+ }),
+ 'Could not reach the host.'
+ );
+ expect(result.headline).toMatch(/clears on its own/);
+ expect(result.headline).not.toMatch(/will not keep retrying/);
+ });
+
+ it('passes a modeled sentence straight through', () => {
+ const message =
+ "prod's Switch stack is not running. Start it from the server's page, then retry.";
+ expect(describeFailure(rpcError('ManagedServerStoppedError', message), 'fallback')).toEqual({
+ headline: message,
+ detail: null,
+ });
+ });
+});
+
+describe('failureText', () => {
+ it('parenthesises the detail for surfaces with one slot', () => {
+ expect(failureText(new Error('ECONNREFUSED'), 'Could not add the server.')).toBe(
+ 'Could not add the server. (ECONNREFUSED)'
+ );
+ });
+
+ it('omits the parenthetical when there is no detail', () => {
+ expect(failureText(new Error(''), 'Could not add the server.')).toBe(
+ 'Could not add the server.'
+ );
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.ts b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.ts
new file mode 100644
index 000000000..1cd536707
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/errors/describe-failure.ts
@@ -0,0 +1,106 @@
+import type { HostReachability } from '@shared/core/remote-hosts/reachability';
+import { RpcError } from '@shared/lib/ipc/rpc-error';
+
+/**
+ * Splitting a failure into the sentence a user reads and the detail they may
+ * need to hand to someone else.
+ *
+ * The pattern this replaces is
+ * `toast({ title: 'Failed to X', description: String(error) })` — the right
+ * shape filled in backwards, with a stub where the explanation belongs and a
+ * raw exception where the explanation was expected. `headline` is what the
+ * screen leads with; `detail` is the diagnostic, kept but demoted to the
+ * toast's description or an expandable block.
+ *
+ * Detail is never dropped. A failure the app cannot describe keeps its raw
+ * message under a caller-supplied headline, which is strictly more than the
+ * raw message alone told anyone.
+ */
+export type FailureDescription = {
+ /** Plain sentence. Never raw exception text. */
+ headline: string;
+ /** Diagnostic text, or null when the headline already says everything. */
+ detail: string | null;
+};
+
+/** Reads as a finished sentence rather than a fragment or a stack-ish blob. */
+function isSentence(text: string): boolean {
+ if (text.length < 12 || text.length > 300) return false;
+ if (text.includes('\n')) return false;
+ // `TypeError: fetch failed`, `Error: ENOENT ...` — a leading exception class.
+ if (/^[A-Z]\w*(Error|Exception):/.test(text)) return false;
+ return /^[A-Z]/.test(text) && /[.!?]$/.test(text);
+}
+
+function describeGatewayFailure(error: RpcError, fallback: string): FailureDescription {
+ const detail = error.stringField('detail') ?? error.message;
+ const status = error.numberField('status');
+
+ switch (error.stringField('kind')) {
+ case 'unauthorized':
+ // Matches the wording already used at the five places that handle a 401
+ // inline, so the same failure reads the same way wherever it surfaces.
+ return {
+ headline: 'Your session for this server expired. Sign in again, then retry.',
+ detail: null,
+ };
+ case 'network':
+ return {
+ headline:
+ 'Could not reach the server. Check that it is running and that you are on its network.',
+ detail,
+ };
+ default:
+ // The gateway's own `detail` is written for a person when it is present;
+ // `message` is the status line and is not.
+ return isSentence(detail)
+ ? { headline: detail, detail: status ? `HTTP ${status}` : null }
+ : { headline: fallback, detail: status ? `HTTP ${status}: ${detail}` : detail };
+ }
+}
+
+function describeHostUnreachable(error: RpcError, fallback: string): FailureDescription {
+ const reachability = error.data.reachability as HostReachability | undefined;
+ if (!reachability) return { headline: fallback, detail: error.message };
+
+ const host = reachability.sshHost;
+ // `suspended` is an authentication failure, and the reconnect loop does not
+ // run in that state — telling the user to wait for it would be telling them
+ // to wait for something that is not going to happen.
+ const headline =
+ reachability.status === 'suspended'
+ ? `Switch Console could not authenticate to ${host}. It will not keep retrying on its own — fix the host's SSH credentials, then retry.`
+ : `Switch Console cannot reach ${host} at the moment. It keeps probing in the background, so this clears on its own once the host answers.`;
+
+ return { headline, detail: reachability.lastError };
+}
+
+/**
+ * @param fallback The sentence to lead with when the failure is not one the app
+ * recognises. Write it for the action the user just took ("Could not save the
+ * agent's settings."), not for the layer that failed.
+ */
+export function describeFailure(error: unknown, fallback: string): FailureDescription {
+ if (error instanceof RpcError) {
+ switch (error.code) {
+ case 'GatewayError':
+ return describeGatewayFailure(error, fallback);
+ case 'HostUnreachableError':
+ return describeHostUnreachable(error, fallback);
+ case 'ManagedServerStoppedError':
+ // Already a modeled, actionable sentence naming the server and the page
+ // to fix it on.
+ return { headline: error.message, detail: null };
+ }
+ }
+
+ const raw = (error instanceof Error ? error.message : String(error)).trim();
+ if (!raw) return { headline: fallback, detail: null };
+ return { headline: fallback, detail: raw };
+}
+
+/** One string, for the surfaces that have nowhere to put the detail separately. */
+export function failureText(error: unknown, fallback: string): string {
+ const { headline, detail } = describeFailure(error, fallback);
+ return detail ? `${headline} (${detail})` : headline;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/errors/reset-agent-error.ts b/console/apps/switch-console-desktop/src/renderer/lib/errors/reset-agent-error.ts
new file mode 100644
index 000000000..a8d3fe9a1
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/errors/reset-agent-error.ts
@@ -0,0 +1,13 @@
+import { failureText } from './describe-failure';
+
+/**
+ * The same failure is offered from three menus — the agent's page header, the
+ * sidebar entry, and the Your Agents card — so the wording lives here rather
+ * than in three places that would drift apart.
+ *
+ * All three report it through a promise toast, which takes one string, so the
+ * detail rides in a parenthetical rather than a description slot.
+ */
+export function resetAgentErrorText(error: unknown): string {
+ return failureText(error, 'Could not reset the agent.');
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/hooks/useImportProgress.ts b/console/apps/switch-console-desktop/src/renderer/lib/hooks/useImportProgress.ts
index 3e43c2b28..5ef4e188e 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/hooks/useImportProgress.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/hooks/useImportProgress.ts
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
const PROGRESS_DURATION_MS = 4000;
const COMPLETE_DELAY_MS = 1000;
@@ -101,7 +102,7 @@ export function useImportProgress() {
maybeScheduleComplete(options.onComplete);
} catch (err) {
cancelAnimation();
- setError(err instanceof Error ? err.message : 'Import failed');
+ setError(failureText(err, 'The import did not finish.'));
setIsImporting(false);
setProgress(0);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/open-external.ts b/console/apps/switch-console-desktop/src/renderer/lib/open-external.ts
index 2ece27e30..a0973e645 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/open-external.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/open-external.ts
@@ -1,4 +1,5 @@
import { toast } from 'sonner';
+import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
/** What the main process reports back from an attempt to open something. */
@@ -31,9 +32,8 @@ export async function reportOpenAttempt(
if (result.success) return true;
toast.error(failureTitle, { description: result.error ?? failureDetail });
} catch (cause) {
- toast.error(failureTitle, {
- description: cause instanceof Error ? cause.message : String(cause),
- });
+ const { detail } = describeFailure(cause, failureTitle);
+ toast.error(failureTitle, { description: detail ?? failureDetail });
}
return false;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/resource.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/resource.ts
index 81c966132..c74b6c76f 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/resource.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/resource.ts
@@ -5,6 +5,7 @@ import {
onBecomeUnobserved,
runInAction,
} from 'mobx';
+import { failureText } from '@renderer/lib/errors/describe-failure';
export type ResourceStrategy<T, TEventData = void> =
| { kind: 'demand' }
@@ -143,7 +144,7 @@ export class Resource<T, TEventData = void> {
})
.catch((e: unknown) => {
runInAction(() => {
- this.error = e instanceof Error ? e.message : String(e);
+ this.error = failureText(e, 'Could not read this host’s resource usage.');
this.loading = this._reloadQueued;
});
})
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/theme/theme-toggle.ts b/console/apps/switch-console-desktop/src/renderer/lib/theme/theme-toggle.ts
index 167322ed8..bdb1fbc3b 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/theme/theme-toggle.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/theme/theme-toggle.ts
@@ -8,13 +8,14 @@ import {
setAppSettingsValueInCache,
updateAppSettingsRequest,
} from '@renderer/features/settings/app-settings-client';
+import { failureText } from '@renderer/lib/errors/describe-failure';
import type { Theme } from '@shared/core/app-settings';
import { getNextTheme } from './theme-toggle-model';
export type ToggleThemeError = { message: string };
function errorMessage(error: unknown): string {
- return error instanceof Error ? error.message : String(error);
+ return failureText(error, 'Could not change the theme.');
}
export async function toggleAppTheme(): Promise<Result<NonNullable<Theme>, ToggleThemeError>> {
diff --git a/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc-error.test.ts b/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc-error.test.ts
new file mode 100644
index 000000000..bfa0ec00d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc-error.test.ts
@@ -0,0 +1,165 @@
+import type { IpcMain } from 'electron';
+import { describe, expect, it } from 'vitest';
+import { createRPCClient, createRPCRouter, registerRPCRouter } from './rpc';
+import { RpcError } from './rpc-error';
+
+/**
+ * A stand-in for the Electron pair, wired the way the real one is: handlers go
+ * in through `ipcMain.handle`, calls come out through the client's `invoke`.
+ * What it deliberately does NOT do is reproduce Electron's rewriting of a
+ * rejected handler — the point of the boundary is that no rejection reaches it.
+ */
+function harness(router: Record<string, Record<string, unknown>>) {
+ const handlers = new Map<string, (...args: unknown[]) => unknown>();
+ const ipcMain = {
+ handle(channel: string, listener: (event: unknown, ...args: unknown[]) => unknown) {
+ handlers.set(channel, (...args: unknown[]) => listener(null, ...args));
+ },
+ } as unknown as IpcMain;
+
+ registerRPCRouter(router, ipcMain);
+
+ return {
+ handlers,
+ client: createRPCClient<typeof router>(async (channel: string, ...args: unknown[]) => {
+ const handler = handlers.get(channel);
+ if (!handler) throw new Error(`no handler for ${channel}`);
+ return await handler(...args);
+ }),
+ };
+}
+
+describe('RPC error boundary', () => {
+ it('resolves rather than rejects, so Electron never rewrites the message', async () => {
+ const { handlers } = harness(
+ createRPCRouter({
+ things: {
+ fail: () => {
+ throw new Error('the disk is full');
+ },
+ },
+ })
+ );
+
+ // Resolving is the whole mechanism: a rejected `ipcMain.handle` is what
+ // Electron prefixes with `Error invoking remote method '<channel>'`.
+ const settled = await handlers.get('things.fail')!();
+ expect(settled).toMatchObject({ message: 'the disk is full' });
+ });
+
+ it('rethrows in the renderer with the message the handler threw', async () => {
+ const { client } = harness(
+ createRPCRouter({
+ things: {
+ fail: () => {
+ throw new Error('the disk is full');
+ },
+ },
+ })
+ );
+
+ const error = await (client.things.fail as () => Promise<unknown>)().catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(RpcError);
+ expect((error as RpcError).message).toBe('the disk is full');
+ // The channel name is ours, not something a user can act on.
+ expect((error as RpcError).message).not.toContain('things.fail');
+ expect((error as RpcError).message).not.toContain('invoking remote method');
+ });
+
+ it('carries the error class through as a discriminator', async () => {
+ class GatewayError extends Error {
+ constructor(
+ readonly kind: string,
+ message: string,
+ readonly status?: number,
+ readonly detail?: string
+ ) {
+ super(message);
+ this.name = 'GatewayError';
+ }
+ }
+
+ const { client } = harness(
+ createRPCRouter({
+ gateway: {
+ call: () => {
+ throw new GatewayError('unauthorized', 'GET /rooms failed: 401', 401, 'token expired');
+ },
+ },
+ })
+ );
+
+ const error = (await (client.gateway.call as () => Promise<unknown>)().catch(
+ (e: unknown) => e
+ )) as RpcError;
+
+ // Before the boundary existed all three of these were lost, and a view had
+ // no way to tell a 401 from a 500 from an unreachable host.
+ expect(error.code).toBe('GatewayError');
+ expect(error.stringField('kind')).toBe('unauthorized');
+ expect(error.numberField('status')).toBe(401);
+ expect(error.stringField('detail')).toBe('token expired');
+ });
+
+ it('trims a message that ends in captured command output', async () => {
+ const { client } = harness(
+ createRPCRouter({
+ host: {
+ probe: () => {
+ throw new Error('probe failed: TypeError: fetch failed\n');
+ },
+ },
+ })
+ );
+
+ const error = (await (client.host.probe as () => Promise<unknown>)().catch(
+ (e: unknown) => e
+ )) as RpcError;
+ expect(error.message).toBe('probe failed: TypeError: fetch failed');
+ });
+
+ it('survives an error carrying values that cannot be cloned', async () => {
+ const { client } = harness(
+ createRPCRouter({
+ weird: {
+ call: () => {
+ throw Object.assign(new Error('nope'), { retry: () => undefined, depth: 3 });
+ },
+ },
+ })
+ );
+
+ const error = (await (client.weird.call as () => Promise<unknown>)().catch(
+ (e: unknown) => e
+ )) as RpcError;
+ expect(error.message).toBe('nope');
+ expect(error.numberField('depth')).toBe(3);
+ expect(error.data.retry).toBeUndefined();
+ });
+
+ it('passes a successful result through untouched', async () => {
+ const { client } = harness(
+ createRPCRouter({
+ things: { get: () => ({ id: 'a', nested: { ok: true } }) },
+ })
+ );
+
+ await expect((client.things.get as () => Promise<unknown>)()).resolves.toEqual({
+ id: 'a',
+ nested: { ok: true },
+ });
+ });
+
+ it('does not mistake a plain object result for a failure', async () => {
+ const { client } = harness(
+ createRPCRouter({
+ things: { get: () => ({ message: 'looks error-ish', code: 'Error' }) },
+ })
+ );
+
+ await expect((client.things.get as () => Promise<unknown>)()).resolves.toEqual({
+ message: 'looks error-ish',
+ code: 'Error',
+ });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc-error.ts b/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc-error.ts
new file mode 100644
index 000000000..2cfa207cb
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc-error.ts
@@ -0,0 +1,120 @@
+/**
+ * Carrying a thrown handler error across the IPC boundary without losing it.
+ *
+ * Left to Electron, a rejected `ipcMain.handle` reaches the renderer as a bare
+ * `Error` whose message has been rewritten to
+ * `Error invoking remote method '<channel>': <message>` — the app's own routing
+ * table, quoted at the user — and with every field but `message` dropped. That
+ * second half is the expensive one: `GatewayError` knows whether a call failed
+ * because the session expired, because the server answered 500, or because the
+ * network never reached it, and all three arrived in the renderer as the same
+ * flat string, so no view could tell them apart.
+ *
+ * A handler failure is therefore returned as a value rather than thrown, and
+ * rebuilt into an {@link RpcError} on the far side. The channel name stays out
+ * of the message, and a discriminator plus the error's own scalar fields
+ * survive the trip.
+ */
+
+/** Marks a resolved IPC value as a handler failure rather than a result. */
+const RPC_ERROR_MARKER = '__switchConsoleRpcError';
+
+export type SerializedRpcError = {
+ [RPC_ERROR_MARKER]: true;
+ /**
+ * Stable discriminator — the thrown error's class name (`GatewayError`,
+ * `HostUnreachableError`, …), or `Error` for anything unremarkable. This is
+ * what a view branches on instead of matching substrings of `message`.
+ */
+ code: string;
+ message: string;
+ /** The error's own enumerable fields, when they survive serialization. */
+ data?: Record<string, unknown>;
+};
+
+/**
+ * A handler failure, rebuilt in the renderer.
+ *
+ * `message` is what the main process actually threw — no channel name, no
+ * wrapping. Anything more specific lives on `code` and `data`.
+ */
+export class RpcError extends Error {
+ readonly code: string;
+ readonly data: Record<string, unknown>;
+
+ constructor(serialized: SerializedRpcError) {
+ super(serialized.message);
+ this.name = 'RpcError';
+ this.code = serialized.code;
+ this.data = serialized.data ?? {};
+ }
+
+ /** A field carried over from the original error, when it is a string. */
+ stringField(key: string): string | undefined {
+ const value = this.data[key];
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+ }
+
+ /** A field carried over from the original error, when it is a number. */
+ numberField(key: string): number | undefined {
+ const value = this.data[key];
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+ }
+}
+
+/**
+ * The error's own enumerable fields, minus anything that cannot cross the
+ * structured-clone boundary.
+ *
+ * A JSON round-trip is the filter: it is exactly the set of values Electron can
+ * carry, and it drops functions, symbols and cycles without having to enumerate
+ * what those might be. Fields are copied wholesale rather than from an
+ * allowlist, so a new modeled error arrives in the renderer intact without
+ * anyone remembering to register it here.
+ */
+function serializableFields(error: object): Record<string, unknown> | undefined {
+ const own: Record<string, unknown> = {};
+ for (const key of Object.keys(error)) {
+ if (key === 'stack' || key === 'message' || key === 'name') continue;
+ own[key] = (error as Record<string, unknown>)[key];
+ }
+ if (Object.keys(own).length === 0) return undefined;
+ try {
+ const round = JSON.parse(JSON.stringify(own)) as Record<string, unknown>;
+ return Object.keys(round).length > 0 ? round : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Turn a thrown handler error into a value the renderer can rebuild.
+ *
+ * The message is trimmed: several main-process messages interpolate captured
+ * command output, which arrives with the trailing newline still attached and
+ * reads as a stray space before whatever punctuation follows it.
+ */
+export function serializeRpcError(error: unknown): SerializedRpcError {
+ if (error instanceof Error) {
+ return {
+ [RPC_ERROR_MARKER]: true,
+ code: error.name || 'Error',
+ message: error.message.trim(),
+ data: serializableFields(error),
+ };
+ }
+ return {
+ [RPC_ERROR_MARKER]: true,
+ code: 'Error',
+ message: String(error).trim(),
+ };
+}
+
+export function isSerializedRpcError(value: unknown): value is SerializedRpcError {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ (value as Record<string, unknown>)[RPC_ERROR_MARKER] === true &&
+ typeof (value as SerializedRpcError).message === 'string'
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc.ts b/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc.ts
index 634c8bd9d..bed9e9cb8 100644
--- a/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc.ts
+++ b/console/apps/switch-console-desktop/src/shared/lib/ipc/rpc.ts
@@ -1,4 +1,5 @@
import { type IpcMain } from 'electron';
+import { isSerializedRpcError, RpcError, serializeRpcError } from './rpc-error';
// oxlint-disable-next-line typescript/no-explicit-any
type ProcedureMap = Record<string, (...args: any[]) => unknown>;
@@ -43,9 +44,16 @@ function registerHandlers(
): void {
if (typeof value === 'function') {
const handler = value as (...a: unknown[]) => unknown;
- ipcMain.handle(prefix, (_event, ...args: unknown[]) =>
- wrap ? wrap(prefix, args, () => handler(...args)) : handler(...args)
- );
+ // Resolved, never rejected: a failure is returned as a serialized error so
+ // Electron does not rewrite the message around the channel name or discard
+ // the error's own fields. `createRPCClient` turns it back into a throw.
+ ipcMain.handle(prefix, async (_event, ...args: unknown[]) => {
+ try {
+ return await (wrap ? wrap(prefix, args, () => handler(...args)) : handler(...args));
+ } catch (error) {
+ return serializeRpcError(error);
+ }
+ });
} else if (value !== null && typeof value === 'object') {
for (const [key, child] of Object.entries(value)) {
registerHandlers(ipcMain, `${prefix}.${key}`, child, wrap);
@@ -81,7 +89,10 @@ function makeChannelProxy(
): unknown {
return new Proxy(
function (...args: unknown[]) {
- return invoke(parts.join('.'), ...args);
+ return invoke(parts.join('.'), ...args).then((result) => {
+ if (isSerializedRpcError(result)) throw new RpcError(result);
+ return result;
+ });
},
{
get(_, key: string) {
diff --git a/console/apps/switch-console-desktop/tooling/oxlint-plugin.js b/console/apps/switch-console-desktop/tooling/oxlint-plugin.js
index 1006bdcbe..5b5e64471 100644
--- a/console/apps/switch-console-desktop/tooling/oxlint-plugin.js
+++ b/console/apps/switch-console-desktop/tooling/oxlint-plugin.js
@@ -1,5 +1,56 @@
const TOOLING_IMPORT_MESSAGE = '@tooling imports are only allowed in test files.';
+const RAW_ERROR_TEXT_MESSAGE =
+ 'Do not turn a caught error into display text by hand. Use describeFailure (title + description) or failureText from @renderer/lib/errors/describe-failure, so the user reads a sentence and the raw detail is moved rather than deleted.';
+
+/** `String(x)`. */
+function isStringCall(node) {
+ return (
+ node?.type === 'CallExpression' &&
+ node.callee?.type === 'Identifier' &&
+ node.callee.name === 'String'
+ );
+}
+
+/** `x.message`, for any `x`. */
+function isMessageAccess(node) {
+ return (
+ node?.type === 'MemberExpression' &&
+ !node.computed &&
+ node.property?.type === 'Identifier' &&
+ node.property.name === 'message'
+ );
+}
+
+/** `x instanceof Error`. */
+function isInstanceofError(node) {
+ return (
+ node?.type === 'BinaryExpression' &&
+ node.operator === 'instanceof' &&
+ node.right?.type === 'Identifier' &&
+ node.right.name === 'Error'
+ );
+}
+
+/**
+ * The idiom this bans is `e instanceof Error ? e.message : String(e)`.
+ *
+ * It appeared 114 times across the app and is the mechanism behind almost every
+ * finding in the CHOO-2060 audit: it produces a string that is either a raw
+ * exception or `[object Object]`, and every call site then rendered it straight
+ * at the user. Banning the shape rather than the rendering keeps the rule
+ * unambiguous — there is no legitimate reason to build display text this way in
+ * the renderer now that the shared boundary exists.
+ */
+function isRawErrorStringification(node) {
+ if (!isInstanceofError(node.test)) return false;
+ const branches = [node.consequent, node.alternate];
+ return (
+ branches.some((branch) => isMessageAccess(branch)) &&
+ branches.some((branch) => isStringCall(branch) || branch?.type === 'Literal')
+ );
+}
+
function isToolingImport(value) {
return value === '@tooling' || value.startsWith('@tooling/');
}
@@ -40,5 +91,21 @@ export default {
};
},
},
+ 'no-raw-error-text': {
+ meta: {
+ type: 'problem',
+ messages: {
+ rawErrorText: RAW_ERROR_TEXT_MESSAGE,
+ },
+ },
+ create(context) {
+ return {
+ ConditionalExpression(node) {
+ if (!isRawErrorStringification(node)) return;
+ context.report({ node, messageId: 'rawErrorText' });
+ },
+ };
+ },
+ },
},
};