Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ VITE_POSTHOG_API_HOST=xxx
VITE_POSTHOG_UI_HOST=xxx

# Use new LLM gateway locally (experimental, needs to be started in mprocs)
LLM_GATEWAY_URL=http://localhost:3308
LLM_GATEWAY_URL=http://localhost:3308

# Whether all errors/warnings show as dismissable toasts in dev
VITE_DEV_ERROR_TOASTS=true
1 change: 1 addition & 0 deletions apps/array/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@
"radix-themes-tw": "0.2.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-error-boundary": "^6.0.0",
"react-hook-form": "^7.64.0",
"react-hotkeys-hook": "^4.4.4",
"react-markdown": "^10.1.0",
Expand Down
2 changes: 2 additions & 0 deletions apps/array/src/main/di/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { ShellService } from "../services/shell/service.js";
import { TaskLinkService } from "../services/task-link/service.js";
import { UIService } from "../services/ui/service.js";
import { UpdatesService } from "../services/updates/service.js";
import { UserNotificationService } from "../services/user-notification/service.js";
import { WorkspaceService } from "../services/workspace/service.js";
import { MAIN_TOKENS } from "./tokens.js";

Expand All @@ -35,4 +36,5 @@ container.bind(MAIN_TOKENS.ShellService).to(ShellService);
container.bind(MAIN_TOKENS.UIService).to(UIService);
container.bind(MAIN_TOKENS.UpdatesService).to(UpdatesService);
container.bind(MAIN_TOKENS.TaskLinkService).to(TaskLinkService);
container.bind(MAIN_TOKENS.UserNotificationService).to(UserNotificationService);
container.bind(MAIN_TOKENS.WorkspaceService).to(WorkspaceService);
1 change: 1 addition & 0 deletions apps/array/src/main/di/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ export const MAIN_TOKENS = Object.freeze({
UpdatesService: Symbol.for("Main.UpdatesService"),
TaskLinkService: Symbol.for("Main.TaskLinkService"),
WorkspaceService: Symbol.for("Main.WorkspaceService"),
UserNotificationService: Symbol.for("Main.UserNotificationService"),
});
5 changes: 4 additions & 1 deletion apps/array/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import { mkdirSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { initializeMainErrorHandling } from "./lib/error-handling.js";

initializeMainErrorHandling();

import {
app,
BrowserWindow,
Expand All @@ -17,7 +21,6 @@ import {
shell,
} from "electron";
import { createIPCHandler } from "trpc-electron/main";
import "./lib/logger";
import { ANALYTICS_EVENTS } from "../types/analytics.js";
import { container } from "./di/container.js";
import { MAIN_TOKENS } from "./di/tokens.js";
Expand Down
20 changes: 20 additions & 0 deletions apps/array/src/main/lib/error-handling.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ipcMain } from "electron";
import { logger } from "./logger.js";

export function initializeMainErrorHandling(): void {
process.on("uncaughtException", (error) => {
logger.error("Uncaught exception", error);
});

process.on("unhandledRejection", (reason) => {
const error = reason instanceof Error ? reason : new Error(String(reason));
logger.error("Unhandled rejection", error);
});

ipcMain.on(
"preload-error",
(_, error: { message: string; stack?: string }) => {
logger.error("Preload error", error);
},
);
}
30 changes: 4 additions & 26 deletions apps/array/src/main/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,15 @@
import type { Logger, ScopedLogger } from "@shared/lib/create-logger.js";
import { createLogger } from "@shared/lib/create-logger.js";
import { app } from "electron";
import log from "electron-log/main";

// Initialize IPC transport to forward main process logs to renderer dev tools
log.initialize();

// Set levels - use debug in dev (check NODE_ENV since app.isPackaged may not be ready)
const isDev = process.env.NODE_ENV === "development" || !app.isPackaged;
const level = isDev ? "debug" : "info";
log.transports.file.level = level;
log.transports.console.level = level;
// IPC transport needs level set separately
log.transports.ipc.level = level;

export const logger = {
info: (message: string, ...args: unknown[]) => log.info(message, ...args),
warn: (message: string, ...args: unknown[]) => log.warn(message, ...args),
error: (message: string, ...args: unknown[]) => log.error(message, ...args),
debug: (message: string, ...args: unknown[]) => log.debug(message, ...args),

scope: (name: string) => {
const scoped = log.scope(name);
return {
info: (message: string, ...args: unknown[]) =>
scoped.info(message, ...args),
warn: (message: string, ...args: unknown[]) =>
scoped.warn(message, ...args),
error: (message: string, ...args: unknown[]) =>
scoped.error(message, ...args),
debug: (message: string, ...args: unknown[]) =>
scoped.debug(message, ...args),
};
},
};

export type Logger = typeof logger;
export type ScopedLogger = ReturnType<typeof logger.scope>;
export const logger = createLogger(log);
export type { Logger, ScopedLogger };
17 changes: 17 additions & 0 deletions apps/array/src/main/preload.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
import { ipcRenderer } from "electron";
import { exposeElectronTRPC } from "trpc-electron/main";
import "electron-log/preload";

// No TRPC available, so just use IPC
process.on("uncaughtException", (error) => {
ipcRenderer.send("preload-error", {
message: error.message,
stack: error.stack,
});
});

process.on("unhandledRejection", (reason) => {
const error = reason instanceof Error ? reason : new Error(String(reason));
ipcRenderer.send("preload-error", {
message: error.message,
stack: error.stack,
});
});

process.once("loaded", async () => {
exposeElectronTRPC();
});
15 changes: 15 additions & 0 deletions apps/array/src/main/services/user-notification/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const UserNotificationEvent = {
Notify: "notify",
} as const;

export type NotificationSeverity = "error" | "warning" | "info";

export interface UserNotificationPayload {
severity: NotificationSeverity;
title: string;
description?: string;
}

export interface UserNotificationEvents {
[UserNotificationEvent.Notify]: UserNotificationPayload;
}
46 changes: 46 additions & 0 deletions apps/array/src/main/services/user-notification/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { app } from "electron";
import { injectable, postConstruct } from "inversify";
import { logger } from "../../lib/logger.js";
import { TypedEventEmitter } from "../../lib/typed-event-emitter.js";
import {
UserNotificationEvent,
type UserNotificationEvents,
} from "./schemas.js";

const isDev = process.env.NODE_ENV === "development" || !app.isPackaged;
const devErrorToastsEnabled =
isDev && process.env.VITE_DEV_ERROR_TOASTS !== "false";

@injectable()
export class UserNotificationService extends TypedEventEmitter<UserNotificationEvents> {
@postConstruct()
init(): void {
if (devErrorToastsEnabled) {
logger.setDevToastEmitter((title, desc) => this.error(title, desc));
}
}

error(title: string, description?: string): void {
this.emit(UserNotificationEvent.Notify, {
severity: "error",
title,
description,
});
}

warning(title: string, description?: string): void {
this.emit(UserNotificationEvent.Notify, {
severity: "warning",
title,
description,
});
}

info(title: string, description?: string): void {
this.emit(UserNotificationEvent.Notify, {
severity: "info",
title,
description,
});
}
}
2 changes: 2 additions & 0 deletions apps/array/src/main/trpc/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { secureStoreRouter } from "./routers/secure-store.js";
import { shellRouter } from "./routers/shell.js";
import { uiRouter } from "./routers/ui.js";
import { updatesRouter } from "./routers/updates.js";
import { userNotificationRouter } from "./routers/user-notification.js";
import { workspaceRouter } from "./routers/workspace.js";
import { router } from "./trpc.js";

Expand All @@ -35,6 +36,7 @@ export const trpcRouter = router({
shell: shellRouter,
ui: uiRouter,
updates: updatesRouter,
userNotification: userNotificationRouter,
deepLink: deepLinkRouter,
workspace: workspaceRouter,
});
Expand Down
20 changes: 20 additions & 0 deletions apps/array/src/main/trpc/routers/user-notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { container } from "../../di/container.js";
import { MAIN_TOKENS } from "../../di/tokens.js";
import { UserNotificationEvent } from "../../services/user-notification/schemas.js";
import type { UserNotificationService } from "../../services/user-notification/service.js";
import { publicProcedure, router } from "../trpc.js";

const getService = () =>
container.get<UserNotificationService>(MAIN_TOKENS.UserNotificationService);

export const userNotificationRouter = router({
onNotify: publicProcedure.subscription(async function* (opts) {
const service = getService();
const iterable = service.toIterable(UserNotificationEvent.Notify, {
signal: opts.signal,
});
for await (const data of iterable) {
yield data;
}
}),
});
21 changes: 9 additions & 12 deletions apps/array/src/renderer/App.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ErrorBoundary } from "@components/ErrorBoundary";
import { MainLayout } from "@components/MainLayout";
import { AuthScreen } from "@features/auth/components/AuthScreen";
import { useAuthStore } from "@features/auth/stores/authStore";
import { useUserNotifications } from "@hooks/useUserNotifications";
import { Flex, Spinner, Text } from "@radix-ui/themes";
import { initializePostHog } from "@renderer/lib/analytics";
import { trpcVanilla } from "@renderer/trpc/client";
import { toast } from "@utils/toast";
import { useEffect, useState } from "react";

