Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): start workspace server on demand (#93382)

Alessandro Pogliaghi0791ff8967f7
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.ts
index 3d80c5653a3c..593482a7878f 100644
--- a/products/desktop/apps/code/src/main/di/bindings.ts
+++ b/products/desktop/apps/code/src/main/di/bindings.ts
@@ -26,6 +26,10 @@ import type {
FocusWorkspaceClient,
FocusWorktreePaths,
} from "@posthog/core/focus/host-focus";
+import type {
+ FOCUS_SERVICE,
+ IFocusService,
+} from "@posthog/core/focus/identifiers";
import type {
GitWorkspaceLookup,
HostGitWorkspaceClient,
@@ -136,7 +140,10 @@ import type {
} from "@posthog/quick-ask/service/quick-ask";
import type { WorkspaceClient } from "@posthog/workspace-client/client";
import type { DatabaseService } from "@posthog/workspace-server/db/service";
-import type { GIT_SERVICE as WS_GIT_SERVICE } from "@posthog/workspace-server/di/tokens";
+import type {
+ CONNECTIVITY_SERVICE as WS_CONNECTIVITY_SERVICE,
+ GIT_SERVICE as WS_GIT_SERVICE,
+} from "@posthog/workspace-server/di/tokens";
import type { AgentService } from "@posthog/workspace-server/services/agent/agent";
import type {
AGENT_AUTH,
@@ -156,6 +163,7 @@ import type {
} from "@posthog/workspace-server/services/archive/ports";
import type { AUTH_PROXY_AUTH } from "@posthog/workspace-server/services/auth-proxy/identifiers";
import type { AuthProxyAuth } from "@posthog/workspace-server/services/auth-proxy/ports";
+import type { ConnectivityService } from "@posthog/workspace-server/services/connectivity/service";
import type {
ENRICHMENT_AUTH,
ENRICHMENT_FILE_READER,
@@ -247,7 +255,6 @@ import type { AppLifecycleService } from "../services/app-lifecycle/service";
import type {
AuthPreferencePortAdapter,
AuthSessionPortAdapter,
- ConnectivityPortAdapter,
OAuthFlowPortAdapter,
TokenCipherPortAdapter,
} from "../services/auth/port-adapters";
@@ -368,7 +375,7 @@ export interface MainBindings {
[AUTH_PREFERENCE_STORE]: AuthPreferencePortAdapter;
[AUTH_OAUTH_FLOW_SERVICE]: OAuthFlowPortAdapter;
[AUTH_TOKEN_CIPHER]: TokenCipherPortAdapter;
- [AUTH_CONNECTIVITY]: ConnectivityPortAdapter;
+ [AUTH_CONNECTIVITY]: ConnectivityService;
[AUTH_TOKEN_OVERRIDE]: string | null;
[MAIN_AUTH_SERVICE]: AuthService;
[AUTH_SERVICE]: AuthService;
@@ -493,6 +500,7 @@ export interface MainBindings {
// ws-server git service (bound to(GitService))
[WS_GIT_SERVICE]: GitService;
+ [WS_CONNECTIVITY_SERVICE]: ConnectivityService;
// index.ts runtime bindings
[MAIN_WORKSPACE_CLIENT]: WorkspaceClient;
@@ -504,6 +512,7 @@ export interface MainBindings {
[FOCUS_WORKSPACE_CLIENT]: FocusWorkspaceClient;
[FOCUS_SESSION_STORE]: FocusSessionStore;
[FOCUS_WORKTREE_PATHS]: FocusWorktreePaths;
+ [FOCUS_SERVICE]: IFocusService;
[MAIN_FS_SERVICE]: FsCapability;
[FS_SERVICE]: FsCapability;
diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.ts
index bd315058bb24..b6fb62fa89a5 100644
--- a/products/desktop/apps/code/src/main/di/container.ts
+++ b/products/desktop/apps/code/src/main/di/container.ts
@@ -93,6 +93,7 @@ import { USAGE_HOST } from "@posthog/core/usage/identifiers";
import { usageMonitorModule } from "@posthog/core/usage/usage-monitor.module";
import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
import { listFilesContainingText } from "@posthog/git/queries";
+import { CONNECTIVITY_CLIENT } from "@posthog/host-router/ports/connectivity-client";
import {
GIT_PR_STATUS_PROVIDER,
type IGitPrStatus,
@@ -138,7 +139,10 @@ import {
WORKTREE_REPOSITORY,
} from "@posthog/workspace-server/db/identifiers";
import { repositoriesModule } from "@posthog/workspace-server/db/repositories.module";
-import { GIT_SERVICE as WS_GIT_SERVICE } from "@posthog/workspace-server/di/tokens";
+import {
+ CONNECTIVITY_SERVICE as WS_CONNECTIVITY_SERVICE,
+ GIT_SERVICE as WS_GIT_SERVICE,
+} from "@posthog/workspace-server/di/tokens";
import { additionalDirectoriesModule } from "@posthog/workspace-server/services/additional-directories/additional-directories.module";
import type { AgentService } from "@posthog/workspace-server/services/agent/agent";
import { agentModule } from "@posthog/workspace-server/services/agent/agent.module";
@@ -160,6 +164,7 @@ import { authProxyModule } from "@posthog/workspace-server/services/auth-proxy/a
import { AUTH_PROXY_AUTH } from "@posthog/workspace-server/services/auth-proxy/identifiers";
import { browserTabsModule } from "@posthog/workspace-server/services/browser-tabs/browser-tabs.module";
import { claudeCliSessionsModule } from "@posthog/workspace-server/services/claude-cli-sessions/claude-cli-sessions.module";
+import { ConnectivityService } from "@posthog/workspace-server/services/connectivity/service";
import { enrichmentModule } from "@posthog/workspace-server/services/enrichment/enrichment.module";
import {
ENRICHMENT_AUTH,
@@ -257,7 +262,6 @@ import { AppLifecycleService } from "../services/app-lifecycle/service";
import {
AuthPreferencePortAdapter,
AuthSessionPortAdapter,
- ConnectivityPortAdapter,
OAuthFlowPortAdapter,
TokenCipherPortAdapter,
} from "../services/auth/port-adapters";
@@ -398,7 +402,12 @@ container.bind(AUTH_SESSION_STORE).to(AuthSessionPortAdapter);
container.bind(AUTH_PREFERENCE_STORE).to(AuthPreferencePortAdapter);
container.bind(AUTH_OAUTH_FLOW_SERVICE).to(OAuthFlowPortAdapter);
container.bind(AUTH_TOKEN_CIPHER).to(TokenCipherPortAdapter);
-container.bind(AUTH_CONNECTIVITY).to(ConnectivityPortAdapter);
+container
+ .bind(WS_CONNECTIVITY_SERVICE)
+ .to(ConnectivityService)
+ .inSingletonScope();
+container.bind(AUTH_CONNECTIVITY).toService(WS_CONNECTIVITY_SERVICE);
+container.bind(CONNECTIVITY_CLIENT).toService(WS_CONNECTIVITY_SERVICE);
container
.bind(AUTH_TOKEN_OVERRIDE)
.toConstantValue(process.env.VITE_POSTHOG_ACCESS_TOKEN_OVERRIDE ?? null);
@@ -707,10 +716,9 @@ container
};
});
container.bind(WORKSPACE_FOCUS).toDynamicValue((ctx): WorkspaceFocus => {
- const focus = ctx.get(FocusHostService);
return {
onBranchRenamed: (handler) =>
- focus.on(FocusServiceEvent.BranchRenamed, handler),
+ ctx.get(FocusHostService).on(FocusServiceEvent.BranchRenamed, handler),
};
});
container
diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.ts
index 02a4c282e133..f44c3bc237bc 100644
--- a/products/desktop/apps/code/src/main/index.ts
+++ b/products/desktop/apps/code/src/main/index.ts
@@ -2,7 +2,7 @@ import "reflect-metadata";
import os from "node:os";
import { TypedEventEmitter } from "@posthog/shared";
import type { WorkspaceClient } from "@posthog/workspace-client/client";
-import { createReconnectingWorkspaceClient } from "@posthog/workspace-client/client";
+import { createLazyWorkspaceClient } from "@posthog/workspace-client/client";
import type { FileWatcherEvent } from "@posthog/workspace-client/types";
import { app, BrowserWindow, dialog, session } from "electron";
import log from "electron-log/main";
@@ -15,6 +15,10 @@ import {
FOCUS_WORKSPACE_CLIENT,
FOCUS_WORKTREE_PATHS,
} from "@posthog/core/focus/host-focus";
+import {
+ FOCUS_SERVICE,
+ type IFocusService,
+} from "@posthog/core/focus/identifiers";
import { GIT_WORKSPACE_CLIENT } from "@posthog/core/git/identifiers";
import type { GitHubIntegrationService } from "@posthog/core/integrations/github";
import {
@@ -34,7 +38,6 @@ import type { NotificationService } from "@posthog/core/notification/notificatio
import { OAUTH_SERVICE } from "@posthog/core/oauth/identifiers";
import type { OAuthService } from "@posthog/core/oauth/oauth";
import type { UpdatesService } from "@posthog/core/updates/updates";
-import { CONNECTIVITY_CLIENT } from "@posthog/host-router/ports/connectivity-client";
import { ENVIRONMENT_CLIENT } from "@posthog/host-router/ports/environment-client";
import { FILE_WATCHER_CONTROL } from "@posthog/host-router/ports/file-watcher-control";
import { DISK_CACHE_SERVICE } from "@posthog/platform/disk-cache";
@@ -282,6 +285,7 @@ async function initializeServices(): Promise<void> {
initDevToolbar();
container.get<DatabaseService>(DATABASE_SERVICE);
+ container.get<WorkspaceService>(WORKSPACE_SERVICE).initBranchWatcher();
container.get<OAuthService>(OAUTH_SERVICE);
const authService = container.get<AuthService>(AUTH_SERVICE);
container.get<NotificationService>(NOTIFICATION_SERVICE);
@@ -304,10 +308,6 @@ async function initializeServices(): Promise<void> {
await authService.initialize();
- // Initialize workspace branch watcher for live branch rename detection
- const workspaceService = container.get<WorkspaceService>(WORKSPACE_SERVICE);
- workspaceService.initBranchWatcher();
-
const suspensionService =
container.get<SuspensionService>(SUSPENSION_SERVICE);
suspensionService.startInactivityChecker();
@@ -386,18 +386,11 @@ async function boot(): Promise<void> {
const wsServer = container.get<WorkspaceServerService>(
WORKSPACE_SERVER_SERVICE,
);
- const workspaceServerStart = wsServer.start().catch((error: unknown) => {
- log.error("workspace-server failed to start", error);
- });
- // The workspace-server child respawns on a new port/secret after a crash;
- // a reconnecting client follows the current connection so main-process
- // callers don't keep hitting the dead port for the rest of the session.
- const workspaceClient = createReconnectingWorkspaceClient(() =>
- wsServer.getConnection(),
+ const workspaceClient = createLazyWorkspaceClient(async () =>
+ wsServer.getOrStart(),
);
container.bind(WORKSPACE_CLIENT).toConstantValue(workspaceClient);
container.bind(GIT_WORKSPACE_CLIENT).toConstantValue(workspaceClient);
- container.bind(CONNECTIVITY_CLIENT).toConstantValue(workspaceClient);
container.bind(ENVIRONMENT_CLIENT).toConstantValue(workspaceClient);
const fileWatcherBridge = new FileWatcherBridge(workspaceClient);
// Re-establish live watches after a workspace-server respawn — the old SSE
@@ -405,6 +398,7 @@ async function boot(): Promise<void> {
wsServer.on(WorkspaceServerEvent.StatusChanged, ({ status }) => {
if (status === WorkspaceServerStatus.Ready) {
fileWatcherBridge.resubscribeAll();
+ container.get<IFocusService>(FOCUS_SERVICE).resubscribeEvents();
}
});
container.bind(FILE_WATCHER_SERVICE).toConstantValue(fileWatcherBridge);
@@ -451,7 +445,6 @@ async function boot(): Promise<void> {
// The hidden quick-ask panel must not keep the app alive after the main
// window closes.
onMainWindowClosed(destroyQuickAskWindow);
- await workspaceServerStart;
if (shutdownStarted) return;
await initializeServices();
initializeDeepLinks();
diff --git a/products/desktop/apps/code/src/main/services/auth/port-adapters.test.ts b/products/desktop/apps/code/src/main/services/auth/port-adapters.test.ts
deleted file mode 100644
index 58712a15f87c..000000000000
--- a/products/desktop/apps/code/src/main/services/auth/port-adapters.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { WorkspaceClient } from "@posthog/workspace-client/client";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import {
- WorkspaceServerEvent,
- WorkspaceServerService,
- WorkspaceServerStatus,
-} from "../workspace-server/service";
-import { ConnectivityPortAdapter } from "./port-adapters";
-
-describe("ConnectivityPortAdapter", () => {
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it("waits for the workspace server before subscribing", () => {
- const unsubscribe = vi.fn();
- const subscribe = vi.fn(() => ({ unsubscribe }));
- const getStatus = vi.fn().mockResolvedValue({ isOnline: true });
- const workspace = {
- connectivity: {
- onStatusChange: { subscribe },
- getStatus: { query: getStatus },
- },
- } as unknown as WorkspaceClient;
- const workspaceServer = new WorkspaceServerService();
-
- const adapter = new ConnectivityPortAdapter(workspace, workspaceServer);
-
- expect(subscribe).not.toHaveBeenCalled();
- expect(getStatus).not.toHaveBeenCalled();
-
- workspaceServer.emit(WorkspaceServerEvent.StatusChanged, {
- status: WorkspaceServerStatus.Ready,
- attempt: 0,
- });
-
- expect(subscribe).toHaveBeenCalledOnce();
- expect(getStatus).toHaveBeenCalledOnce();
-
- adapter.dispose();
- expect(unsubscribe).toHaveBeenCalledOnce();
- });
-});
diff --git a/products/desktop/apps/code/src/main/services/auth/port-adapters.ts b/products/desktop/apps/code/src/main/services/auth/port-adapters.ts
index 0ec2efd5ea14..7d51f3951adf 100644
--- a/products/desktop/apps/code/src/main/services/auth/port-adapters.ts
+++ b/products/desktop/apps/code/src/main/services/auth/port-adapters.ts
@@ -2,8 +2,6 @@ import type {
AuthOrgProjectPreferenceRecord,
AuthPreferenceRecord,
AuthSessionRecord,
- ConnectivityStatus,
- IAuthConnectivity,
IAuthOAuthFlowService,
IAuthPreferenceStore,
IAuthSessionStore,
@@ -18,22 +16,14 @@ import type {
import { OAUTH_SERVICE } from "@posthog/core/oauth/identifiers";
import type { OAuthService } from "@posthog/core/oauth/oauth";
import type { CloudRegion } from "@posthog/shared";
-import type { WorkspaceClient } from "@posthog/workspace-client/client";
import type { IAuthPreferenceRepository } from "@posthog/workspace-server/db/repositories/auth-preference-repository";
import type { IAuthSessionRepository } from "@posthog/workspace-server/db/repositories/auth-session-repository";
import { inject, injectable } from "inversify";
import {
AUTH_PREFERENCE_REPOSITORY,
AUTH_SESSION_REPOSITORY,
- WORKSPACE_CLIENT,
- WORKSPACE_SERVER_SERVICE,
} from "../../di/tokens";
import { decrypt, encrypt } from "../../utils/encryption";
-import {
- WorkspaceServerEvent,
- type WorkspaceServerService,
- WorkspaceServerStatus,
-} from "../workspace-server/service";
@injectable()
export class TokenCipherPortAdapter implements IAuthTokenCipher {
@@ -150,74 +140,3 @@ export class AuthPreferencePortAdapter implements IAuthPreferenceStore {
this.repository.saveOrgProject(input);
}
}
-
-@injectable()
-export class ConnectivityPortAdapter implements IAuthConnectivity {
- private isOnline = true;
- private readonly handlers = new Set<(status: ConnectivityStatus) => void>();
- private sub: { unsubscribe: () => void } | null = null;
- private readonly onServerStatusChanged = ({
- status,
- }: {
- status: WorkspaceServerStatus;
- }): void => {
- if (status === WorkspaceServerStatus.Ready) this.subscribe();
- };
-
- constructor(
- @inject(WORKSPACE_CLIENT)
- private readonly workspace: WorkspaceClient,
- @inject(WORKSPACE_SERVER_SERVICE)
- private readonly workspaceServer: WorkspaceServerService,
- ) {
- // The workspace-server child respawns on a new port after a crash; the
- // old SSE subscription keeps retrying the dead port forever, so re-
- // establish it against the current connection once the server is healthy.
- this.workspaceServer.on(
- WorkspaceServerEvent.StatusChanged,
- this.onServerStatusChanged,
- );
- if (this.workspaceServer.getStatus() === WorkspaceServerStatus.Ready) {
- this.subscribe();
- }
- }
-
- dispose(): void {
- this.workspaceServer.off(
- WorkspaceServerEvent.StatusChanged,
- this.onServerStatusChanged,
- );
- this.sub?.unsubscribe();
- this.sub = null;
- }
-
- private subscribe(): void {
- this.sub?.unsubscribe();
- this.sub = this.workspace.connectivity.onStatusChange.subscribe(undefined, {
- onData: (status) => {
- this.isOnline = status.isOnline;
- for (const handler of this.handlers) {
- handler({ isOnline: status.isOnline });
- }
- },
- onError: () => {},
- });
- void this.workspace.connectivity.getStatus
- .query()
- .then((status) => {
- this.isOnline = status.isOnline;
- })
- .catch(() => {});
- }
-
- getStatus(): ConnectivityStatus {
- return { isOnline: this.isOnline };
- }
-
- onStatusChange(handler: (status: ConnectivityStatus) => void): () => void {
- this.handlers.add(handler);
- return () => {
- this.handlers.delete(handler);
- };
- }
-}
diff --git a/products/desktop/apps/code/src/main/services/workspace-server/service.test.ts b/products/desktop/apps/code/src/main/services/workspace-server/service.test.ts
index 8f9f69afd446..db629c614661 100644
--- a/products/desktop/apps/code/src/main/services/workspace-server/service.test.ts
+++ b/products/desktop/apps/code/src/main/services/workspace-server/service.test.ts
@@ -1,11 +1,13 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+const { logError } = vi.hoisted(() => ({ logError: vi.fn() }));
+
vi.mock("../../utils/logger.js", () => ({
logger: {
scope: () => ({
info: vi.fn(),
warn: vi.fn(),
- error: vi.fn(),
+ error: logError,
debug: vi.fn(),
}),
},
@@ -68,13 +70,13 @@ describe("WorkspaceServerService", () => {
vi.restoreAllMocks();
});
- describe("start", () => {
+ describe("getOrStart", () => {
it("transitions idle -> starting -> ready and exposes the connection", async () => {
const service = new WorkspaceServerService();
withHealthySpawn(service);
const statuses = trackStatuses(service);
- const result = await service.start();
+ const result = await service.getOrStart();
expect(result).toEqual(CONNECTION);
expect(service.getConnection()).toEqual(CONNECTION);
@@ -93,12 +95,12 @@ describe("WorkspaceServerService", () => {
const service = new WorkspaceServerService();
const spawn = withHealthySpawn(service);
- const first = service.start();
- const second = service.start();
+ const first = service.getOrStart();
+ const second = service.getOrStart();
expect(first).toBe(second);
await first;
- await expect(service.start()).resolves.toEqual(CONNECTION);
+ await expect(service.getOrStart()).resolves.toEqual(CONNECTION);
expect(spawn).toHaveBeenCalledTimes(1);
});
});
@@ -110,7 +112,11 @@ describe("WorkspaceServerService", () => {
const spawn = withFailingSpawn(service);
const statuses = trackStatuses(service);
- service.start().catch(() => {});
+ await expect(service.getOrStart()).rejects.toThrow("unhealthy");
+ await expect(service.getOrStart()).rejects.toThrow(
+ "workspace-server is retrying",
+ );
+ expect(spawn).toHaveBeenCalledTimes(1);
await vi.runAllTimersAsync();
expect(service.getStatus()).toBe(WorkspaceServerStatus.Failed);
@@ -119,6 +125,15 @@ describe("WorkspaceServerService", () => {
expect(statuses[0]).toBe(WorkspaceServerStatus.Starting);
expect(statuses).toContain(WorkspaceServerStatus.Retrying);
expect(statuses[statuses.length - 1]).toBe(WorkspaceServerStatus.Failed);
+ expect(logError).toHaveBeenCalledOnce();
+ expect(logError).toHaveBeenCalledWith(
+ "workspace-server failed to start",
+ expect.objectContaining({ message: "unhealthy" }),
+ );
+ await expect(service.getOrStart()).rejects.toThrow(
+ "workspace-server is failed",
+ );
+ expect(spawn).toHaveBeenCalledTimes(6);
});
it("restart() resets the attempt budget after a failure", async () => {
@@ -126,7 +141,7 @@ describe("WorkspaceServerService", () => {
const service = new WorkspaceServerService();
const spawn = withFailingSpawn(service);
- service.start().catch(() => {});
+ service.getOrStart().catch(() => {});
await vi.runAllTimersAsync();
expect(service.getStatus()).toBe(WorkspaceServerStatus.Failed);
@@ -146,7 +161,7 @@ describe("WorkspaceServerService", () => {
it("goes idle, clears the connection and suppresses restarts", async () => {
const service = new WorkspaceServerService();
withHealthySpawn(service);
- await service.start();
+ await service.getOrStart();
service.stop();
diff --git a/products/desktop/apps/code/src/main/services/workspace-server/service.ts b/products/desktop/apps/code/src/main/services/workspace-server/service.ts
index 535837819ef8..6b3c892e0569 100644
--- a/products/desktop/apps/code/src/main/services/workspace-server/service.ts
+++ b/products/desktop/apps/code/src/main/services/workspace-server/service.ts
@@ -30,15 +30,10 @@ export type WorkspaceServerStatus =
(typeof WorkspaceServerStatus)[keyof typeof WorkspaceServerStatus];
export const WorkspaceServerEvent = {
- ConnectionLost: "connectionLost",
StatusChanged: "statusChanged",
} as const;
export interface WorkspaceServerEvents {
- [WorkspaceServerEvent.ConnectionLost]: {
- code: number | null;
- signal: NodeJS.Signals | null;
- };
[WorkspaceServerEvent.StatusChanged]: {
status: WorkspaceServerStatus;
attempt: number;
@@ -69,11 +64,26 @@ export class WorkspaceServerService extends TypedEventEmitter<WorkspaceServerEve
return { status: this.status, attempt: this.restartAttempts };
}
- start(): Promise<WorkspaceConnection> {
+ getOrStart(): Promise<WorkspaceConnection> {
if (this.connection) return Promise.resolve(this.connection);
if (this.pendingStart) return this.pendingStart;
+ if (this.stopping) {
+ return Promise.reject(new Error("workspace-server is stopping"));
+ }
+ if (this.status !== WorkspaceServerStatus.Idle) {
+ return Promise.reject(new Error(`workspace-server is ${this.status}`));
+ }
+
+ return this.start();
+ }
+
+ private start(): Promise<WorkspaceConnection> {
+ if (this.connection) return Promise.resolve(this.connection);
+ if (this.pendingStart) return this.pendingStart;
+ if (this.stopping) {
+ return Promise.reject(new Error("workspace-server is stopping"));
+ }
- this.stopping = false;
this.clearRestartTimer();
this.pendingStart = this.runStart();
return this.pendingStart;
@@ -132,6 +142,7 @@ export class WorkspaceServerService extends TypedEventEmitter<WorkspaceServerEve
if (this.pendingStart || this.restartTimer) return;
if (this.restartAttempts >= MAX_RESTART_ATTEMPTS) {
+ log.error("workspace-server failed to start", error);
this.setStatus(WorkspaceServerStatus.Failed, errorMessage(error));
return;
}
@@ -204,12 +215,10 @@ export class WorkspaceServerService extends TypedEventEmitter<WorkspaceServerEve
c.stderr?.on("data", (chunk) => process.stderr.write(chunk));
c.once("exit", (code, signal) => {
if (this.child !== c) return;
- const wasConnected = this.connection !== null;
this.child = null;
this.connection = null;
log.info("child exited", { code, signal });
- if (wasConnected && !this.stopping) {
- this.emit(WorkspaceServerEvent.ConnectionLost, { code, signal });
+ if (!this.stopping) {
this.scheduleRestart();
}
});
diff --git a/products/desktop/apps/code/src/main/trpc/routers/workspace-server.ts b/products/desktop/apps/code/src/main/trpc/routers/workspace-server.ts
index 26d214aefaf1..21e0de647314 100644
--- a/products/desktop/apps/code/src/main/trpc/routers/workspace-server.ts
+++ b/products/desktop/apps/code/src/main/trpc/routers/workspace-server.ts
@@ -17,24 +17,13 @@ const getService = () =>
export const workspaceServerRouter = router({
getConnection: publicProcedure.output(connectionSchema).query(async () => {
- const service = getService();
- return service.getConnection() ?? service.start();
+ return getService().getOrStart();
}),
restart: publicProcedure.mutation(async () => {
await getService().restart();
}),
- onConnectionLost: publicProcedure.subscription(async function* (opts) {
- const service = getService();
- const iterable = service.toIterable(WorkspaceServerEvent.ConnectionLost, {
- signal: opts.signal,
- });
- for await (const data of iterable) {
- yield data;
- }
- }),
-
onStatusChanged: publicProcedure.subscription(async function* (opts) {
const service = getService();
const iterable = service.toIterable(WorkspaceServerEvent.StatusChanged, {
diff --git a/products/desktop/apps/code/src/renderer/components/Providers.tsx b/products/desktop/apps/code/src/renderer/components/Providers.tsx
index d7c50d58d44b..347c40a0f439 100644
--- a/products/desktop/apps/code/src/renderer/components/Providers.tsx
+++ b/products/desktop/apps/code/src/renderer/components/Providers.tsx
@@ -7,18 +7,16 @@ import {
trpcClient,
useTRPC,
} from "@renderer/trpc/client";
-import {
- QueryClientProvider,
- useMutation,
- useQuery,
- useQueryClient,
-} from "@tanstack/react-query";
+import { QueryClientProvider, useMutation } from "@tanstack/react-query";
import { useSubscription } from "@trpc/tanstack-react-query";
import { queryClient } from "@utils/queryClient";
import type React from "react";
-import { useCallback, useState } from "react";
+import { useState } from "react";
import { HotkeysProvider } from "react-hotkeys-hook";
+const getWorkspaceConnection = () =>
+ trpcClient.workspaceServer.getConnection.query();
+
function WorkspaceServerErrorBanner({
onRetry,
disabled,
@@ -50,50 +48,28 @@ function ConnectedWorkspaceProvider({
children: React.ReactNode;
}) {
const trpc = useTRPC();
- const rqClient = useQueryClient();
- const [serverStatus, setServerStatus] = useState<string>("ready");
- const { data: connection } = useQuery(
- trpc.workspaceServer.getConnection.queryOptions(undefined, {
- staleTime: 30_000,
- }),
- );
-
- const invalidateConnection = useCallback(() => {
- rqClient.invalidateQueries({
- queryKey: trpc.workspaceServer.getConnection.queryKey(),
- });
- }, [rqClient, trpc]);
+ const [serverStatus, setServerStatus] = useState<string>("idle");
const restartServer = useMutation(
trpc.workspaceServer.restart.mutationOptions(),
);
- useSubscription(
- trpc.workspaceServer.onConnectionLost.subscriptionOptions(undefined, {
- onData: invalidateConnection,
- }),
- );
-
useSubscription(
trpc.workspaceServer.onStatusChanged.subscriptionOptions(undefined, {
onData: (data) => {
setServerStatus(data.status);
- if (data.status === "ready") {
- invalidateConnection();
- }
},
}),
);
return (
- <WorkspaceClientProvider connection={connection} queryClient={queryClient}>
+ <WorkspaceClientProvider
+ getConnection={getWorkspaceConnection}
+ queryClient={queryClient}
+ >
{serverStatus === "failed" ? (
<WorkspaceServerErrorBanner
- onRetry={() =>
- restartServer.mutate(undefined, {
- onSettled: () => invalidateConnection(),
- })
- }
+ onRetry={() => restartServer.mutate()}
disabled={restartServer.isPending}
/>
) : null}
diff --git a/products/desktop/packages/core/src/auth/identifiers.ts b/products/desktop/packages/core/src/auth/identifiers.ts
index b0cb00259588..40f46e736793 100644
--- a/products/desktop/packages/core/src/auth/identifiers.ts
+++ b/products/desktop/packages/core/src/auth/identifiers.ts
@@ -105,8 +105,7 @@ export interface ConnectivityStatus {
/**
* Reports network connectivity so the session refresh can avoid pointless
- * offline attempts and recover when the network returns. Desktop adapter wraps
- * the ConnectivityService (workspace-server connectivity stream).
+ * offline attempts and recover when the network returns.
*/
export interface IAuthConnectivity {
getStatus(): ConnectivityStatus;
diff --git a/products/desktop/packages/core/src/focus/focus-service.test.ts b/products/desktop/packages/core/src/focus/focus-service.test.ts
new file mode 100644
index 000000000000..21a5e8ee6b8f
--- /dev/null
+++ b/products/desktop/packages/core/src/focus/focus-service.test.ts
@@ -0,0 +1,44 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { FocusHostService } from "./focus-service";
+
+describe("FocusHostService event subscriptions", () => {
+ const branchUnsubscribe = vi.fn();
+ const foreignUnsubscribe = vi.fn();
+ const branchSubscribe = vi.fn(() => ({ unsubscribe: branchUnsubscribe }));
+ const foreignSubscribe = vi.fn(() => ({ unsubscribe: foreignUnsubscribe }));
+
+ const createService = () =>
+ new FocusHostService(
+ {
+ focus: {
+ onBranchRenamed: { subscribe: branchSubscribe },
+ onForeignBranchCheckout: { subscribe: foreignSubscribe },
+ },
+ } as never,
+ {} as never,
+ {} as never,
+ );
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("does not connect to the workspace server during construction", () => {
+ createService();
+
+ expect(branchSubscribe).not.toHaveBeenCalled();
+ expect(foreignSubscribe).not.toHaveBeenCalled();
+ });
+
+ it("replaces event subscriptions after the workspace server restarts", () => {
+ const service = createService();
+
+ service.resubscribeEvents();
+ service.resubscribeEvents();
+
+ expect(branchSubscribe).toHaveBeenCalledTimes(2);
+ expect(foreignSubscribe).toHaveBeenCalledTimes(2);
+ expect(branchUnsubscribe).toHaveBeenCalledOnce();
+ expect(foreignUnsubscribe).toHaveBeenCalledOnce();
+ });
+});
diff --git a/products/desktop/packages/core/src/focus/focus-service.ts b/products/desktop/packages/core/src/focus/focus-service.ts
index 515374e279b4..e52056b22c99 100644
--- a/products/desktop/packages/core/src/focus/focus-service.ts
+++ b/products/desktop/packages/core/src/focus/focus-service.ts
@@ -1,6 +1,6 @@
import { TypedEventEmitter } from "@posthog/shared";
import type { FocusBranchRenamedEvent } from "@posthog/workspace-client/types";
-import { inject, injectable } from "inversify";
+import { inject, injectable, preDestroy } from "inversify";
import {
FOCUS_SESSION_STORE,
FOCUS_WORKSPACE_CLIENT,
@@ -23,6 +23,11 @@ export class FocusHostService
extends TypedEventEmitter<FocusServiceEvents>
implements IFocusService
{
+ private branchRenamedSubscription: { unsubscribe(): void } | null = null;
+ private foreignBranchCheckoutSubscription: {
+ unsubscribe(): void;
+ } | null = null;
+
constructor(
@inject(FOCUS_WORKSPACE_CLIENT)
private readonly workspaceClient: FocusWorkspaceClient,
@@ -32,18 +37,34 @@ export class FocusHostService
private readonly paths: FocusWorktreePaths,
) {
super();
- this.focus.onBranchRenamed.subscribe(undefined, {
- onData: (event) => {
- void this.handleBranchRenamed(event);
- },
- onError: () => {},
- });
- this.focus.onForeignBranchCheckout.subscribe(undefined, {
- onData: (event) => {
- this.emit(FocusServiceEvent.ForeignBranchCheckout, event);
+ }
+
+ resubscribeEvents(): void {
+ this.unsubscribeEvents();
+ this.branchRenamedSubscription = this.focus.onBranchRenamed.subscribe(
+ undefined,
+ {
+ onData: (event) => {
+ void this.handleBranchRenamed(event);
+ },
+ onError: () => {},
},
- onError: () => {},
- });
+ );
+ this.foreignBranchCheckoutSubscription =
+ this.focus.onForeignBranchCheckout.subscribe(undefined, {
+ onData: (event) => {
+ this.emit(FocusServiceEvent.ForeignBranchCheckout, event);
+ },
+ onError: () => {},
+ });
+ }
+
+ @preDestroy()
+ unsubscribeEvents(): void {
+ this.branchRenamedSubscription?.unsubscribe();
+ this.branchRenamedSubscription = null;
+ this.foreignBranchCheckoutSubscription?.unsubscribe();
+ this.foreignBranchCheckoutSubscription = null;
}
private get focus() {
diff --git a/products/desktop/packages/core/src/focus/identifiers.ts b/products/desktop/packages/core/src/focus/identifiers.ts
index 5f49dd11be4f..17b4f441fe44 100644
--- a/products/desktop/packages/core/src/focus/identifiers.ts
+++ b/products/desktop/packages/core/src/focus/identifiers.ts
@@ -72,6 +72,7 @@ export interface FocusServiceEvents {
}
export interface IFocusService {
+ resubscribeEvents(): void;
getSession(mainRepoPath: string): FocusSession | null;
saveSession(session: FocusSession): Promise<void>;
deleteSession(mainRepoPath: string): Promise<void>;
diff --git a/products/desktop/packages/host-router/src/ports/connectivity-client.ts b/products/desktop/packages/host-router/src/ports/connectivity-client.ts
index cb6c67e5a37a..2dfe8182c161 100644
--- a/products/desktop/packages/host-router/src/ports/connectivity-client.ts
+++ b/products/desktop/packages/host-router/src/ports/connectivity-client.ts
@@ -1,9 +1,13 @@
-import type { WorkspaceClient } from "@posthog/workspace-client/client";
+import type { ConnectivityStatusOutput } from "@posthog/workspace-server/services/connectivity/schemas";
export const CONNECTIVITY_CLIENT = Symbol.for(
"posthog.host.connectivityClient",
);
export interface HostConnectivityClient {
- connectivity: WorkspaceClient["connectivity"];
+ getStatus(): ConnectivityStatusOutput;
+ checkNow(): Promise<ConnectivityStatusOutput>;
+ onStatusChange(
+ handler: (status: ConnectivityStatusOutput) => void,
+ ): () => void;
}
diff --git a/products/desktop/packages/host-router/src/routers/connectivity.router.ts b/products/desktop/packages/host-router/src/routers/connectivity.router.ts
index a26f7810a4b2..16f300c5637e 100644
--- a/products/desktop/packages/host-router/src/routers/connectivity.router.ts
+++ b/products/desktop/packages/host-router/src/routers/connectivity.router.ts
@@ -15,22 +15,18 @@ const ws = (container: ServiceResolver) =>
export const connectivityRouter = router({
getStatus: publicProcedure
.output(connectivityStatusOutput)
- .query(({ ctx }) => ws(ctx.container).connectivity.getStatus.query()),
+ .query(({ ctx }) => ws(ctx.container).getStatus()),
checkNow: publicProcedure
.output(connectivityStatusOutput)
- .mutation(({ ctx }) => ws(ctx.container).connectivity.checkNow.mutate()),
+ .mutation(({ ctx }) => ws(ctx.container).checkNow()),
onStatusChange: publicProcedure.subscription(async function* (opts) {
const queue: ConnectivityStatusOutput[] = [];
let resolve: (() => void) | null = null;
- const subscription = ws(
- opts.ctx.container,
- ).connectivity.onStatusChange.subscribe(undefined, {
- onData: (status) => {
- queue.push(status);
- resolve?.();
- },
+ const unsubscribe = ws(opts.ctx.container).onStatusChange((status) => {
+ queue.push(status);
+ resolve?.();
});
try {
while (!opts.signal?.aborted) {
@@ -45,7 +41,7 @@ export const connectivityRouter = router({
}
}
} finally {
- subscription.unsubscribe();
+ unsubscribe();
}
}),
});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
index c2611a4cbe1d..436deaa3463a 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelHomeComposer.tsx
@@ -158,7 +158,11 @@ export const ChannelHomeComposer = forwardRef<
const { hasGithubIntegration, isLoadingIntegrations } =
useUserRepositoryIntegration();
- const { workspaceMode, setWorkspaceMode } = useResolvedWorkspaceMode({
+ const {
+ workspaceMode,
+ isResolved: isWorkspaceModeResolved,
+ setWorkspaceMode,
+ } = useResolvedWorkspaceMode({
hasGithubIntegration,
isLoadingIntegrations,
allowWorktree: false,
@@ -280,7 +284,7 @@ export const ChannelHomeComposer = forwardRef<
allowNoRepo: true,
channelContext: effectiveChannelContext,
channelContextPath: wiki.path,
- submissionBlocked: wiki.blocked,
+ submissionBlocked: wiki.blocked || !isWorkspaceModeResolved,
channelName,
channelId,
channelContextId: channelId,
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx b/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx
index 26773dd6bebb..064f03d77a87 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx
+++ b/products/desktop/packages/ui/src/features/message-editor/components/AttachmentMenu.tsx
@@ -77,6 +77,7 @@ export function AttachmentMenu({
queryKey: ["git", "getGhStatus"],
queryFn: () => getGhStatus(),
staleTime: 60_000,
+ enabled: menuOpen && !!repoPath,
});
const issueDisabledReason = getIssueDisabledReason(ghStatus, repoPath);
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
index 0d1f9be7e30a..e4567fd4a927 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskInput.tsx
@@ -504,17 +504,23 @@ export function TaskInput({
);
}, [flagsLoaded, lastUsedAgentRuntime, piHarnessEnabled, settingsHydrated]);
- const { workspaceMode, setWorkspaceMode, overrideWorkspaceMode } =
- useResolvedWorkspaceMode({
- hasGithubIntegration,
- isLoadingIntegrations,
- pinCloud: !!initialCloudRepository,
- });
+ const {
+ workspaceMode,
+ isResolved: isWorkspaceModeResolved,
+ setWorkspaceMode,
+ overrideWorkspaceMode,
+ } = useResolvedWorkspaceMode({
+ hasGithubIntegration,
+ isLoadingIntegrations,
+ pinCloud: !!initialCloudRepository,
+ });
+ const localWorkspaceReady =
+ isWorkspaceModeResolved && workspaceMode !== "cloud";
const showCodexNotConnectedNotice =
runtime !== "pi" &&
adapter === "codex" &&
- workspaceMode !== "cloud" &&
+ localWorkspaceReady &&
codexSubscription.needsConnection;
const showClaudeNotConnectedNotice =
@@ -550,7 +556,7 @@ export function TaskInput({
return repositories.includes(lower) ? lower : null;
}, [selectedRepository, repositories]);
const { currentBranch, branchLoading, defaultBranch, busyState } =
- useGitQueries(selectedDirectory);
+ useGitQueries(selectedDirectory, { enabled: localWorkspaceReady });
const selectedGithubUserIntegrationId = selectedCloudRepository
? getUserIntegrationIdForRepo(selectedCloudRepository)
@@ -1074,7 +1080,7 @@ export function TaskInput({
channelName,
channelId,
channelContextId,
- submissionBlocked: channelContextBlocked,
+ submissionBlocked: channelContextBlocked || !isWorkspaceModeResolved,
allowNoRepo: repoOptional,
});
@@ -1355,7 +1361,7 @@ export function TaskInput({
>
<DropZoneOverlay isVisible={isDraggingFile} />
<Flex height="100%" width="100%">
- {previewFile && selectedDirectory && (
+ {localWorkspaceReady && previewFile && selectedDirectory && (
<Box className="h-full min-w-0 flex-1 border-gray-4 border-r">
<NewTaskFilePreview
repoPath={selectedDirectory}
@@ -1475,7 +1481,9 @@ export function TaskInput({
repoPath={
workspaceMode === "cloud"
? selectedCloudRepository
- : selectedDirectory
+ : localWorkspaceReady
+ ? selectedDirectory
+ : null
}
currentBranch={currentBranch}
defaultBranch={
@@ -1485,6 +1493,7 @@ export function TaskInput({
}
disabled={
isCreatingTask ||
+ !isWorkspaceModeResolved ||
(workspaceMode === "cloud" && !selectedCloudRepository)
}
loading={
@@ -1513,7 +1522,7 @@ export function TaskInput({
/>
</ButtonGroup>
)}
- {!repoOptional && workspaceMode !== "cloud" && (
+ {!repoOptional && localWorkspaceReady && (
<AdditionalDirectoriesButton
values={additionalDirectories}
onChange={setAdditionalDirectories}
@@ -1810,7 +1819,9 @@ export function TaskInput({
</AnimatePresence>
) : showNewTaskSuggestions ? (
<NewTaskSuggestions
- repoPath={selectedDirectory || null}
+ repoPath={
+ localWorkspaceReady ? selectedDirectory || null : null
+ }
workspaceMode={effectiveWorkspaceMode}
disabled={isCreatingTask}
/>
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsx b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsx
index 971f994f40b0..58765a5e9995 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.test.tsx
@@ -57,12 +57,14 @@ describe("useResolvedWorkspaceMode", () => {
);
expect(result.current.workspaceMode).toBe("local");
+ expect(result.current.isResolved).toBe(false);
cloudState.enabled = true;
cloudState.flagsLoaded = true;
rerender(SETTLED);
expect(result.current.workspaceMode).toBe("cloud");
+ expect(result.current.isResolved).toBe(true);
});
it.each([
@@ -159,10 +161,13 @@ describe("useResolvedWorkspaceMode", () => {
useResolvedWorkspaceMode(SETTLED),
);
+ expect(result.current.isResolved).toBe(false);
+
settingsState._hasHydrated = true;
rerender();
expect(result.current.workspaceMode).toBe("local");
+ expect(result.current.isResolved).toBe(true);
});
it("pins cloud on a cloud-only host", () => {
@@ -172,5 +177,6 @@ describe("useResolvedWorkspaceMode", () => {
const { result } = renderHook(() => useResolvedWorkspaceMode(SETTLED));
expect(result.current.workspaceMode).toBe("cloud");
+ expect(result.current.isResolved).toBe(true);
});
});
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.ts
index 6f5baf879dd9..f46d85b2510b 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useResolvedWorkspaceMode.ts
@@ -22,6 +22,7 @@ export interface UseResolvedWorkspaceModeInput {
export interface ResolvedWorkspaceMode {
workspaceMode: WorkspaceMode;
+ isResolved: boolean;
setWorkspaceMode: (mode: WorkspaceMode) => void;
overrideWorkspaceMode: (mode: WorkspaceMode) => void;
}
@@ -59,6 +60,8 @@ export function useResolvedWorkspaceMode({
lastUsedLocalWorkspaceMode: localFallback,
});
});
+ const initiallyResolved = pinCloud || !localWorkspaces;
+ const [isResolved, setIsResolved] = useState(initiallyResolved);
const cloudSignalsSettled = areCloudSignalsSettled({
cloudModeEnabled,
@@ -66,16 +69,18 @@ export function useResolvedWorkspaceMode({
isLoadingIntegrations,
});
- const didResolveRef = useRef(false);
+ const didResolveRef = useRef(initiallyResolved);
useEffect(() => {
if (didResolveRef.current) return;
if (!settingsHydrated) return;
if (pinCloud) {
didResolveRef.current = true;
+ setIsResolved(true);
return;
}
if (preferredMode === "cloud" && !cloudSignalsSettled) return;
didResolveRef.current = true;
+ setIsResolved(true);
if (!localWorkspaces) return;
setWorkspaceModeState(
resolveWorkspaceModePreference({
@@ -99,6 +104,7 @@ export function useResolvedWorkspaceMode({
const setWorkspaceMode = useCallback(
(mode: WorkspaceMode) => {
didResolveRef.current = true;
+ setIsResolved(true);
setWorkspaceModeState(mode);
setLastUsedWorkspaceMode(mode);
if (mode !== "cloud") setLastUsedLocalWorkspaceMode(mode);
@@ -108,8 +114,14 @@ export function useResolvedWorkspaceMode({
const overrideWorkspaceMode = useCallback((mode: WorkspaceMode) => {
didResolveRef.current = true;
+ setIsResolved(true);
setWorkspaceModeState(mode);
}, []);
- return { workspaceMode, setWorkspaceMode, overrideWorkspaceMode };
+ return {
+ workspaceMode,
+ isResolved,
+ setWorkspaceMode,
+ overrideWorkspaceMode,
+ };
}
diff --git a/products/desktop/packages/workspace-client/src/client.test.ts b/products/desktop/packages/workspace-client/src/client.test.ts
index 57dc071c8d00..513239a01b2a 100644
--- a/products/desktop/packages/workspace-client/src/client.test.ts
+++ b/products/desktop/packages/workspace-client/src/client.test.ts
@@ -1,9 +1,5 @@
-import { describe, expect, it, vi } from "vitest";
-import {
- createReconnectingWorkspaceClient,
- type WorkspaceClient,
- type WorkspaceConnection,
-} from "./client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createLazyWorkspaceClient, type WorkspaceConnection } from "./client";
const connA: WorkspaceConnection = {
url: "http://127.0.0.1:1111",
@@ -14,60 +10,68 @@ const connB: WorkspaceConnection = {
secret: "secret-b",
};
-function makeFakeClient(name: string): WorkspaceClient {
- return { name } as unknown as WorkspaceClient;
-}
+const trpcResponse = (data: unknown) =>
+ new Response(JSON.stringify([{ result: { data: { json: data } } }]), {
+ headers: { "content-type": "application/json" },
+ });
+
+describe("createLazyWorkspaceClient", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
-describe("createReconnectingWorkspaceClient", () => {
- it("builds one client per connection and reuses it across accesses", () => {
- const buildClient = vi.fn(() => makeFakeClient("a"));
- const client = createReconnectingWorkspaceClient(() => connA, buildClient);
+ it("does not resolve a connection until an operation starts", () => {
+ const getConnection = vi.fn().mockResolvedValue(connA);
+ const client = createLazyWorkspaceClient(getConnection);
- expect(Reflect.get(client, "name")).toBe("a");
- expect(Reflect.get(client, "name")).toBe("a");
- expect(buildClient).toHaveBeenCalledTimes(1);
- expect(buildClient).toHaveBeenCalledWith(connA);
+ Reflect.get(client.fs, "readAbsoluteFile");
+
+ expect(getConnection).not.toHaveBeenCalled();
});
- it("rebuilds the client when the connection changes (server respawn)", () => {
+ it("resolves the current connection for each query", async () => {
let current = connA;
- const buildClient = vi
+ const getConnection = vi.fn(async () => current);
+ const fetch = vi
.fn()
- .mockReturnValueOnce(makeFakeClient("a"))
- .mockReturnValueOnce(makeFakeClient("b"));
- const client = createReconnectingWorkspaceClient(
- () => current,
- buildClient,
- );
+ .mockResolvedValueOnce(trpcResponse("first"))
+ .mockResolvedValueOnce(trpcResponse("second"));
+ vi.stubGlobal("fetch", fetch);
+ const client = createLazyWorkspaceClient(getConnection);
- expect(Reflect.get(client, "name")).toBe("a");
+ await expect(
+ client.fs.readAbsoluteFile.query({ filePath: "/tmp/first" }),
+ ).resolves.toBe("first");
current = connB;
- expect(Reflect.get(client, "name")).toBe("b");
- expect(buildClient).toHaveBeenCalledTimes(2);
- expect(buildClient).toHaveBeenLastCalledWith(connB);
- });
-
- it("keeps using the last known client while the server is down", () => {
- let current: WorkspaceConnection | null = connA;
- const buildClient = vi.fn(() => makeFakeClient("a"));
- const client = createReconnectingWorkspaceClient(
- () => current,
- buildClient,
- );
+ await expect(
+ client.fs.readAbsoluteFile.query({ filePath: "/tmp/second" }),
+ ).resolves.toBe("second");
- expect(Reflect.get(client, "name")).toBe("a");
- current = null;
- expect(Reflect.get(client, "name")).toBe("a");
- expect(buildClient).toHaveBeenCalledTimes(1);
+ expect(getConnection).toHaveBeenCalledTimes(2);
+ const firstUrl = new URL(String(fetch.mock.calls[0]?.[0]));
+ const secondUrl = new URL(String(fetch.mock.calls[1]?.[0]));
+ expect(firstUrl.origin).toBe(connA.url);
+ expect(secondUrl.origin).toBe(connB.url);
+ expect(
+ new Headers(fetch.mock.calls[0]?.[1]?.headers).get("x-workspace-secret"),
+ ).toBe(connA.secret);
+ expect(
+ new Headers(fetch.mock.calls[1]?.[1]?.headers).get("x-workspace-secret"),
+ ).toBe(connB.secret);
});
- it("throws when accessed before any connection is established", () => {
- const buildClient = vi.fn();
- const client = createReconnectingWorkspaceClient(() => null, buildClient);
+ it("resolves a connection when a subscription starts", async () => {
+ const getConnection = vi.fn().mockRejectedValue(new Error("start failed"));
+ const onError = vi.fn();
+ const client = createLazyWorkspaceClient(getConnection);
- expect(() => Reflect.get(client, "name")).toThrow(
- "workspace-server connection is not established yet",
+ const subscription = client.fileWatcher.watch.subscribe(
+ { repoPath: "/tmp/repo" },
+ { onError },
);
- expect(buildClient).not.toHaveBeenCalled();
+
+ await vi.waitFor(() => expect(getConnection).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce());
+ subscription.unsubscribe();
});
});
diff --git a/products/desktop/packages/workspace-client/src/client.ts b/products/desktop/packages/workspace-client/src/client.ts
index 186a7c8dda2a..1ebcd979a01b 100644
--- a/products/desktop/packages/workspace-client/src/client.ts
+++ b/products/desktop/packages/workspace-client/src/client.ts
@@ -8,6 +8,7 @@ import {
import superjson from "superjson";
const SECRET_HEADER = "x-workspace-secret";
+const UNRESOLVED_WORKSPACE_URL = "http://workspace-server.invalid/trpc";
export interface WorkspaceConnection {
url: string;
@@ -16,66 +17,51 @@ export interface WorkspaceConnection {
export type WorkspaceClient = ReturnType<typeof createWorkspaceClient>;
-/**
- * A workspace client that follows the host's current connection. The
- * workspace-server child can crash and be respawned on a new port with a new
- * secret; a client built once at boot would keep calling the dead port
- * ("fetch failed") for the rest of the app session. This proxy re-reads the
- * connection at the start of every call chain and rebuilds the underlying
- * client whenever it changes. While the server is down (`getConnection`
- * returns null) the last known client is used, so calls fail fast against the
- * old port instead of hanging.
- */
-export function createReconnectingWorkspaceClient(
- getConnection: () => WorkspaceConnection | null,
- buildClient: (
- connection: WorkspaceConnection,
- ) => WorkspaceClient = createWorkspaceClient,
-): WorkspaceClient {
- let built: {
- connection: WorkspaceConnection;
- client: WorkspaceClient;
- } | null = null;
-
- const resolve = (): WorkspaceClient => {
- const connection = getConnection() ?? built?.connection;
- if (!connection) {
- throw new Error("workspace-server connection is not established yet");
- }
- if (
- !built ||
- built.connection.url !== connection.url ||
- built.connection.secret !== connection.secret
- ) {
- built = { connection, client: buildClient(connection) };
- }
- return built.client;
- };
-
- return new Proxy({} as WorkspaceClient, {
- get: (_target, prop) => Reflect.get(resolve() as object, prop),
- has: (_target, prop) => Reflect.has(resolve() as object, prop),
- getPrototypeOf: () => Reflect.getPrototypeOf(resolve() as object),
- });
+export function createWorkspaceClient(connection: WorkspaceConnection) {
+ return createLazyWorkspaceClient(() => Promise.resolve(connection));
}
-export function createWorkspaceClient(connection: WorkspaceConnection) {
- const url = `${connection.url.replace(/\/$/, "")}/trpc`;
- const headers = { [SECRET_HEADER]: connection.secret };
- const subscriptionUrl = `${url}?secret=${encodeURIComponent(connection.secret)}`;
+export function createLazyWorkspaceClient(
+ getConnection: () => Promise<WorkspaceConnection>,
+) {
+ const fetchWithConnection = async (
+ input: { url: string } | URL | string,
+ init?: RequestInit,
+ ) => {
+ const connection = await getConnection();
+ const unresolvedUrl = new URL(
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.href
+ : input.url,
+ );
+ const resolvedUrl = new URL(
+ `${unresolvedUrl.pathname}${unresolvedUrl.search}`,
+ connection.url,
+ );
+ const headers = new Headers(init?.headers);
+ headers.set(SECRET_HEADER, connection.secret);
+ return globalThis.fetch(resolvedUrl, { ...init, headers });
+ };
return createTRPCClient<AppRouter>({
links: [
splitLink({
condition: (op) => op.type === "subscription",
true: httpSubscriptionLink({
- url: subscriptionUrl,
+ url: async () => {
+ const connection = await getConnection();
+ return `${connection.url.replace(/\/$/, "")}/trpc?secret=${encodeURIComponent(connection.secret)}`;
+ },
transformer: superjson,
}),
false: httpBatchLink({
- url,
+ url: UNRESOLVED_WORKSPACE_URL,
transformer: superjson,
- headers: () => headers,
+ fetch: fetchWithConnection as NonNullable<
+ Parameters<typeof httpBatchLink>[0]["fetch"]
+ >,
}),
}),
],
diff --git a/products/desktop/packages/workspace-client/src/provider.tsx b/products/desktop/packages/workspace-client/src/provider.tsx
index 24593ac6c62d..92903cb62126 100644
--- a/products/desktop/packages/workspace-client/src/provider.tsx
+++ b/products/desktop/packages/workspace-client/src/provider.tsx
@@ -1,6 +1,10 @@
import type { QueryClient } from "@tanstack/react-query";
import { type ReactNode, useMemo } from "react";
-import { createWorkspaceClient, type WorkspaceConnection } from "./client";
+import {
+ createLazyWorkspaceClient,
+ createWorkspaceClient,
+ type WorkspaceConnection,
+} from "./client";
import { WorkspaceTRPCProvider } from "./trpc";
const UNAVAILABLE: WorkspaceConnection = {
@@ -9,19 +13,24 @@ const UNAVAILABLE: WorkspaceConnection = {
};
export interface WorkspaceClientProviderProps {
- connection: WorkspaceConnection | null | undefined;
+ connection?: WorkspaceConnection | null;
+ getConnection?: () => Promise<WorkspaceConnection>;
queryClient: QueryClient;
children: ReactNode;
}
export function WorkspaceClientProvider({
connection,
+ getConnection,
queryClient,
children,
}: WorkspaceClientProviderProps) {
const client = useMemo(
- () => createWorkspaceClient(connection ?? UNAVAILABLE),
- [connection],
+ () =>
+ getConnection
+ ? createLazyWorkspaceClient(getConnection)
+ : createWorkspaceClient(connection ?? UNAVAILABLE),
+ [connection, getConnection],
);
return (
diff --git a/products/desktop/packages/workspace-server/src/di/container.ts b/products/desktop/packages/workspace-server/src/di/container.ts
index 4a616a80d104..2d84521878d7 100644
--- a/products/desktop/packages/workspace-server/src/di/container.ts
+++ b/products/desktop/packages/workspace-server/src/di/container.ts
@@ -1,6 +1,5 @@
import "reflect-metadata";
import { TypedContainer } from "@inversifyjs/strongly-typed";
-import { ConnectivityService } from "../services/connectivity/service";
import { EnvironmentService } from "../services/environment/service";
import { FocusService } from "../services/focus/service";
import { FocusSyncService } from "../services/focus/sync-service";
@@ -10,7 +9,6 @@ import { LOGS_SERVICE } from "../services/local-logs/identifiers";
import { LocalLogsService } from "../services/local-logs/service";
import { WatcherService } from "../services/watcher/service";
import {
- CONNECTIVITY_SERVICE,
ENVIRONMENT_SERVICE,
FOCUS_SERVICE,
FOCUS_SYNC_SERVICE,
@@ -28,7 +26,6 @@ interface WorkspaceServerBindings {
[WATCHER_SERVICE]: WatcherService;
[LOCAL_LOGS_SERVICE]: LocalLogsService;
[LOGS_SERVICE]: LocalLogsService;
- [CONNECTIVITY_SERVICE]: ConnectivityService;
[ENVIRONMENT_SERVICE]: EnvironmentService;
}
@@ -40,5 +37,4 @@ container.bind(FS_SERVICE).to(FsService).inSingletonScope();
container.bind(WATCHER_SERVICE).to(WatcherService).inSingletonScope();
container.bind(LOCAL_LOGS_SERVICE).to(LocalLogsService).inSingletonScope();
container.bind(LOGS_SERVICE).toService(LOCAL_LOGS_SERVICE);
-container.bind(CONNECTIVITY_SERVICE).to(ConnectivityService).inSingletonScope();
container.bind(ENVIRONMENT_SERVICE).to(EnvironmentService).inSingletonScope();
diff --git a/products/desktop/packages/workspace-server/src/serve.ts b/products/desktop/packages/workspace-server/src/serve.ts
index ba8902accf84..d692369ef12b 100644
--- a/products/desktop/packages/workspace-server/src/serve.ts
+++ b/products/desktop/packages/workspace-server/src/serve.ts
@@ -5,7 +5,6 @@ import { serve } from "@hono/node-server";
import { createApp } from "./app";
import { container } from "./di/container";
import {
- CONNECTIVITY_SERVICE,
ENVIRONMENT_SERVICE,
FOCUS_SERVICE,
FOCUS_SYNC_SERVICE,
@@ -15,7 +14,6 @@ import {
WATCHER_SERVICE,
} from "./di/tokens";
import { removeLegacyNodeShimDirs } from "./services/agent/legacy-node-shim";
-import type { ConnectivityService } from "./services/connectivity/service";
import type { EnvironmentService } from "./services/environment/service";
import type { FocusService } from "./services/focus/service";
import type { FocusSyncService } from "./services/focus/sync-service";
@@ -73,7 +71,6 @@ const router = createAppRouter({
fsService: container.get<FsService>(FS_SERVICE),
watcherService: container.get<WatcherService>(WATCHER_SERVICE),
localLogsService: container.get<LocalLogsService>(LOCAL_LOGS_SERVICE),
- connectivityService: container.get<ConnectivityService>(CONNECTIVITY_SERVICE),
environmentService: container.get<EnvironmentService>(ENVIRONMENT_SERVICE),
});
const app = createApp({ sharedSecret, router });
diff --git a/products/desktop/packages/workspace-server/src/services/connectivity/service.ts b/products/desktop/packages/workspace-server/src/services/connectivity/service.ts
index 7f4434ef77d7..b2ab74d34241 100644
--- a/products/desktop/packages/workspace-server/src/services/connectivity/service.ts
+++ b/products/desktop/packages/workspace-server/src/services/connectivity/service.ts
@@ -1,5 +1,5 @@
import { TypedEventEmitter } from "@posthog/shared";
-import { injectable } from "inversify";
+import { injectable, preDestroy } from "inversify";
import {
ConnectivityEvent,
type ConnectivityEvents,
@@ -34,11 +34,19 @@ export class ConnectivityService extends TypedEventEmitter<ConnectivityEvents> {
return { isOnline: this.isOnline };
}
+ onStatusChange(
+ handler: (status: ConnectivityStatusOutput) => void,
+ ): () => void {
+ this.on(ConnectivityEvent.StatusChange, handler);
+ return () => this.off(ConnectivityEvent.StatusChange, handler);
+ }
+
async checkNow(): Promise<ConnectivityStatusOutput> {
await this.checkConnectivity();
return { isOnline: this.isOnline };
}
+ @preDestroy()
stop(): void {
if (this.pollTimeoutId) {
clearTimeout(this.pollTimeoutId);
diff --git a/products/desktop/packages/workspace-server/src/trpc.ts b/products/desktop/packages/workspace-server/src/trpc.ts
index dde559bd6602..959f1d566bda 100644
--- a/products/desktop/packages/workspace-server/src/trpc.ts
+++ b/products/desktop/packages/workspace-server/src/trpc.ts
@@ -1,8 +1,6 @@
import { initTRPC } from "@trpc/server";
import superjson from "superjson";
import { z } from "zod";
-import { connectivityStatusOutput } from "./services/connectivity/schemas";
-import type { ConnectivityService } from "./services/connectivity/service";
import {
createEnvironmentInput,
deleteEnvironmentInput,
@@ -161,7 +159,6 @@ export interface WorkspaceServerServices {
fsService: FsService;
watcherService: WatcherService;
localLogsService: LocalLogsService;
- connectivityService: ConnectivityService;
environmentService: EnvironmentService;
}
@@ -172,7 +169,6 @@ export function createAppRouter({
fsService: fsServiceInst,
watcherService: watcherServiceInst,
localLogsService: localLogsServiceInst,
- connectivityService: connectivityServiceInst,
environmentService: environmentServiceInst,
}: WorkspaceServerServices) {
const focusService = () => focusServiceInst;
@@ -181,7 +177,6 @@ export function createAppRouter({
const fsService = () => fsServiceInst;
const watcherService = () => watcherServiceInst;
const localLogsService = () => localLogsServiceInst;
- const connectivityService = () => connectivityServiceInst;
const environmentService = () => environmentServiceInst;
return t.router({
@@ -882,23 +877,6 @@ export function createAppRouter({
localLogsService().writeLocalLogs(input.taskRunId, input.content),
),
}),
- connectivity: t.router({
- getStatus: t.procedure
- .output(connectivityStatusOutput)
- .query(() => connectivityService().getStatus()),
-
- checkNow: t.procedure
- .output(connectivityStatusOutput)
- .mutation(() => connectivityService().checkNow()),
-
- onStatusChange: t.procedure.subscription(async function* (opts) {
- for await (const status of connectivityService().statusChangeEvents(
- opts.signal,
- )) {
- yield status;
- }
- }),
- }),
environment: t.router({
list: t.procedure
.input(listEnvironmentsInput)