Skip to content

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

feat(switchdash): logging and diagnostics foundation (CHOO-1683) (#83)

Louis Amaudruz52ed9496e680
diff --git a/dash/AGENTS.md b/dash/AGENTS.md
index a80a046f3..234c08bb6 100644
--- a/dash/AGENTS.md
+++ b/dash/AGENTS.md
@@ -232,6 +232,34 @@ shell, terminals, updates, and view state. Stateful main-process concerns use
singleton services; expected failures should use the `Result<T, E>` pattern from
`src/main/lib/result.ts`.
+### Logging
+
+`createLogger()` in `src/shared/logger.ts` backs all three processes. The console and
+the file sink are levelled independently: the console follows `LOG_LEVEL` (default
+`warn`), the file follows `LOG_FILE_LEVEL` (default `info`), so a shipped build records
+the run that led to a failure without a noisy terminal.
+
+Entries carry structured context. Do not add a parameter to a function only so a log
+line can mention it — the identity is ambient:
+
+- **Main:** an `AsyncLocalStorage` scope (`src/main/lib/log-context.ts`) is opened at the
+ RPC chokepoint, so anything beneath a call inherits its `sessionId`. Use
+ `runWithLogContext()` when adding a new entry point, and `bindLogContext()` for
+ callbacks that outlive the operation that created them (streams, intervals) — ALS
+ follows promises and timers but such emitters otherwise keep a stale scope forever.
+- **Renderer:** no ALS in the browser; attach ids with `log.child({ … })`.
+- **Enrichment:** `registerLogContextResolver()` derives the remaining fields from the
+ ids present (session → room, id → name). Resolvers must stay synchronous and
+ best-effort; never query the database from the logging path, which runs during
+ shutdown and inside error handlers.
+
+Names come from a cache **pushed to** by the row mappers (`mapSessionRowToSession`,
+`mapAgentRowToAgent`) — never fetched on demand.
+
+At the boundaries that fail (sidecar launch, migrations, updater, PTY, RPC), log an
+`event` plus an enumerated `stage`/`errorCode` rather than prose, so failures can be
+grepped and counted.
+
## Testing Strategy
- Local merge gate:
@@ -282,8 +310,19 @@ pnpm run lint
- Application secrets are stored through encrypted app secret services and Electron
safe storage.
- The app ships no telemetry or analytics; do not add tracking or phone-home behavior.
-- File logging redacts common secret patterns; preserve this behavior when touching
- logging or error-reporting code.
+ Logs are local-only: they leave the machine solely when the user attaches them to a
+ feedback report, via `getDiagnosticLogAttachment()`. Do not add any other path that
+ transmits log content.
+- **Redaction is split by destination, and both halves must be preserved:**
+ - **Secrets** (tokens, keys, JWTs, PEM blocks, URL credentials) are redacted on the
+ write path by `redactSecrets()` and must never reach disk.
+ - **Personal data** (home directories, IP and MAC addresses, emails) is deliberately
+ *retained* in the local log file — it is what makes a user's own log debuggable —
+ and is redacted by `redactDiagnosticLog()` in `getDiagnosticLogAttachment()`, the
+ single point at which content leaves the machine. Do not "fix" the local file by
+ scrubbing it on write; that reinstates the problem this split exists to solve.
+ - Anything contributed via `registerDiagnosticSection()` passes through the same
+ export scrub. Never read the raw log file from outside `file-logger.ts`.
- PTY environment passthrough must use the allowlist in `src/main/core/pty/pty-env.ts`.
- Treat shell escaping and PTY spawning as security-sensitive.
- Do not bypass path-safety, shell escaping, or validation helpers.
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
index a00d3f600..ab2795036 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
@@ -52,7 +52,14 @@ async function buildLauncher(params: AgentSidecarParams): Promise<RemoteSidecarL
launchSpec,
credsSlug: params.credsSlug,
},
- log,
+ // Bound once here so every line the launcher writes names the agent it is
+ // acting for. Sidecar work runs off watchers rather than an RPC call, so
+ // there is no ambient scope for it to inherit.
+ log: log.child({
+ component: 'sidecar-launcher',
+ agentSlug: params.credsSlug,
+ agentName: params.agentName ?? undefined,
+ }),
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
index 0115cee82..9220a5ff3 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
@@ -25,6 +25,7 @@ import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notific
import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';
import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';
import { events } from '@main/lib/events';
+import { runWithLogContext } from '@main/lib/log-context';
import { log } from '@main/lib/logger';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { makePtyId } from '@shared/core/pty/ptyId';
@@ -97,7 +98,17 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {
isResuming: boolean = false,
initialPrompt?: string
): Promise<void> {
- return this.startInternal(session, initialSize, isResuming, initialPrompt, false);
+ // Establishes the scope the PTY spawn and everything else below inherits,
+ // so those lines name their session without being handed its id.
+ return runWithLogContext(
+ {
+ component: 'local-agent-runtime',
+ sessionId: this.sessionId,
+ agentId: session.agentId,
+ agentName: session.agentName ?? undefined,
+ },
+ () => this.startInternal(session, initialSize, isResuming, initialPrompt, false)
+ );
}
private async startInternal(
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
index 1f66cd52b..b794aed8a 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
@@ -48,7 +48,7 @@ const readyLine = (
epoch,
version,
})}\n`;
-const noopLog = { debug: vi.fn(), warn: vi.fn() };
+const noopLog = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() };
interface ExecCall {
command: string;
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
index f392a7e2a..e03a16a7b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
@@ -117,6 +117,7 @@ export interface SidecarHost {
export interface SidecarLauncherLogger {
debug(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
+ error(message: string, meta?: Record<string, unknown>): void;
}
function sidecarEnv(config: SidecarLaunchConfig): Record<string, string> {
@@ -190,6 +191,9 @@ export class RemoteSidecarLauncher {
private readonly log: SidecarLauncherLogger;
private readonly sleep: (ms: number) => Promise<void>;
+ /** Step currently being attempted, reported when a launch fails. */
+ private stage = 'idle';
+
private readonly hashBundle: () => Promise<string>;
constructor(opts: {
@@ -250,11 +254,41 @@ export class RemoteSidecarLauncher {
* the bundle and start fresh.
*/
async deployAndLaunch(): Promise<SidecarEndpoint> {
+ const startedAt = Date.now();
+ // Which step was reached is the whole diagnosis here: an SSH auth refusal
+ // and a ready-file timeout are unrelated faults with unrelated fixes, and
+ // a single "sidecar launch failed" cannot tell them apart.
+ this.stage = 'launch-spec';
+
+ try {
+ const endpoint = await this.runDeployAndLaunch();
+ this.log.debug('RemoteSidecarLauncher: launch succeeded', {
+ event: 'sidecar_launch_succeeded',
+ durationMs: Date.now() - startedAt,
+ sidecarTmuxName: this.sidecarTmuxName,
+ });
+ return endpoint;
+ } catch (error) {
+ this.log.error('RemoteSidecarLauncher: launch failed', {
+ event: 'sidecar_launch_failed',
+ stage: this.stage,
+ durationMs: Date.now() - startedAt,
+ sidecarTmuxName: this.sidecarTmuxName,
+ agentSlug: this.config.credsSlug,
+ error: String(error),
+ });
+ throw error;
+ }
+ }
+
+ private async runDeployAndLaunch(): Promise<SidecarEndpoint> {
// Always (re)write the launch spec first so a config change (e.g. new extra
// args) takes effect on the next fresh launch, even when reattaching.
await this.writeLaunchSpec();
+ this.stage = 'hash-bundle';
const localHash = await this.hashBundle();
+ this.stage = 'reattach-check';
const existing = await this.decideExisting(localHash);
if (existing) {
this.log.debug('RemoteSidecarLauncher: reattached to running sidecar', {
@@ -268,6 +302,7 @@ export class RemoteSidecarLauncher {
// overwrite the bundle under each other and each kill the other's freshly
// started process. Serialise it across clients, then re-check — whoever
// waited may find the holder already started exactly what it wanted.
+ this.stage = 'deploy-lock';
return this.withDeployLock(async () => {
const reattach = await this.decideExisting(localHash);
if (reattach) {
@@ -279,16 +314,21 @@ export class RemoteSidecarLauncher {
}
const previousEpoch = await this.runningEpoch();
+ this.stage = 'prepare-dir';
const remoteHash = await this.prepareDir();
if (remoteHash === localHash) {
this.log.debug('RemoteSidecarLauncher: bundle unchanged on host — skipping upload', {
sidecarTmuxName: this.sidecarTmuxName,
});
} else {
+ this.stage = 'upload-bundle';
await this.uploadBundle();
}
+ this.stage = 'kill-previous';
await this.killSidecar();
+ this.stage = 'spawn';
await this.startDetached(localHash);
+ this.stage = 'await-ready';
return this.awaitReady(previousEpoch);
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
index 5d08a0c66..3eddc80f4 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
@@ -21,6 +21,7 @@ import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-co
import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';
import type { SshConnectionManagerEvent } from '@main/core/ssh/lifecycle/ssh-connection-manager';
import { events } from '@main/lib/events';
+import { runWithLogContext } from '@main/lib/log-context';
import { log } from '@main/lib/logger';
import type { AgentSessionConfig } from '@shared/core/providers/agent-session';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
@@ -132,6 +133,10 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
if (!this.supervisor.isDesired()) return;
const session = this.session;
if (!session) return;
+ return this.withLogScope(() => this.rehydrateInternal(session));
+ }
+
+ private async rehydrateInternal(session: Session): Promise<void> {
const size = ptySessionRegistry.getLastSize(this.ptySessionId) ?? {
cols: DEFAULT_COLS,
rows: DEFAULT_ROWS,
@@ -315,7 +320,15 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
}
await agentHookService.handleRawHook(raw, { startLocalPoller: false });
},
- log,
+ // Bound explicitly rather than inherited: the relay polls on its own timer
+ // for the lifetime of the session, and a scope captured from whatever call
+ // happened to start it would drift out of date.
+ log: log.child({
+ component: 'hook-relay',
+ sessionId: this.sessionId,
+ agentId: this.session?.agentId,
+ agentName: this.session?.agentName ?? undefined,
+ }),
});
this.relay = relay;
relay.start();
@@ -336,6 +349,26 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
this.stopRelay();
}
+ /**
+ * Run inside this runtime's log scope.
+ *
+ * Remote agent work is driven by watchers and reconnect events rather than by
+ * an RPC call, so there is no ambient context to inherit — it is established
+ * here instead. Everything below reports which session and agent it belongs
+ * to without any intermediate signature carrying the ids.
+ */
+ private withLogScope<T>(fn: () => T): T {
+ return runWithLogContext(
+ {
+ component: 'ssh-agent-runtime',
+ sessionId: this.sessionId,
+ agentId: this.session?.agentId,
+ agentName: this.session?.agentName ?? undefined,
+ },
+ fn
+ );
+ }
+
async start(
session: Session,
initialSize: { cols: number; rows: number } = {
@@ -345,9 +378,20 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
isResuming: boolean = false,
initialPrompt?: string
): Promise<void> {
- return this.startInternal(session, initialSize, isResuming, initialPrompt, false, {
- shellRefreshRetried: false,
- });
+ // Bound before the assignment inside startInternal, so the agent fields come
+ // from the session being started rather than a stale one.
+ return runWithLogContext(
+ {
+ component: 'ssh-agent-runtime',
+ sessionId: this.sessionId,
+ agentId: session.agentId,
+ agentName: session.agentName ?? undefined,
+ },
+ () =>
+ this.startInternal(session, initialSize, isResuming, initialPrompt, false, {
+ shellRefreshRetried: false,
+ })
+ );
}
private async startInternal(
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts b/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts
index 8608a249b..9fd84ef9b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts
@@ -1,7 +1,12 @@
import type { AgentRow } from '@main/db/schema';
+import { noteAgentName } from '@main/lib/log-name-cache';
import type { Agent } from '@shared/core/agents/agents';
export function mapAgentRowToAgent(row: AgentRow): Agent {
+ // Every read and write of an agent passes through here, so the log sink can
+ // name an agent id without ever querying for it.
+ noteAgentName(row.id, row.name);
+
return {
id: row.id,
locationId: row.locationId,
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts
index a7bfdd8be..dc2c2d70d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts
@@ -1,4 +1,5 @@
import type { SessionRow } from '@main/db/schema';
+import { noteAgentName, noteSessionTitle } from '@main/lib/log-name-cache';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import type { AgentStatus } from '@shared/core/providers/agentEvents';
import type { Session, SessionLifecycleStatus } from '@shared/core/sessions/sessions';
@@ -15,6 +16,11 @@ export function mapSessionRowToSession(
providerId: AgentProviderId,
agentName: string
): Session {
+ // Single chokepoint for session rows, so the log sink can put a title next to
+ // a session id without a query on the write path.
+ noteSessionTitle(row.id, row.title);
+ noteAgentName(row.agentId, agentName);
+
const config = row.config ?? {};
return {
id: row.id,
diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/sidecar-diagnostics.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/sidecar-diagnostics.ts
new file mode 100644
index 000000000..764ca2acb
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/sidecar-diagnostics.ts
@@ -0,0 +1,74 @@
+import { DEEPLINK_SCHEME } from '@main/app/deeplinks';
+import { readAgentSidecarLog } from '@main/core/agent-runtime/impl/ensure-agent-sidecar';
+import { getRemoteAgentLocation } from '@main/core/agents/agent-location';
+import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';
+import { getAgents } from '@main/core/agents/getAgents';
+import { registerDiagnosticSection } from '@main/lib/file-logger';
+import { log } from '@main/lib/logger';
+import type { Agent } from '@shared/core/agents/agents';
+
+const DIAGNOSTIC_TAIL_LINES = 200;
+
+/**
+ * Include remote sidecar logs in the diagnostic attachment.
+ *
+ * A remote agent keeps running while switchdash is closed, so its sidecar is
+ * where the failures worth reporting tend to happen — and until now that log
+ * stayed on the VM, leaving a bug report about a remote agent with no record of
+ * the process it was actually about.
+ *
+ * Pulled on demand rather than streamed continuously: a report is the only time
+ * the content is needed, and holding a live tail open per agent would cost an
+ * SSH channel each for output almost always discarded.
+ */
+export function registerSidecarDiagnostics(): void {
+ registerDiagnosticSection('remote sidecar logs', collectSidecarLogs);
+}
+
+async function collectSidecarLogs(): Promise<string> {
+ const agents = await getAgents();
+ const remote = await filterRemote(agents);
+ if (!remote.length) return '';
+
+ const sections = await Promise.all(remote.map(collectForAgent));
+ return sections.filter(Boolean).join('\n');
+}
+
+async function filterRemote(agents: Agent[]): Promise<Agent[]> {
+ const checked = await Promise.all(
+ agents.map(async (agent) => ((await getRemoteAgentLocation(agent)) ? agent : undefined))
+ );
+ return checked.filter((agent): agent is Agent => agent !== undefined);
+}
+
+async function collectForAgent(agent: Agent): Promise<string> {
+ const label = `--- sidecar: ${agent.name ?? agent.id} (${agent.id}) ---`;
+
+ try {
+ const conn = await connectRemoteAgent(agent);
+ const tail = await readAgentSidecarLog(
+ {
+ providerId: agent.providerId,
+ repoDir: conn.remoteRepoDir,
+ deeplinkScheme: DEEPLINK_SCHEME,
+ autoApprove: agent.autoApprove,
+ credsSlug: agent.name ?? agent.id,
+ agentName: agent.name ?? null,
+ ctx: conn.ctx,
+ connectionId: conn.connectionId,
+ host: conn.host,
+ },
+ DIAGNOSTIC_TAIL_LINES
+ );
+
+ return `${label}\n${tail.trim() || '(log empty)'}`;
+ } catch (error) {
+ // An unreachable host is itself worth reporting — it is frequently the
+ // problem being reported — so the failure is recorded rather than dropped.
+ log.warn('sidecarDiagnostics: failed to read sidecar log', {
+ agentId: agent.id,
+ error: String(error),
+ });
+ return `${label}\n(unavailable: ${String(error)})`;
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts
index 9060f5fa2..0cdc81556 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts
@@ -176,6 +176,24 @@ class SwitchRoomService implements IDisposable {
});
}
+ /**
+ * The room fields a log entry can borrow from a session id.
+ *
+ * Synchronous and in-memory on purpose: this runs on the logging write path,
+ * where an awaited lookup would be a deadlock waiting for shutdown.
+ */
+ describeSessionForLog(
+ sessionId: string
+ ): { roomId?: string; roomName?: string; agentId?: string } | undefined {
+ const connection = this.connections.get(sessionId);
+ if (!connection) return undefined;
+ return {
+ roomId: connection.roomId ?? undefined,
+ roomName: connection.roomName ?? undefined,
+ agentId: connection.agentId ?? undefined,
+ };
+ }
+
/** The current set of live session→room connections. */
getConnections(): SessionRoomConnection[] {
return [...this.connections.values()].map(({ sessionId, roomId, agentId }) => ({
diff --git a/dash/apps/switchdash-desktop/src/main/db/initialize.ts b/dash/apps/switchdash-desktop/src/main/db/initialize.ts
index 9829af7b0..77402f752 100644
--- a/dash/apps/switchdash-desktop/src/main/db/initialize.ts
+++ b/dash/apps/switchdash-desktop/src/main/db/initialize.ts
@@ -1,5 +1,6 @@
import { createHash } from 'node:crypto';
import type BetterSqlite3 from 'better-sqlite3';
+import { log } from '@main/lib/logger';
import journal from '@root/drizzle/meta/_journal.json';
// Vite bundles all migration SQL files at build time — no runtime path resolution needed.
@@ -13,6 +14,10 @@ const sqlFiles = import.meta.glob('@root/drizzle/*.sql', {
type JournalEntry = { idx: number; when: number; tag: string; breakpoints: boolean };
function runBundledMigrations(connection: BetterSqlite3.Database): void {
+ const migrationLog = log.child({ component: 'db-migration' });
+ const startedAt = Date.now();
+ const applied: string[] = [];
+
connection.exec(`
CREATE TABLE IF NOT EXISTS __drizzle_migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -33,6 +38,8 @@ function runBundledMigrations(connection: BetterSqlite3.Database): void {
// (outside the migration transaction) and restore it afterwards.
connection.pragma('foreign_keys = OFF');
try {
+ // A failed migration is unrecoverable and cannot be reconstructed after the
+ // fact, so which one was being applied is recorded as it happens.
connection.transaction(() => {
for (const entry of (journal as { entries: JournalEntry[] }).entries) {
if (entry.when <= lastTimestamp) continue;
@@ -51,8 +58,26 @@ function runBundledMigrations(connection: BetterSqlite3.Database): void {
connection
.prepare('INSERT INTO __drizzle_migrations (hash, created_at) VALUES (?, ?)')
.run(hash, entry.when);
+ applied.push(entry.tag);
}
})();
+
+ if (applied.length) {
+ migrationLog.info('Applied database migrations', {
+ event: 'db_migration_applied',
+ migrations: applied,
+ durationMs: Date.now() - startedAt,
+ });
+ }
+ } catch (error) {
+ migrationLog.error('Database migration failed', {
+ event: 'db_migration_failed',
+ applied,
+ failedAfter: applied.at(-1) ?? '(none)',
+ durationMs: Date.now() - startedAt,
+ error: String(error),
+ });
+ throw error;
} finally {
connection.pragma('foreign_keys = ON');
}
diff --git a/dash/apps/switchdash-desktop/src/main/index.ts b/dash/apps/switchdash-desktop/src/main/index.ts
index 4b9d491c6..9f42d4b97 100644
--- a/dash/apps/switchdash-desktop/src/main/index.ts
+++ b/dash/apps/switchdash-desktop/src/main/index.ts
@@ -29,18 +29,22 @@ import {
import { locationFileIndexService } from './core/search/location-file-index-service';
import { searchService } from './core/search/search-service';
import { appSettingsService } from './core/settings/settings-service';
+import { registerSidecarDiagnostics } from './core/sidecar/sidecar-diagnostics';
import { sshConnectionManager } from './core/ssh/lifecycle/production-ssh-connection-manager';
import { autoSessionWatcher } from './core/switch-rooms/auto-session-watcher';
import { restoreSwitchRoomSessions } from './core/switch-rooms/restore-sessions';
import { updateService } from './core/updates/update-service';
import { viewStateService } from './core/view-state/view-state-service';
import { initializeDatabase } from './db/initialize';
+import { logAppExit, logAppStart, registerAppDiagnostics } from './lib/app-diagnostics';
import {
initializeFileLogger,
registerProcessErrorLogging,
registerRendererLogHandler,
} from './lib/file-logger';
+import { registerLogEnrichment } from './lib/log-enrichment';
import { log } from './lib/logger';
+import { withRPCLogContext } from './lib/rpc-logging';
import { rpcRouter } from './rpc';
import { resolveUserEnv } from './utils/userEnv';
@@ -56,8 +60,12 @@ registerAppScheme();
setupDeeplinks();
initializeFileLogger();
+registerLogEnrichment();
+registerAppDiagnostics();
+registerSidecarDiagnostics();
registerProcessErrorLogging(log);
registerRendererLogHandler(ipcMain);
+logAppStart();
app.on('second-instance', () => {
const win = BrowserWindow.getAllWindows()[0];
@@ -134,7 +142,7 @@ void app.whenReady().then(async () => {
log.error('Failed to start agent event service:', e);
});
- registerRPCRouter(rpcRouter, ipcMain);
+ registerRPCRouter(rpcRouter, ipcMain, withRPCLogContext);
void reconcileResourceSampler();
@@ -217,6 +225,7 @@ void app.whenReady().then(async () => {
app.on('before-quit', (event) => {
event.preventDefault();
+ logAppExit('before-quit');
agentHookService.dispose();
stopResourceSampler();
localServerService.dispose();
diff --git a/dash/apps/switchdash-desktop/src/main/lib/app-diagnostics.ts b/dash/apps/switchdash-desktop/src/main/lib/app-diagnostics.ts
new file mode 100644
index 000000000..a7c37072d
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/lib/app-diagnostics.ts
@@ -0,0 +1,67 @@
+import { app } from 'electron';
+import { getLogFilePath, getLogWriteFailures, registerDiagnosticSection } from './file-logger';
+import { getRunId } from './log-context';
+import { log } from './logger';
+
+/**
+ * Record what this run is, once, at startup.
+ *
+ * Without it an exported log opens mid-sentence: no version, no platform, and
+ * — because the file spans restarts — no way to tell where one launch ended
+ * and the next began. A crash loop and an uneventful afternoon look alike.
+ * Every entry carries the same `runId`, so a single launch can be isolated.
+ */
+export function logAppStart(): void {
+ log.child({ component: 'app', event: 'app_start' }).info('Application starting', {
+ runId: getRunId(),
+ appVersion: app.getVersion(),
+ electron: process.versions.electron,
+ chrome: process.versions.chrome,
+ node: process.versions.node,
+ platform: process.platform,
+ arch: process.arch,
+ locale: app.getLocale(),
+ packaged: app.isPackaged,
+ });
+}
+
+/**
+ * Record how the run ended.
+ *
+ * The absence of this line before the next `app_start` is what identifies a
+ * crash — a clean quit and a hard kill are otherwise indistinguishable after
+ * the fact.
+ */
+export function logAppExit(reason: string): void {
+ log.child({ component: 'app', event: 'app_exit' }).info('Application exiting', { reason });
+}
+
+export function registerAppDiagnostics(): void {
+ registerDiagnosticSection('system info', async () => {
+ const failures = getLogWriteFailures();
+
+ const lines = [
+ `app version: ${app.getVersion()}`,
+ `packaged: ${app.isPackaged}`,
+ `run id: ${getRunId()}`,
+ `platform: ${process.platform} ${process.arch}`,
+ `electron: ${process.versions.electron}`,
+ `chrome: ${process.versions.chrome}`,
+ `node: ${process.versions.node}`,
+ `locale: ${app.getLocale()}`,
+ `uptime: ${Math.round(process.uptime())}s`,
+ `log file: ${getLogFilePath() ?? '(not initialised)'}`,
+ ];
+
+ // Surfaced rather than hidden: if writes were failing, the log below this
+ // header is incomplete, and whoever reads the report needs to know that
+ // before concluding anything from what is missing.
+ if (failures.count > 0) {
+ lines.push(
+ `log write failures: ${failures.count}${failures.lastError ? ` (last: ${failures.lastError})` : ''}`
+ );
+ }
+
+ return lines.join('\n');
+ });
+}
diff --git a/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.ts b/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.ts
index 4b41ac29e..bdf5e71bf 100644
--- a/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/lib/file-logger.test.ts
@@ -1,5 +1,11 @@
-import { describe, expect, it, vi } from 'vitest';
-import { redactDiagnosticLog } from './file-logger';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ clearDiagnosticSections,
+ getDiagnosticLogAttachment,
+ redactDiagnosticLog,
+ redactSecrets,
+ registerDiagnosticSection,
+} from './file-logger';
vi.mock('electron', () => ({
app: {
@@ -130,3 +136,109 @@ describe('redactDiagnosticLog', () => {
expect(redacted).toContain('https://[REDACTED_CREDENTIALS]@example.com/repo');
});
});
+
+describe('redactSecrets (write path)', () => {
+ it.each([
+ ['bearer authorization', 'authorization: Bearer abc123', 'abc123'],
+ ['api key', 'api_key=super-secret-key', 'super-secret-key'],
+ ['github token', 'ghp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'ghp_a'],
+ ['anthropic key', 'sk-ant-aaaaaaaaaaaaaaaaaaaaaaaa', 'sk-ant-a'],
+ ['jwt', 'eyJabcdefgh.eyJabcdefgh.signaturebits', 'signaturebits'],
+ ['json password', JSON.stringify({ password: 'hunter2' }), 'hunter2'],
+ ])('never lets %s reach disk', (_label, input, secret) => {
+ const written = redactSecrets(input);
+
+ expect(written).not.toContain(secret);
+ expect(written).toContain('REDACTED');
+ });
+
+ it('redacts PEM private-key blocks', () => {
+ const pem = [
+ '-----BEGIN RSA PRIVATE KEY-----',
+ 'MIIEpAIBAAKCAQEAxyz...',
+ '-----END RSA PRIVATE KEY-----',
+ ].join('\n');
+
+ expect(redactSecrets(pem)).toBe('[REDACTED_PEM_BLOCK]');
+ });
+
+ it.each([
+ ['ipv4 address', 'ssh to 192.168.1.25 refused', '192.168.1.25'],
+ ['linux home path', 'worktree /home/bob/work/repo missing', '/home/bob/work/repo'],
+ ['macos home path', 'worktree /Users/alice/repo missing', '/Users/alice/repo'],
+ ['email address', 'signed in as [email protected]', '[email protected]'],
+ ])('keeps %s readable in the local file', (_label, input, retained) => {
+ // The local log is the copy the user debugs from; scrubbing the address or
+ // path here would delete the very detail a failure report is about. It is
+ // removed by redactDiagnosticLog when content actually leaves the machine.
+ expect(redactSecrets(input)).toContain(retained);
+ });
+
+ it('composes with the export pass, which then removes the rest', () => {
+ const line = 'ssh to 192.168.1.25 with token ghp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+
+ const onDisk = redactSecrets(line);
+ const exported = redactDiagnosticLog(onDisk);
+
+ expect(onDisk).toContain('192.168.1.25');
+ expect(onDisk).not.toContain('ghp_a');
+ expect(exported).toContain('[REDACTED_IP]');
+ expect(exported).not.toContain('ghp_a');
+ });
+});
+
+describe('diagnostic sections', () => {
+ beforeEach(() => {
+ clearDiagnosticSections();
+ });
+
+ it('includes a contributed section in the attachment', async () => {
+ registerDiagnosticSection('sidecar', async () => 'sidecar said hello');
+
+ const { content } = await getDiagnosticLogAttachment();
+
+ expect(content).toContain('===== sidecar =====');
+ expect(content).toContain('sidecar said hello');
+ });
+
+ it('redacts contributed sections like everything else', async () => {
+ registerDiagnosticSection('sidecar', async () => 'connected from 192.168.1.25');
+
+ const { content } = await getDiagnosticLogAttachment();
+
+ // A section must not become a way around the export scrub.
+ expect(content).toContain('[REDACTED_IP]');
+ expect(content).not.toContain('192.168.1.25');
+ });
+
+ it('reports a failing section rather than omitting it', async () => {
+ registerDiagnosticSection('sidecar', async () => {
+ throw new Error('host unreachable');
+ });
+
+ const { content } = await getDiagnosticLogAttachment();
+
+ // Silence would read as "there was nothing to report" — and an unreachable
+ // host is frequently the thing being reported.
+ expect(content).toContain('failed to collect');
+ expect(content).toContain('host unreachable');
+ });
+
+ it('does not let one section block the others', async () => {
+ registerDiagnosticSection('slow', () => new Promise<string>(() => {}));
+ registerDiagnosticSection('fast', async () => 'collected fine');
+
+ const { content } = await vi.waitFor(() => getDiagnosticLogAttachment(), { timeout: 10_000 });
+
+ expect(content).toContain('collected fine');
+ expect(content).toContain('timed out collecting');
+ }, 15_000);
+
+ it('omits an empty section entirely', async () => {
+ registerDiagnosticSection('empty', async () => ' ');
+
+ const { content } = await getDiagnosticLogAttachment();
+
+ expect(content).not.toContain('===== empty =====');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/lib/file-logger.ts b/dash/apps/switchdash-desktop/src/main/lib/file-logger.ts
index 2e040770c..d734073f1 100644
--- a/dash/apps/switchdash-desktop/src/main/lib/file-logger.ts
+++ b/dash/apps/switchdash-desktop/src/main/lib/file-logger.ts
@@ -6,8 +6,10 @@ import {
serializeLogValue,
stringifyLogValue,
type Level,
+ type LogContext,
type LogSinkEntry,
} from '@shared/logger';
+import { resolveLogContext } from './log-context';
const MAX_LOG_BYTES = 5 * 1024 * 1024;
const DIAGNOSTIC_LOG_BYTES = 500 * 1024;
@@ -16,6 +18,9 @@ const LOG_FILE_NAME = 'switchdash.log';
const DIAGNOSTIC_ATTACHMENT_FILENAME = 'switchdash-diagnostics.log';
const RENDERER_LOG_PAYLOAD_LIMIT = 64 * 1024;
const PROCESS_EXIT_FLUSH_TIMEOUT_MS = 1000;
+const FLUSH_INTERVAL_MS = 250;
+const FLUSH_BYTES = 64 * 1024;
+const DIAGNOSTIC_SECTION_TIMEOUT_MS = 5000;
const SECRET_KEY_NAMES =
'authorization|api[_-]?key|token|password|passphrase|secret|access[_-]?token|refresh[_-]?token|client[_-]?secret';
@@ -65,6 +70,12 @@ let logFilePath: string | undefined;
let logDirReady = false;
let pendingWrite: Promise<void> = Promise.resolve();
+let buffer: string[] = [];
+let bufferedBytes = 0;
+let flushTimer: NodeJS.Timeout | undefined;
+let failedWrites = 0;
+let lastWriteError: string | undefined;
+
export function initializeFileLogger() {
const electronApp = app as Electron.App | undefined;
if (!electronApp?.setAppLogsPath) return;
@@ -77,6 +88,75 @@ export function getLogFilePath() {
return logFilePath;
}
+/**
+ * A sink that has stopped recording must not do so quietly: an empty log file
+ * looks identical to an uneventful run, and the user only finds out when the
+ * diagnostics they send back turn out to be blank.
+ */
+function recordWriteFailure(error: unknown) {
+ failedWrites += 1;
+ lastWriteError = error instanceof Error ? error.message : String(error);
+ console.error('Failed to write application log:', error);
+}
+
+export function getLogWriteFailures(): { count: number; lastError?: string } {
+ return { count: failedWrites, lastError: lastWriteError };
+}
+
+type DiagnosticSection = { title: string; collect: () => Promise<string> };
+
+const diagnosticSections: DiagnosticSection[] = [];
+
+/**
+ * Contribute an extra section to the diagnostic attachment.
+ *
+ * Registered rather than imported for the same reason the context resolvers
+ * are: the subsystems worth reporting on all log, so importing them here would
+ * be a cycle.
+ */
+export function registerDiagnosticSection(title: string, collect: () => Promise<string>): void {
+ diagnosticSections.push({ title, collect });
+}
+
+/** Test seam. */
+export function clearDiagnosticSections(): void {
+ diagnosticSections.length = 0;
+}
+
+async function collectDiagnosticSections(): Promise<string> {
+ if (!diagnosticSections.length) return '';
+
+ const collected = await Promise.all(
+ diagnosticSections.map(async ({ title, collect }) => {
+ try {
+ // A section that hangs must not hold the report hostage; a remote pull
+ // over SSH can stall indefinitely on an unreachable host.
+ const body = await withTimeout(collect(), DIAGNOSTIC_SECTION_TIMEOUT_MS);
+ if (body === TIMED_OUT) return `===== ${title} =====\n(timed out collecting)\n`;
+ return body.trim() ? `===== ${title} =====\n${body.trim()}\n` : '';
+ } catch (error) {
+ // Say so rather than omitting the section: a silently missing section
+ // reads as "there was nothing to report".
+ return `===== ${title} =====\n(failed to collect: ${String(error)})\n`;
+ }
+ })
+ );
+
+ return collected.filter(Boolean).join('\n');
+}
+
+const TIMED_OUT = Symbol('timed-out');
+
+function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | typeof TIMED_OUT> {
+ return Promise.race([
+ promise,
+ new Promise<typeof TIMED_OUT>((resolve) => {
+ const timer = setTimeout(() => resolve(TIMED_OUT), ms);
+ timer.unref?.();
+ }),
+ ]);
+}
+
export async function getDiagnosticLogAttachment() {
if (!logFilePath) initializeFileLogger();
const path = logFilePath;
@@ -89,9 +169,21 @@ export async function getDiagnosticLogAttachment() {
if (!path) return fallback;
+ // Buffered entries are part of the run being reported on.
+ await flushLogWrites();
+
const raw = await readFile(path, 'utf8').catch(() => '');
const tail = trimToLineBoundary(raw, DIAGNOSTIC_LOG_BYTES);
- const redacted = redactDiagnosticLog(tail);
+ const sections = await collectDiagnosticSections();
+
+ const body = sections ? `${sections}\n===== application log =====\n${tail}` : tail;
+
+ // Personal data is removed here rather than on write: this is the only path
+ // by which log content leaves the machine, so scrubbing at the boundary keeps
+ // the exported copy exactly as safe while leaving the user's own log
+ // readable enough to debug from. Contributed sections go through the same
+ // pass, so a section cannot become a way around it.
+ const redacted = redactDiagnosticLog(body);
return {
filename: DIAGNOSTIC_ATTACHMENT_FILENAME,
@@ -109,10 +201,51 @@ export function writeLogEntry(entry: LogSinkEntry) {
timestamp: new Date().toISOString(),
level: entry.level,
source: entry.source ?? 'main',
+ ...omitEmptyContext(resolveLogContext(entry.context)),
message: formatMessage(entry.input),
- data: entry.input.map(serializeLogValue),
+ data: structuredArgs(entry.input),
});
- const line = `${redactDiagnosticLog(payload)}\n`;
+ const line = `${redactSecrets(payload)}\n`;
+
+ buffer.push(line);
+ bufferedBytes += Buffer.byteLength(line);
+
+ // An error may be the last thing recorded before a crash, so it is not left
+ // sitting in a buffer waiting for a timer that will never fire.
+ if (entry.level === 'error' || bufferedBytes >= FLUSH_BYTES) {
+ void flushBuffer();
+ return;
+ }
+
+ scheduleFlush();
+}
+
+function scheduleFlush() {
+ if (flushTimer) return;
+ flushTimer = setTimeout(() => {
+ flushTimer = undefined;
+ void flushBuffer();
+ }, FLUSH_INTERVAL_MS);
+ // Never let a pending log flush be the reason the process stays alive.
+ flushTimer.unref?.();
+}
+
+/**
+ * Append everything buffered as a single write.
+ *
+ * Batching keeps the file sink viable at `info`: one append and one rotation
+ * check per batch rather than per entry, and the promise chain grows once per
+ * flush instead of once per log call.
+ */
+function flushBuffer(): Promise<void> {
+ if (!buffer.length) return pendingWrite;
+
+ const path = logFilePath;
+ if (!path) return pendingWrite;
+
+ const chunk = buffer.join('');
+ buffer = [];
+ bufferedBytes = 0;
pendingWrite = pendingWrite
.then(async () => {
@@ -120,16 +253,22 @@ export function writeLogEntry(entry: LogSinkEntry) {
await mkdir(join(path, '..'), { recursive: true });
logDirReady = true;
}
- await rotateIfNeeded(path, Buffer.byteLength(line));
- await appendFile(path, line, 'utf8');
+ await rotateIfNeeded(path, Buffer.byteLength(chunk));
+ await appendFile(path, chunk, 'utf8');
})
.catch((error) => {
- console.error('Failed to write application log:', error);
+ recordWriteFailure(error);
});
+
+ return pendingWrite;
}
export function flushLogWrites() {
- return pendingWrite;
+ if (flushTimer) {
+ clearTimeout(flushTimer);
+ flushTimer = undefined;
+ }
+ return flushBuffer();
}
export function registerProcessErrorLogging(log: {
@@ -157,13 +296,59 @@ function flushAndExit() {
export function registerRendererLogHandler(ipcMain: Electron.IpcMain) {
ipcMain.on('switchdash:renderer-log', (event, payload: unknown) => {
if (!isTrustedRendererSender(event.senderFrame)) return;
- if (!isWithinPayloadLimit(payload)) return;
const parsed = parseRendererLog(payload);
if (!parsed) return;
- writeLogEntry(parsed);
+ writeLogEntry(capPayload(parsed));
});
}
+/**
+ * Keep the head of an oversized entry instead of discarding it.
+ *
+ * Entries large enough to breach the limit are the ones worth having — a big
+ * error object, a failed response body — so dropping them silently removed the
+ * best evidence and left no sign that anything was missing.
+ */
+function capPayload(entry: LogSinkEntry): LogSinkEntry {
+ const size = payloadSize(entry.input);
+ if (size <= RENDERER_LOG_PAYLOAD_LIMIT) return entry;
+
+ const kept: unknown[] = [];
+ let used = 0;
+
+ for (const value of entry.input) {
+ const encoded = typeof value === 'string' ? value : stringifyLogValue(value);
+ const remaining = RENDERER_LOG_PAYLOAD_LIMIT - used;
+ if (remaining <= 0) break;
+
+ if (encoded.length <= remaining) {
+ kept.push(value);
+ used += encoded.length;
+ continue;
+ }
+
+ kept.push(`${encoded.slice(0, remaining)}…`);
+ break;
+ }
+
+ return {
+ ...entry,
+ input: [...kept, { truncated: { originalBytes: size, keptBytes: used } }],
+ };
+}
+
+function payloadSize(input: unknown[]): number {
+ try {
+ return input.reduce<number>(
+ (total, value) =>
+ total + (typeof value === 'string' ? value.length : stringifyLogValue(value).length),
+ 0
+ );
+ } catch {
+ return Number.POSITIVE_INFINITY;
+ }
+}
+
function isTrustedRendererSender(frame: Electron.WebFrameMain | null): boolean {
if (!frame) return false;
try {
@@ -178,14 +363,6 @@ function isTrustedRendererSender(frame: Electron.WebFrameMain | null): boolean {
}
}
-function isWithinPayloadLimit(payload: unknown): boolean {
- try {
- return JSON.stringify(payload).length <= RENDERER_LOG_PAYLOAD_LIMIT;
- } catch {
- return false;
- }
-}
-
async function rotateIfNeeded(path: string, incomingBytes: number) {
const current = await stat(path).catch(() => undefined);
if (!current || current.size + incomingBytes <= MAX_LOG_BYTES) return;
@@ -219,28 +396,60 @@ function parseRendererLog(payload: unknown): LogSinkEntry | undefined {
const record = payload as Record<string, unknown>;
if (!isLevel(record.level)) return undefined;
const input = Array.isArray(record.input) ? record.input : [record.input];
- return { level: record.level, source: 'renderer', input };
+ return {
+ level: record.level,
+ source: 'renderer',
+ input,
+ context: isLogContext(record.context) ? record.context : undefined,
+ };
+}
+
+function isLogContext(value: unknown): value is LogContext {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isLevel(value: unknown): value is Level {
return value === 'debug' || value === 'info' || value === 'warn' || value === 'error';
}
+/**
+ * The human-readable part of the line: the string arguments only.
+ *
+ * Structured arguments are recorded separately by `structuredArgs`, so keeping
+ * them out of here stops every entry from carrying the same payload twice —
+ * which at a 5 MiB rotation directly halves how much history is retained.
+ */
function formatMessage(input: unknown[]) {
- return input
- .map((value) => {
- if (typeof value === 'string') return value;
- if (value instanceof Error) return value.message;
- return stringifyLogValue(value);
- })
- .join(' ');
+ const strings = input.filter((value): value is string => typeof value === 'string');
+ if (strings.length) return strings.join(' ');
+
+ // A bare `log.error(err)` would otherwise produce an empty message; the error
+ // text is worth the small overlap with `data`.
+ const firstError = input.find((value) => value instanceof Error);
+ return firstError instanceof Error ? firstError.message : '';
+}
+
+function structuredArgs(input: unknown[]) {
+ const structured = input.filter((value) => typeof value !== 'string');
+ return structured.length ? structured.map(serializeLogValue) : undefined;
+}
+
+function omitEmptyContext(context: LogContext | undefined) {
+ if (!context) return undefined;
+ const entries = Object.entries(context).filter(([, value]) => value !== undefined);
+ return entries.length ? Object.fromEntries(entries) : undefined;
}
export function redactDiagnosticLog(value: string) {
return redactPii(redactSecrets(value));
}
-function redactSecrets(value: string) {
+/**
+ * Applied to every entry on the way to disk. Secrets are removed here and
+ * never recorded; personal data is left intact for local debugging and removed
+ * by `redactDiagnosticLog` at the point content leaves the machine.
+ */
+export function redactSecrets(value: string) {
return applyRedactions(value, SECRET_PATTERNS);
}
diff --git a/dash/apps/switchdash-desktop/src/main/lib/log-context.test.ts b/dash/apps/switchdash-desktop/src/main/lib/log-context.test.ts
new file mode 100644
index 000000000..6f108719d
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/lib/log-context.test.ts
@@ -0,0 +1,123 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import {
+ bindLogContext,
+ clearLogContextResolvers,
+ getRunId,
+ registerLogContextResolver,
+ resolveLogContext,
+ runWithLogContext,
+} from './log-context';
+
+beforeEach(() => {
+ clearLogContextResolvers();
+});
+
+describe('runWithLogContext', () => {
+ it('makes context visible to code that was never passed it', () => {
+ const deep = () => resolveLogContext(undefined);
+
+ const resolved = runWithLogContext({ sessionId: 'session-1' }, () => deep());
+
+ expect(resolved.sessionId).toBe('session-1');
+ });
+
+ it('survives await boundaries', async () => {
+ const resolved = await runWithLogContext({ sessionId: 'session-1' }, async () => {
+ await Promise.resolve();
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ return resolveLogContext(undefined);
+ });
+
+ expect(resolved.sessionId).toBe('session-1');
+ });
+
+ it('keeps concurrent scopes separate', async () => {
+ const run = (id: string) =>
+ runWithLogContext({ sessionId: id }, async () => {
+ await new Promise((resolve) => setTimeout(resolve, id === 'slow' ? 10 : 1));
+ return resolveLogContext(undefined).sessionId;
+ });
+
+ const [slow, fast] = await Promise.all([run('slow'), run('fast')]);
+
+ expect(slow).toBe('slow');
+ expect(fast).toBe('fast');
+ });
+
+ it('nests, with the inner scope winning', () => {
+ const resolved = runWithLogContext({ sessionId: 'outer', component: 'a' }, () =>
+ runWithLogContext({ sessionId: 'inner' }, () => resolveLogContext(undefined))
+ );
+
+ expect(resolved.sessionId).toBe('inner');
+ expect(resolved.component).toBe('a');
+ });
+
+ it('does not leak outside the scope', () => {
+ runWithLogContext({ sessionId: 'session-1' }, () => undefined);
+
+ expect(resolveLogContext(undefined).sessionId).toBeUndefined();
+ });
+});
+
+describe('bindLogContext', () => {
+ it('re-applies a captured scope to a callback invoked outside it', () => {
+ const callback = runWithLogContext({ sessionId: 'session-1' }, () =>
+ bindLogContext(() => resolveLogContext(undefined).sessionId)
+ );
+
+ expect(callback()).toBe('session-1');
+ });
+});
+
+describe('resolveLogContext', () => {
+ it('stamps every entry with the run id', () => {
+ expect(resolveLogContext(undefined).runId).toBe(getRunId());
+ });
+
+ it('prefers the entry context over the ambient scope', () => {
+ const resolved = runWithLogContext({ sessionId: 'ambient' }, () =>
+ resolveLogContext({ sessionId: 'explicit' })
+ );
+
+ expect(resolved.sessionId).toBe('explicit');
+ });
+
+ it('fills gaps from a registered resolver', () => {
+ registerLogContextResolver((context) =>
+ context.sessionId === 'session-1' ? { roomId: 'room-1', roomName: 'General' } : undefined
+ );
+
+ const resolved = resolveLogContext({ sessionId: 'session-1' });
+
+ expect(resolved.roomId).toBe('room-1');
+ expect(resolved.roomName).toBe('General');
+ });
+
+ it('never lets a resolver overwrite a value from the call site', () => {
+ registerLogContextResolver(() => ({ roomName: 'derived' }));
+
+ expect(resolveLogContext({ roomName: 'explicit' }).roomName).toBe('explicit');
+ });
+
+ it('lets a later resolver build on an earlier one', () => {
+ registerLogContextResolver(() => ({ agentId: 'agent-1' }));
+ registerLogContextResolver((context) =>
+ context.agentId === 'agent-1' ? { agentName: 'Ada' } : undefined
+ );
+
+ expect(resolveLogContext({ sessionId: 'session-1' }).agentName).toBe('Ada');
+ });
+
+ it('keeps the entry when a resolver throws', () => {
+ registerLogContextResolver(() => {
+ throw new Error('resolver exploded');
+ });
+ registerLogContextResolver(() => ({ roomId: 'room-1' }));
+
+ const resolved = resolveLogContext({ sessionId: 'session-1' });
+
+ expect(resolved.sessionId).toBe('session-1');
+ expect(resolved.roomId).toBe('room-1');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/lib/log-context.ts b/dash/apps/switchdash-desktop/src/main/lib/log-context.ts
new file mode 100644
index 000000000..791c5474f
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/lib/log-context.ts
@@ -0,0 +1,100 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { randomUUID } from 'node:crypto';
+import { mergeLogContext, type LogContext } from '@shared/logger';
+
+/**
+ * Ambient log context for the main process.
+ *
+ * Work started at an entry point (an RPC call, a PTY spawn, a sidecar launch)
+ * runs inside a scope carrying the ids that identify it. Code far below can
+ * then log without every intermediate signature having to forward a session id
+ * it has no other use for.
+ *
+ * This is deliberately confined to logging: nothing must *behave* differently
+ * based on ambient state, only report differently. Ambient state that changes
+ * behaviour is invisible coupling and far harder to reason about than a
+ * parameter.
+ */
+const storage = new AsyncLocalStorage<LogContext>();
+
+/** Identifies one app run, so a single launch can be isolated in a rotated log. */
+const runId = randomUUID();
+
+export function getRunId(): string {
+ return runId;
+}
+
+export function runWithLogContext<T>(context: LogContext, fn: () => T): T {
+ return storage.run(mergeLogContext(storage.getStore(), context) ?? context, fn);
+}
+
+/**
+ * Capture the current scope and re-apply it later.
+ *
+ * `AsyncLocalStorage` follows promises and timers but not every long-lived
+ * emitter: a stream or interval created inside a scope keeps that scope
+ * forever, which produces stale attribution once the work it belonged to is
+ * gone. Callbacks that outlive their originating operation should be bound
+ * explicitly rather than relying on propagation.
+ */
+export function bindLogContext<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R {
+ const captured = storage.getStore();
+ if (!captured) return fn;
+ return (...args: A) => storage.run(captured, () => fn(...args));
+}
+
+type LogContextResolver = (context: LogContext) => LogContext | undefined;
+
+const resolvers: LogContextResolver[] = [];
+
+/**
+ * Register a function that fills in fields derivable from the ids already on an
+ * entry — for example turning a session id into its room and agent.
+ *
+ * Registration (rather than a direct import) keeps the sink from depending on
+ * the services it enriches from, which would otherwise be a cycle: those
+ * services log.
+ */
+export function registerLogContextResolver(resolver: LogContextResolver): void {
+ resolvers.push(resolver);
+}
+
+/** Test seam; production code registers once at boot. */
+export function clearLogContextResolvers(): void {
+ resolvers.length = 0;
+}
+
+/**
+ * Merge ambient context, the entry's own context, and anything the registered
+ * resolvers can derive from it.
+ *
+ * Enrichment is best-effort by construction: a resolver that throws is skipped
+ * rather than allowed to take down the write. It must also stay synchronous —
+ * a logger that awaits a database read is a logger that deadlocks at shutdown.
+ */
+export function resolveLogContext(entry: LogContext | undefined): LogContext {
+ const resolved: LogContext = {
+ runId,
+ ...storage.getStore(),
+ ...entry,
+ };
+
+ for (const resolver of resolvers) {
+ try {
+ const derived = resolver(resolved);
+ if (!derived) continue;
+
+ // Only fill gaps: a value supplied at the call site is more specific than
+ // one derived from an id, so it is never overwritten.
+ for (const [key, value] of Object.entries(derived)) {
+ if (value === undefined) continue;
+ if (resolved[key as keyof LogContext] !== undefined) continue;
+ Object.assign(resolved, { [key]: value });
+ }
+ } catch {
+ // A broken resolver degrades the context; it must not lose the entry.
+ }
+ }
+
+ return resolved;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/lib/log-enrichment.ts b/dash/apps/switchdash-desktop/src/main/lib/log-enrichment.ts
new file mode 100644
index 000000000..c8a3d22ab
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/lib/log-enrichment.ts
@@ -0,0 +1,25 @@
+import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';
+import { registerLogContextResolver } from './log-context';
+import { lookupAgentName, lookupSessionTitle } from './log-name-cache';
+
+/**
+ * Teach the log sink how to expand the ids an entry already carries.
+ *
+ * Call sites thread at most a session id — everything else is derived here, in
+ * one place, so no intermediate function has to forward fields it does not
+ * otherwise use.
+ */
+export function registerLogEnrichment(): void {
+ // A live session already knows its room and agent; this costs a map lookup.
+ registerLogContextResolver((context) => {
+ if (!context.sessionId) return undefined;
+ return switchRoomService.describeSessionForLog(context.sessionId);
+ });
+
+ // Names for whichever ids ended up on the entry, including ids the resolver
+ // above just derived.
+ registerLogContextResolver((context) => ({
+ sessionTitle: lookupSessionTitle(context.sessionId),
+ agentName: lookupAgentName(context.agentId),
+ }));
+}
diff --git a/dash/apps/switchdash-desktop/src/main/lib/log-name-cache.ts b/dash/apps/switchdash-desktop/src/main/lib/log-name-cache.ts
new file mode 100644
index 000000000..0738ba02a
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/lib/log-name-cache.ts
@@ -0,0 +1,72 @@
+/**
+ * Remembers the human-readable name of entities the app has already loaded, so
+ * log entries can carry `sessionTitle` / `agentName` next to their ids.
+ *
+ * The cache is *pushed to*, never read through. Callers that already hold a
+ * record hand over the name they have; the logger only ever reads what is
+ * present. That keeps database access off the logging path entirely — a
+ * read-through cache would put a query behind every unresolved id, which on a
+ * write path that runs during shutdown and inside error handlers is a much
+ * worse trade than occasionally logging an id without its name.
+ */
+const MAX_ENTRIES = 256;
+
+class BoundedNameCache {
+ private readonly entries = new Map<string, string>();
+
+ note(id: string | undefined, name: string | undefined | null): void {
+ if (!id || !name) return;
+ // Re-insert so the most recently seen entries are the last to be evicted.
+ this.entries.delete(id);
+ this.entries.set(id, name);
+ if (this.entries.size > MAX_ENTRIES) {
+ const oldest = this.entries.keys().next();
+ if (!oldest.done) this.entries.delete(oldest.value);
+ }
+ }
+
+ lookup(id: string | undefined): string | undefined {
+ return id ? this.entries.get(id) : undefined;
+ }
+
+ forget(id: string): void {
+ this.entries.delete(id);
+ }
+
+ clear(): void {
+ this.entries.clear();
+ }
+}
+
+const sessionTitles = new BoundedNameCache();
+const agentNames = new BoundedNameCache();
+
+export function noteSessionTitle(id: string | undefined, title: string | undefined | null): void {
+ sessionTitles.note(id, title);
+}
+
+export function noteAgentName(id: string | undefined, name: string | undefined | null): void {
+ agentNames.note(id, name);
+}
+
+export function lookupSessionTitle(id: string | undefined): string | undefined {
+ return sessionTitles.lookup(id);
+}
+
+export function lookupAgentName(id: string | undefined): string | undefined {
+ return agentNames.lookup(id);
+}
+
+export function forgetSessionTitle(id: string): void {
+ sessionTitles.forget(id);
+}
+
+export function forgetAgentName(id: string): void {
+ agentNames.forget(id);
+}
+
+/** Test seam. */
+export function clearLogNameCaches(): void {
+ sessionTitles.clear();
+ agentNames.clear();
+}
diff --git a/dash/apps/switchdash-desktop/src/main/lib/logger.ts b/dash/apps/switchdash-desktop/src/main/lib/logger.ts
index 2d7bbf293..4e5200d84 100644
--- a/dash/apps/switchdash-desktop/src/main/lib/logger.ts
+++ b/dash/apps/switchdash-desktop/src/main/lib/logger.ts
@@ -1,10 +1,32 @@
-import { createLogger } from '@shared/logger';
+import { createLogger, resolveLogLevel } from '@shared/logger';
import { writeLogEntry } from './file-logger';
+import { resolveLogContext } from './log-context';
+
+/**
+ * The console and the file are levelled independently.
+ *
+ * A single level meant the file recorded exactly what the terminal did, so a
+ * shipped build — where the default is `warn` — kept only warnings and errors
+ * and none of the run that led to them. The file now defaults to `info` so a
+ * user's log has the story around a failure, while the console stays quiet
+ * unless asked otherwise.
+ */
+const fileLevel = resolveLogLevel({
+ envLevel: process.env.LOG_FILE_LEVEL ?? process.env.LOG_LEVEL ?? 'info',
+ debugFlag: process.argv.includes('--debug-logs'),
+});
export const log = createLogger({
envLevel: process.env.LOG_LEVEL,
debugFlag: process.argv.includes('--debug-logs'),
sink: writeLogEntry,
+ sinkLevel: fileLevel,
+ // Resolution is idempotent, and the sink resolves again so that renderer and
+ // sidecar entries are enriched the same way; doing it here as well is what
+ // lets the console show the same identity the file records.
+ contextProvider: () => resolveLogContext(undefined),
+ consoleContext: true,
+ onSinkError: (error) => console.error('Log sink failed:', error),
});
export type Logger = ReturnType<typeof createLogger>;
diff --git a/dash/apps/switchdash-desktop/src/main/lib/rpc-logging.ts b/dash/apps/switchdash-desktop/src/main/lib/rpc-logging.ts
new file mode 100644
index 000000000..573a42a1e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/lib/rpc-logging.ts
@@ -0,0 +1,54 @@
+import type { RPCInvocationWrapper } from '@shared/lib/ipc/rpc';
+import { serializeLogValue, type LogContext } from '@shared/logger';
+import { runWithLogContext } from './log-context';
+import { log } from './logger';
+
+/**
+ * Reads the ids an RPC call already carries in its arguments.
+ *
+ * Only `sessionId` is looked for: it is the one field the rest of the context
+ * can be derived from, and picking it up here means no handler below has to
+ * forward it purely so that a log line can mention it.
+ */
+function rpcLogContext(channel: string, args: unknown[]): LogContext {
+ const context: LogContext = { component: `rpc:${channel}` };
+
+ for (const arg of args) {
+ if (typeof arg !== 'object' || arg === null) continue;
+ const candidate = (arg as Record<string, unknown>).sessionId;
+ if (typeof candidate === 'string') {
+ context.sessionId = candidate;
+ break;
+ }
+ }
+
+ return context;
+}
+
+export const withRPCLogContext: RPCInvocationWrapper = (channel, args, invoke) =>
+ runWithLogContext(rpcLogContext(channel, args), () => {
+ try {
+ const result = invoke();
+ // A rejected handler surfaces in the renderer as a failed call with no
+ // record of why on this side, so the reason is captured here — the one
+ // point every call already passes through.
+ if (result instanceof Promise) {
+ return result.catch((error: unknown) => {
+ logRPCFailure(channel, error);
+ throw error;
+ });
+ }
+ return result;
+ } catch (error) {
+ logRPCFailure(channel, error);
+ throw error;
+ }
+ });
+
+function logRPCFailure(channel: string, error: unknown) {
+ log.error('RPC handler failed', {
+ event: 'rpc_failed',
+ component: `rpc:${channel}`,
+ error: serializeLogValue(error),
+ });
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/utils/logger.ts b/dash/apps/switchdash-desktop/src/renderer/utils/logger.ts
index 0f50f19b0..6713d2431 100644
--- a/dash/apps/switchdash-desktop/src/renderer/utils/logger.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/utils/logger.ts
@@ -1,11 +1,19 @@
import { createLogger, serializeLogValue, type LogSinkEntry } from '@shared/logger';
+/**
+ * `AsyncLocalStorage` is a Node API and has no browser equivalent, so the
+ * renderer cannot resolve ambient context the way the main process does.
+ * Instead it attaches whatever ids the call site knows via `log.child(...)`
+ * and leaves the rest to the main sink, which enriches every entry in one
+ * place regardless of which process it came from.
+ */
export const log = createLogger({
sink: (entry) => {
const safe: LogSinkEntry = {
level: entry.level,
input: entry.input.map(serializeLogValue),
source: entry.source,
+ context: entry.context,
};
window.electronAPI?.eventSend('switchdash:renderer-log', safe);
},
diff --git a/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.ts b/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.ts
index b39765be2..634c8bd9d 100644
--- a/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.ts
+++ b/dash/apps/switchdash-desktop/src/shared/lib/ipc/rpc.ts
@@ -22,23 +22,44 @@ export function createRPCRouter<T extends RouterMap>(routers: T): T {
return routers;
}
+/**
+ * Wraps a leaf handler invocation. Every RPC call funnels through here, which
+ * makes it the one place able to give the whole call tree beneath it an
+ * identity (see the main process's log context) without touching call sites.
+ */
+export type RPCInvocationWrapper = (
+ channel: string,
+ args: unknown[],
+ invoke: () => unknown
+) => unknown;
+
// Recursively walks the handler tree and registers every leaf function with
// ipcMain at its full dot-joined path (e.g. "git.commit", "git.worktree.commit").
-function registerHandlers(ipcMain: IpcMain, prefix: string, value: unknown): void {
+function registerHandlers(
+ ipcMain: IpcMain,
+ prefix: string,
+ value: unknown,
+ wrap: RPCInvocationWrapper | undefined
+): void {
if (typeof value === 'function') {
+ const handler = value as (...a: unknown[]) => unknown;
ipcMain.handle(prefix, (_event, ...args: unknown[]) =>
- (value as (...a: unknown[]) => unknown)(...args)
+ wrap ? wrap(prefix, args, () => handler(...args)) : handler(...args)
);
} else if (value !== null && typeof value === 'object') {
for (const [key, child] of Object.entries(value)) {
- registerHandlers(ipcMain, `${prefix}.${key}`, child);
+ registerHandlers(ipcMain, `${prefix}.${key}`, child, wrap);
}
}
}
-export function registerRPCRouter(router: RouterMap, ipcMain: IpcMain): void {
+export function registerRPCRouter(
+ router: RouterMap,
+ ipcMain: IpcMain,
+ wrap?: RPCInvocationWrapper
+): void {
for (const [ns, handlers] of Object.entries(router)) {
- registerHandlers(ipcMain, ns, handlers);
+ registerHandlers(ipcMain, ns, handlers, wrap);
}
}
diff --git a/dash/apps/switchdash-desktop/src/shared/logger.test.ts b/dash/apps/switchdash-desktop/src/shared/logger.test.ts
new file mode 100644
index 000000000..c30d3d74b
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/logger.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createLogger, formatContextForConsole, type LogSinkEntry } from './logger';
+
+function collect() {
+ const entries: LogSinkEntry[] = [];
+ return { entries, sink: (entry: LogSinkEntry) => entries.push(entry) };
+}
+
+describe('createLogger levels', () => {
+ it('records to the sink below the console level', () => {
+ const { entries, sink } = collect();
+ const log = createLogger({ envLevel: 'warn', sinkLevel: 'info', sink });
+
+ log.info('boot complete');
+
+ expect(entries).toHaveLength(1);
+ expect(entries[0]?.level).toBe('info');
+ });
+
+ it('keeps the console quiet while the sink records', () => {
+ const spy = vi.spyOn(console, 'info').mockImplementation(() => undefined);
+ const { sink } = collect();
+ const log = createLogger({ envLevel: 'warn', sinkLevel: 'info', sink });
+
+ log.info('boot complete');
+
+ expect(spy).not.toHaveBeenCalled();
+ spy.mockRestore();
+ });
+
+ it('drops entries below the sink level', () => {
+ const { entries, sink } = collect();
+ const log = createLogger({ envLevel: 'warn', sinkLevel: 'info', sink });
+
+ log.debug('noisy');
+
+ expect(entries).toHaveLength(0);
+ });
+
+ it('always records errors regardless of level', () => {
+ const { entries, sink } = collect();
+ const log = createLogger({ envLevel: 'error', sinkLevel: 'error', sink });
+
+ log.error('exploded');
+
+ expect(entries).toHaveLength(1);
+ });
+
+ it('defaults the sink level to the console level when unset', () => {
+ const log = createLogger({ envLevel: 'warn' });
+
+ expect(log.sinkLevel).toBe('warn');
+ });
+});
+
+describe('child loggers', () => {
+ it('attaches bound context to every entry', () => {
+ const { entries, sink } = collect();
+ const log = createLogger({ envLevel: 'debug', sink }).child({ component: 'updater' });
+
+ log.info('checking');
+
+ expect(entries[0]?.context).toMatchObject({ component: 'updater' });
+ });
+
+ it('merges nested children, innermost winning', () => {
+ const { entries, sink } = collect();
+ const log = createLogger({ envLevel: 'debug', sink })
+ .child({ component: 'updater', sessionId: 'session-1' })
+ .child({ component: 'updater:download' });
+
+ log.info('downloading');
+
+ expect(entries[0]?.context).toMatchObject({
+ component: 'updater:download',
+ sessionId: 'session-1',
+ });
+ });
+
+ it('does not mutate the parent logger', () => {
+ const { entries, sink } = collect();
+ const parent = createLogger({ envLevel: 'debug', sink });
+ parent.child({ component: 'child-only' });
+
+ parent.info('from parent');
+
+ expect(entries[0]?.context?.component).toBeUndefined();
+ });
+
+ it('lets bound context override the ambient provider', () => {
+ const { entries, sink } = collect();
+ const log = createLogger({
+ envLevel: 'debug',
+ sink,
+ contextProvider: () => ({ sessionId: 'ambient' }),
+ }).child({ sessionId: 'bound' });
+
+ log.info('hello');
+
+ expect(entries[0]?.context?.sessionId).toBe('bound');
+ });
+});
+
+describe('sink failures', () => {
+ it('reports rather than swallows them', () => {
+ const onSinkError = vi.fn();
+ const log = createLogger({
+ envLevel: 'debug',
+ sink: () => {
+ throw new Error('disk full');
+ },
+ onSinkError,
+ });
+
+ expect(() => log.info('hello')).not.toThrow();
+ expect(onSinkError).toHaveBeenCalledOnce();
+ });
+});
+
+describe('console context rendering', () => {
+ it('appends identity to console output when enabled', () => {
+ const spy = vi.spyOn(console, 'info').mockImplementation(() => undefined);
+ const log = createLogger({ envLevel: 'debug', consoleContext: true }).child({
+ component: 'hook-relay',
+ agentName: 'freebsd_vt',
+ sessionId: 'ac3bee1e-bb1d-47ba-809c-75ed35d46df7',
+ });
+
+ log.info('received events');
+
+ expect(spy).toHaveBeenCalledWith(
+ 'received events',
+ '[hook-relay agent=freebsd_vt session=ac3bee1e]'
+ );
+ spy.mockRestore();
+ });
+
+ it('stays silent about context when not enabled', () => {
+ const spy = vi.spyOn(console, 'info').mockImplementation(() => undefined);
+ const log = createLogger({ envLevel: 'debug' }).child({ component: 'hook-relay' });
+
+ log.info('received events');
+
+ expect(spy).toHaveBeenCalledWith('received events');
+ spy.mockRestore();
+ });
+
+ it('shows the name instead of the id when both are known', () => {
+ expect(formatContextForConsole({ agentId: 'abcdef12-3456', agentName: 'freebsd_vt' })).toBe(
+ '[agent=freebsd_vt]'
+ );
+ });
+
+ it('falls back to a shortened id when there is no name', () => {
+ expect(formatContextForConsole({ agentId: 'abcdef12-3456' })).toBe('[agent=abcdef12]');
+ });
+
+ it('renders nothing when there is nothing worth showing', () => {
+ expect(formatContextForConsole({ runId: 'only-a-run-id' })).toBe('');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/shared/logger.ts b/dash/apps/switchdash-desktop/src/shared/logger.ts
index 5ca22f01a..961b2d151 100644
--- a/dash/apps/switchdash-desktop/src/shared/logger.ts
+++ b/dash/apps/switchdash-desktop/src/shared/logger.ts
@@ -1,13 +1,57 @@
export type Level = 'debug' | 'info' | 'warn' | 'error';
+/**
+ * Structured fields attached to a log entry.
+ *
+ * Ids are the join key and names are decoration: names are mutable (a session
+ * can be renamed mid-run) so they record what the entity was called at write
+ * time and must never be used to correlate entries.
+ */
+export type LogContext = {
+ component?: string;
+ runId?: string;
+ sessionId?: string;
+ sessionTitle?: string;
+ agentId?: string;
+ agentName?: string;
+ agentSlug?: string;
+ roomId?: string;
+ roomName?: string;
+ event?: string;
+ stage?: string;
+ errorCode?: string;
+ durationMs?: number;
+ attempt?: number;
+};
+
export type LogSinkEntry = {
level: Level;
input: unknown[];
source?: string;
+ context?: LogContext;
};
export type LogSink = (entry: LogSinkEntry) => void;
+export type Logger = {
+ level: Level;
+ sinkLevel: Level;
+ debug: (...input: unknown[]) => void;
+ info: (...input: unknown[]) => void;
+ warn: (...input: unknown[]) => void;
+ error: (...input: unknown[]) => void;
+ child: (context: LogContext) => Logger;
+};
+
+export function mergeLogContext(
+ base: LogContext | undefined,
+ extra: LogContext | undefined
+): LogContext | undefined {
+ if (!base) return extra;
+ if (!extra) return base;
+ return { ...base, ...extra };
+}
+
export function serializeLogValue(value: unknown): unknown {
if (value instanceof Error) {
return {
@@ -60,32 +104,130 @@ export function resolveLogLevel(args?: { envLevel?: string; debugFlag?: boolean
return parseLogLevel(args?.envLevel) ?? (args?.debugFlag ? 'debug' : undefined) ?? 'warn';
}
-export function createLogger(args?: { envLevel?: string; debugFlag?: boolean; sink?: LogSink }) {
+export type CreateLoggerArgs = {
+ envLevel?: string;
+ debugFlag?: boolean;
+ sink?: LogSink;
+ /**
+ * Level for the sink, resolved independently of the console level. The
+ * console stays quiet by default while the file sink records the run, so a
+ * shipped build has usable history without a noisy terminal.
+ */
+ sinkLevel?: Level;
+ /** Ambient fields resolved at write time, merged under the entry's own context. */
+ contextProvider?: () => LogContext | undefined;
+ /**
+ * Append the resolved context to console output as well as to the sink.
+ *
+ * Off by default so shipped console output stays terse, but the terminal is
+ * where the app is actually watched during development — context that only
+ * reaches the log file is context nobody sees while working.
+ */
+ consoleContext?: boolean;
+ onSinkError?: (error: unknown) => void;
+};
+
+const CONSOLE_CONTEXT_KEYS: Array<keyof LogContext> = [
+ 'component',
+ 'event',
+ 'stage',
+ 'agentName',
+ 'agentSlug',
+ 'agentId',
+ 'sessionTitle',
+ 'sessionId',
+ 'roomName',
+ 'roomId',
+];
+
+const SHORTENED_ID_KEYS = new Set<keyof LogContext>(['agentId', 'sessionId', 'roomId']);
+
+/** Compact single-token rendering, e.g. `[sidecar-launcher agent=freebsd_vt session=ac3bee1e]`. */
+export function formatContextForConsole(context: LogContext): string {
+ const parts: string[] = [];
+
+ for (const key of CONSOLE_CONTEXT_KEYS) {
+ const value = context[key];
+ if (value === undefined || value === '') continue;
+
+ const text = String(value);
+ // Ids are for correlating against the log file, where they appear in full;
+ // the leading segment is enough to recognise one by eye.
+ const rendered = SHORTENED_ID_KEYS.has(key) ? text.slice(0, 8) : text;
+
+ // A name makes its id redundant at a glance, so only one of the pair shows.
+ if (key === 'agentId' && context.agentName) continue;
+ if (key === 'sessionId' && context.sessionTitle) continue;
+ if (key === 'roomId' && context.roomName) continue;
+
+ parts.push(key === 'component' ? rendered : `${consoleKey(key)}=${rendered}`);
+ }
+
+ return parts.length ? `[${parts.join(' ')}]` : '';
+}
+
+function consoleKey(key: keyof LogContext): string {
+ if (key === 'agentName' || key === 'agentSlug') return 'agent';
+ if (key === 'sessionTitle') return 'session';
+ if (key === 'roomName') return 'room';
+ if (key === 'sessionId') return 'session';
+ if (key === 'agentId') return 'agent';
+ if (key === 'roomId') return 'room';
+ return key;
+}
+
+export function createLogger(args?: CreateLoggerArgs): Logger {
const level = resolveLogLevel({
envLevel: args?.envLevel ?? import.meta.env?.VITE_LOG_LEVEL,
debugFlag: args?.debugFlag,
});
+ const sinkLevel = args?.sinkLevel ?? level;
- function enabled(target: Level): boolean {
- return ORDER[target] >= ORDER[level];
+ function enabled(target: Level, against: Level): boolean {
+ return ORDER[target] >= ORDER[against];
}
- function emit(target: Level, writer: (...input: unknown[]) => void, input: unknown[]) {
- if (target !== 'error' && !enabled(target)) return;
- writer(...input);
- if (!args?.sink) return;
- try {
- args.sink({ level: target, input });
- } catch {
- // Sink failures must never break the caller.
+ function build(bound: LogContext | undefined): Logger {
+ function emit(target: Level, writer: (...input: unknown[]) => void, input: unknown[]) {
+ // Errors are always recorded regardless of the configured level.
+ const always = target === 'error';
+ const toConsole = always || enabled(target, level);
+ const toSink = Boolean(args?.sink) && (always || enabled(target, sinkLevel));
+ if (!toConsole && !toSink) return;
+
+ const context = mergeLogContext(args?.contextProvider?.(), bound);
+
+ if (toConsole) {
+ const suffix = args?.consoleContext && context ? formatContextForConsole(context) : '';
+ writer(...(suffix ? [...input, suffix] : input));
+ }
+
+ if (!args?.sink || !toSink) return;
+
+ try {
+ args.sink({
+ level: target,
+ input,
+ context,
+ });
+ } catch (error) {
+ // Sink failures must never break the caller, but they must not be
+ // invisible either — a logger that silently stops recording is worse
+ // than no logger at all.
+ args.onSinkError?.(error);
+ }
}
+
+ return {
+ level,
+ sinkLevel,
+ debug: (...input: unknown[]) => emit('debug', console.debug, input),
+ info: (...input: unknown[]) => emit('info', console.info, input),
+ warn: (...input: unknown[]) => emit('warn', console.warn, input),
+ error: (...input: unknown[]) => emit('error', console.error, input),
+ child: (context: LogContext) => build(mergeLogContext(bound, context)),
+ };
}
- return {
- level,
- debug: (...input: unknown[]) => emit('debug', console.debug, input),
- info: (...input: unknown[]) => emit('info', console.info, input),
- warn: (...input: unknown[]) => emit('warn', console.warn, input),
- error: (...input: unknown[]) => emit('error', console.error, input),
- };
+ return build(undefined);
}