function App() {
Expand All @@ -16,15 +16,8 @@ function App() {
initializePostHog();
}, []);

// Global workspace error listener for toasts
useEffect(() => {
const subscription = trpcVanilla.workspace.onError.subscribe(undefined, {
onData: (data) => {
toast.error("Workspace error", { description: data.message });
},
});
return () => subscription.unsubscribe();
}, []);
// Global notification listener - handles all main process notifications
useUserNotifications();

useEffect(() => {
initializeOAuth().finally(() => setIsLoading(false));
Expand All @@ -41,7 +34,11 @@ function App() {
);
}

return isAuthenticated ? <MainLayout /> : <AuthScreen />;
return (
<ErrorBoundary>
{isAuthenticated ? <MainLayout /> : <AuthScreen />}
</ErrorBoundary>
);
}

export default App;
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { buildApiFetcher } from "@api/fetcher";
import { createApiClient, type Schemas } from "@api/generated";
import type { AgentEvent } from "@posthog/agent";
import { logger } from "@renderer/lib/logger";
import type { Task, TaskRun } from "@shared/types";
import type { StoredLogEntry } from "@shared/types/session-events";
import { buildApiFetcher } from "./fetcher";
import { createApiClient, type Schemas } from "./generated";

const log = logger.scope("posthog-client");

