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): don't drop shell output while tab is hidden (#82763)

Charles Vienecd3c30e1387
diff --git a/products/desktop/packages/ui/src/features/terminal/Terminal.tsx b/products/desktop/packages/ui/src/features/terminal/Terminal.tsx
index 01f2d665fef3..a945054da075 100644
--- a/products/desktop/packages/ui/src/features/terminal/Terminal.tsx
+++ b/products/desktop/packages/ui/src/features/terminal/Terminal.tsx
@@ -4,11 +4,6 @@ import { Box } from "@radix-ui/themes";
import "@xterm/xterm/css/xterm.css";
import { resolveTerminalFontFamily } from "@posthog/core/terminal/resolveTerminalFontFamily";
-import { useService } from "@posthog/di/react";
-import {
- SHELL_CLIENT,
- type ShellClient,
-} from "@posthog/ui/features/terminal/shellClient";
import { terminalManager } from "@posthog/ui/features/terminal/TerminalManager";
import { useCallback, useEffect, useRef } from "react";
@@ -34,7 +29,6 @@ export function Terminal({
onExit,
}: TerminalProps) {
const terminalRef = useRef<HTMLDivElement>(null);
- const shellClient = useService<ShellClient>(SHELL_CLIENT);
const isDarkMode = useThemeStore((state) => state.isDarkMode);
const terminalFont = useSettingsStore((s) => s.terminalFont);
const terminalCustomFontFamily = useSettingsStore(
@@ -85,21 +79,6 @@ export function Terminal({
terminalManager.setUseWebgl(terminalGpuRendering);
}, [terminalGpuRendering]);
- // Subscribe to shell data + exit events via the host shell client.
- useEffect(() => {
- if (!sessionId) return;
- const dataSub = shellClient.onData(sessionId, (event) => {
- terminalManager.writeData(event.sessionId, event.data);
- });
- const exitSub = shellClient.onExit(sessionId, (event) => {
- terminalManager.handleExit(event.sessionId, event.exitCode ?? undefined);
- });
- return () => {
- dataSub.unsubscribe();
- exitSub.unsubscribe();
- };
- }, [sessionId, shellClient]);
-
// Event callbacks
useEffect(() => {
const offReady = terminalManager.on("ready", ({ sessionId: id }) => {
diff --git a/products/desktop/packages/ui/src/features/terminal/TerminalManager.test.ts b/products/desktop/packages/ui/src/features/terminal/TerminalManager.test.ts
index fb9667161d6f..70972524fde2 100644
--- a/products/desktop/packages/ui/src/features/terminal/TerminalManager.test.ts
+++ b/products/desktop/packages/ui/src/features/terminal/TerminalManager.test.ts
@@ -7,6 +7,18 @@ const mocks = vi.hoisted(() => {
const write = vi.fn();
const resize = vi.fn();
const openExternal = vi.fn();
+ const onData = vi.fn(
+ (
+ _sessionId: string,
+ _onEvent: (event: { sessionId: string; data: string }) => void,
+ ) => ({ unsubscribe: vi.fn() }),
+ );
+ const onExit = vi.fn(
+ (
+ _sessionId: string,
+ _onEvent: (event: { sessionId: string; exitCode: number | null }) => void,
+ ) => ({ unsubscribe: vi.fn() }),
+ );
const logInfo = vi.fn();
const logError = vi.fn();
const logWarn = vi.fn();
@@ -55,6 +67,8 @@ const mocks = vi.hoisted(() => {
write,
resize,
openExternal,
+ onData,
+ onExit,
logInfo,
logError,
logWarn,
@@ -71,6 +85,8 @@ vi.mock("@posthog/di/container", () => ({
write: mocks.write,
resize: mocks.resize,
openExternal: mocks.openExternal,
+ onData: mocks.onData,
+ onExit: mocks.onExit,
}),
}));
@@ -267,6 +283,73 @@ describe("TerminalManager.destroyForTask", () => {
});
});
+describe("TerminalManager shell output subscription", () => {
+ const sessionId = "detached-output-test";
+ const rafCallbacks: FrameRequestCallback[] = [];
+
+ beforeEach(() => {
+ mocks.check.mockReset().mockResolvedValue(true);
+ mocks.create.mockReset().mockResolvedValue(undefined);
+ mocks.write.mockReset().mockResolvedValue(undefined);
+ mocks.resize.mockReset().mockResolvedValue(undefined);
+ mocks.onData.mockClear();
+ mocks.onExit.mockClear();
+ mocks.terminalInstances.length = 0;
+ rafCallbacks.length = 0;
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {
+ rafCallbacks.push(cb);
+ return rafCallbacks.length;
+ });
+ vi.stubGlobal("cancelAnimationFrame", () => {});
+ });
+
+ afterEach(() => {
+ terminalManager.destroy(sessionId);
+ vi.unstubAllGlobals();
+ });
+
+ it("writes shell data to the terminal without a mounted component", () => {
+ terminalManager.create({ sessionId, persistenceKey: "task-hidden" });
+
+ const emitShellData = mocks.onData.mock.calls[0][1];
+ emitShellData({ sessionId, data: "output while hidden" });
+ for (const cb of rafCallbacks) {
+ cb(0);
+ }
+
+ expect(mocks.terminalInstances[0].write).toHaveBeenCalledWith(
+ "output while hidden",
+ );
+ });
+
+ it("delivers shell exit to listeners without a mounted component", () => {
+ terminalManager.create({ sessionId, persistenceKey: "task-hidden" });
+ const exitListener = vi.fn();
+ const off = terminalManager.on("exit", exitListener);
+
+ const emitShellExit = mocks.onExit.mock.calls[0][1];
+ emitShellExit({ sessionId, exitCode: 1 });
+
+ expect(exitListener).toHaveBeenCalledWith({
+ sessionId,
+ persistenceKey: "task-hidden",
+ exitCode: 1,
+ });
+ off();
+ });
+
+ it("unsubscribes from shell data and exit on destroy", () => {
+ terminalManager.create({ sessionId, persistenceKey: "task-hidden" });
+ const dataUnsubscribe = mocks.onData.mock.results[0].value.unsubscribe;
+ const exitUnsubscribe = mocks.onExit.mock.results[0].value.unsubscribe;
+
+ terminalManager.destroy(sessionId);
+
+ expect(dataUnsubscribe).toHaveBeenCalledTimes(1);
+ expect(exitUnsubscribe).toHaveBeenCalledTimes(1);
+ });
+});
+
describe("TerminalManager custom key handling", () => {
const sessionId = "key-handler-test";
diff --git a/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts b/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts
index e8ce975bb698..a8044d786a77 100644
--- a/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts
+++ b/products/desktop/packages/ui/src/features/terminal/TerminalManager.ts
@@ -192,6 +192,8 @@ class TerminalManagerImpl {
return existing;
}
+ const shellClient = resolveService<ShellClient>(SHELL_CLIENT);
+
const term = new XTerm({
cursorBlink: true,
fontSize: 12,
@@ -231,18 +233,26 @@ class TerminalManagerImpl {
}
// Setup user input handler
- const disposable = term.onData((data: string) => {
- resolveService<ShellClient>(SHELL_CLIENT)
- .write({ sessionId, data })
- .catch((error: Error) => {
- this.handleMissingSessionError(sessionId, instance, error, {
- reason: "write",
- retryData: data,
- });
+ const inputDisposable = term.onData((data: string) => {
+ shellClient.write({ sessionId, data }).catch((error: Error) => {
+ this.handleMissingSessionError(sessionId, instance, error, {
+ reason: "write",
+ retryData: data,
});
+ });
this.scheduleSave(sessionId, instance);
});
- instance.cleanups.push(() => disposable.dispose());
+ instance.cleanups.push(() => inputDisposable.dispose());
+
+ // Instance-lifetime, not component-lifetime: pty output while the tab is unmounted would otherwise be dropped
+ const dataSub = shellClient.onData(sessionId, (event) => {
+ this.writeData(event.sessionId, event.data);
+ });
+ const exitSub = shellClient.onExit(sessionId, (event) => {
+ this.handleExit(event.sessionId, event.exitCode ?? undefined);
+ });
+ instance.cleanups.push(() => dataSub.unsubscribe());
+ instance.cleanups.push(() => exitSub.unsubscribe());
// Initialize shell session
this.initializeSession(sessionId, instance, cwd, taskId, command);
@@ -310,7 +320,7 @@ class TerminalManagerImpl {
}
}
- writeData(sessionId: string, data: string): void {
+ private writeData(sessionId: string, data: string): void {
const instance = this.instances.get(sessionId);
if (!instance) {
return;
@@ -343,7 +353,7 @@ class TerminalManagerImpl {
this.scheduleSave(sessionId, instance);
}
- handleExit(sessionId: string, exitCode?: number): void {
+ private handleExit(sessionId: string, exitCode?: number): void {
const instance = this.instances.get(sessionId);
if (instance) {
// Without this, ResizeObserver keeps firing shell.resize against the dead