Expand Down
56 changes: 56 additions & 0 deletions apps/array/src/renderer/components/ErrorBoundary.tsx
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should just render the error in the screen instead of a toast if it triggers the error boundary.

Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Button, Card, Flex, Text } from "@radix-ui/themes";
import { logger } from "@renderer/lib/logger";
import type { ReactNode } from "react";
import { ErrorBoundary as ReactErrorBoundary } from "react-error-boundary";

interface Props {
children: ReactNode;
fallback?: ReactNode;
}

function DefaultFallback({
error,
onReset,
}: {
error: Error;
onReset: () => void;
}) {
return (
<Flex align="center" justify="center" minHeight="100vh" p="4">
<Card size="3" style={{ maxWidth: 400 }}>
<Flex direction="column" align="center" gap="4" p="4">
<Text size="3" weight="bold" align="center">
Something went wrong
</Text>
<Text size="2" color="gray" align="center">
{error.message}
</Text>
<Button onClick={onReset} variant="soft">
Try again
</Button>
</Flex>
</Card>
</Flex>
);
}

export function ErrorBoundary({ children, fallback }: Props) {
return (
<ReactErrorBoundary
fallbackRender={({ error, resetErrorBoundary }) =>
fallback ?? (
<DefaultFallback error={error} onReset={resetErrorBoundary} />
)
}
onError={(error, info) => {
logger.error("React error boundary caught error", {
error: error.message,
stack: error.stack,
componentStack: info.componentStack,
});
}}
>
{children}
</ReactErrorBoundary>
);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PostHogAPIClient } from "@api/posthogClient";
import { PostHogAPIClient } from "@renderer/api/posthogClient";
import { identifyUser, resetUser, track } from "@renderer/lib/analytics";
import { electronStorage } from "@renderer/lib/electronStorage";
import { logger } from "@renderer/lib/logger";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { PostHogAPIClient } from "@api/posthogClient";
import { useAuthStore } from "@features/auth/stores/authStore";
import type { PostHogAPIClient } from "@renderer/api/posthogClient";
import type {
UseMutationOptions,
UseMutationResult,
Expand Down
2 changes: 1 addition & 1 deletion apps/array/src/renderer/hooks/useAuthenticatedQuery.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { PostHogAPIClient } from "@api/posthogClient";
import { useAuthStore } from "@features/auth/stores/authStore";
import type { PostHogAPIClient } from "@renderer/api/posthogClient";
import type {
QueryKey,
UseQueryOptions,
Expand Down
20 changes: 20 additions & 0 deletions apps/array/src/renderer/hooks/useUserNotifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { trpcReact } from "@renderer/trpc/client";
import { toast } from "@utils/toast";

export function useUserNotifications() {
trpcReact.userNotification.onNotify.useSubscription(undefined, {
onData: ({ severity, title, description }) => {
switch (severity) {
case "error":
toast.error(title, { description });
break;
case "warning":
toast.warning(title, { description });
break;
case "info":
toast.info(title, description);
break;
}
},
});
}
Loading