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
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { describe, expect, mock, spyOn, test } from "bun:test";
import { useTerminalCloseConfirmStore } from "renderer/stores/terminal-close-confirm/store";
import {
confirmCloseTerminals,
probeTerminalRunning,
} from "./confirm-close-terminals";

type ProbeUtils = Parameters<typeof probeTerminalRunning>[0];

function probeUtils(query: ReturnType<typeof mock>): ProbeUtils {
return {
client: { terminal: { hasRunningProcess: { query } } },
} as unknown as ProbeUtils;
}

describe("probeTerminalRunning", () => {
test("aborts a stalled request and allows the terminal to close", async () => {
const controller = new AbortController();
const timeout = spyOn(AbortSignal, "timeout").mockReturnValue(
controller.signal,
);
const warning = spyOn(console, "warn").mockImplementation(() => {});
const query = mock(
(_input: unknown, options: { signal?: AbortSignal }) =>
new Promise<{ running: boolean }>((_resolve, reject) => {
options.signal?.addEventListener("abort", () =>
reject(options.signal?.reason),
);
}),
);

try {
const result = probeTerminalRunning(
probeUtils(query),
"workspace",
"term",
);
expect(timeout).toHaveBeenCalledWith(2_000);
expect(query).toHaveBeenCalledWith(
{ terminalId: "term", workspaceId: "workspace" },
{ signal: controller.signal, context: { skipBatch: true } },
);
controller.abort(new DOMException("Timed out", "TimeoutError"));
expect(await result).toBe(false);
expect(warning).toHaveBeenCalledTimes(1);
} finally {
timeout.mockRestore();
warning.mockRestore();
}
});

for (const running of [true, false]) {
test(`returns the live running state (${running})`, async () => {
const query = mock(async () => ({ running }));
expect(
await probeTerminalRunning(probeUtils(query), "workspace", "term"),
).toBe(running);
});
}
});

test("checks a tab's terminals concurrently before allowing its close", async () => {
const first = Promise.withResolvers<boolean>();
const second = Promise.withResolvers<boolean>();
const suppressed = useTerminalCloseConfirmStore.getState().suppressed;
const saved = localStorage.getItem("terminal-close-confirm-v1");
useTerminalCloseConfirmStore.setState({ suppressed: false });
const isRunning = mock((id: string) =>
id === "first" ? first.promise : second.promise,
);
const result = confirmCloseTerminals(["first", "second"], isRunning, {
title: "Close terminals",
description: "A process is running",
confirmLabel: "Close",
});
try {
expect(isRunning.mock.calls.map(([id]) => id)).toEqual(["first", "second"]);
first.resolve(false);
second.resolve(false);
expect(await result).toBe(true);
} finally {
first.resolve(false);
second.resolve(false);
await result;
useTerminalCloseConfirmStore.setState({ suppressed });
if (saved === null) localStorage.removeItem("terminal-close-confirm-v1");
else localStorage.setItem("terminal-close-confirm-v1", saved);
}
});
38 changes: 21 additions & 17 deletions apps/desktop/src/renderer/lib/terminal/confirm-close-terminals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,25 @@ import { useTerminalCloseConfirmStore } from "renderer/stores/terminal-close-con

type WorkspaceTrpcUtils = ReturnType<typeof workspaceTrpc.useUtils>;

const RUNNING_PROCESS_PROBE_TIMEOUT_MS = 2_000;

/**
* Fetch whether a foreground process is running in a terminal. Probes live
* state (staleTime: 0), and reports "not running" on any error so a failed
* probe never blocks the close.
* state without the query cache, and reports "not running" on errors or
* timeouts so a failed probe never blocks the close.
*/
export async function probeTerminalRunning(
utils: WorkspaceTrpcUtils,
workspaceId: string,
terminalId: string,
): Promise<boolean> {
try {
const { running } = await utils.terminal.hasRunningProcess.fetch(
const { running } = await utils.client.terminal.hasRunningProcess.query(
{ terminalId, workspaceId },
{ staleTime: 0 },
{
signal: AbortSignal.timeout(RUNNING_PROCESS_PROBE_TIMEOUT_MS),
context: { skipBatch: true },
},
);
return running;
} catch (error) {
Expand Down Expand Up @@ -51,20 +56,19 @@ export async function confirmCloseTerminals(
): Promise<boolean> {
if (useTerminalCloseConfirmStore.getState().suppressed) return true;

let running = false;
for (const terminalId of terminalIds) {
// Backgrounded terminals stay alive on close, so nothing is killed.
if (hasTerminalBackgroundIntent(terminalId)) continue;
try {
if (await isRunning(terminalId)) {
running = true;
break;
const runningStates = await Promise.all(
terminalIds.map(async (terminalId) => {
// Backgrounded terminals stay alive on close, so nothing is killed.
if (hasTerminalBackgroundIntent(terminalId)) return false;
try {
return await isRunning(terminalId);
} catch {
// If we can't tell, don't block the user from closing.
return false;
}
} catch {
// If we can't tell, don't block the user from closing.
}
}
if (!running) return true;
}),
);
if (!runningStates.some(Boolean)) return true;

return new Promise<boolean>((resolve) => {
const shown = alert({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,78 @@ describe("createHostServiceLinks", () => {
expect(methods).toEqual(["POST"]);
});

test("replays a query over GET when a pre-1.24 host rejects the POST", async () => {
const { client, methods } = fakeHost("http://legacy.test", {
allowMethodOverride: false,
for (const skipBatch of [false, true]) {
test(`replays a query over GET when a pre-1.24 host rejects the POST (skipBatch=${skipBatch})`, async () => {
const { client, methods } = fakeHost(`http://legacy-${skipBatch}.test`, {
allowMethodOverride: false,
});

expect(
await client.settings.agentConfigs.list.query(undefined, {
context: { skipBatch },
}),
).toEqual([{ id: "claude" }]);
expect(methods).toEqual(["POST", "GET"]);
});
}

expect(await client.settings.agentConfigs.list.query()).toEqual([
{ id: "claude" },
]);
expect(methods).toEqual(["POST", "GET"]);
test("aborts an isolated query while a same-tick sibling stays active", async () => {
const hostUrl = "http://isolated-abort.test";
const requests: Request[] = [];
const dispatched = Promise.withResolvers<void>();
const release = Promise.withResolvers<void>();
hosts.set(hostUrl, async (req) => {
requests.push(req);
if (requests.length === 2 || new URL(req.url).pathname.includes(",")) {
dispatched.resolve();
}
await new Promise<void>((resolve, reject) => {
release.promise.then(resolve);
req.signal.addEventListener("abort", () => reject(req.signal.reason), {
once: true,
});
});
return fetchRequestHandler({
endpoint: "/trpc",
req,
router,
allowMethodOverride: true,
});
});
const client = createTRPCClient<TestRouter>({
links: createHostServiceLinks({
url: `${hostUrl}/trpc`,
}) as unknown as TRPCLink<TestRouter>[],
});
const controller = new AbortController();
let probeAborted = false;
let siblingSettled = false;
const probe = client.settings.agentConfigs.list
.query(undefined, {
signal: controller.signal,
context: { skipBatch: true },
})
.catch(() => {
probeAborted = true;
});
const sibling = client.settings.agentConfigs.echo
.query({ n: 42 })
.finally(() => {
siblingSettled = true;
});
try {
await dispatched.promise;
controller.abort();
await Bun.sleep(0);
expect(probeAborted).toBe(true);
expect(siblingSettled).toBe(false);
expect(requests).toHaveLength(2);
expect(requests.filter((req) => req.signal.aborted)).toHaveLength(1);
} finally {
release.resolve();
await Promise.allSettled([probe, sibling]);
}
expect(await sibling).toEqual({ n: 42 });
});

test("remembers a legacy host so later queries skip the failing POST", async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { AppRouter } from "@superset/host-service/trpc";
import {
httpBatchStreamLink,
httpLink,
retryLink,
splitLink,
TRPCClientError,
Expand Down Expand Up @@ -69,6 +70,12 @@ export function createHostServiceLinks(
): TRPCLink<AppRouter>[] {
const { url, headers } = options;
const shared = { url, transformer: superjson, headers };
const transport = (methodOverride?: "POST") =>
splitLink<AppRouter>({
condition: (op) => op.context.skipBatch === true,
true: httpLink({ ...shared, methodOverride }),
false: httpBatchStreamLink({ ...shared, methodOverride }),
});
return [
retryLink({
retry: ({ op, error, attempts }) => {
Expand All @@ -84,8 +91,8 @@ export function createHostServiceLinks(
}),
splitLink({
condition: () => legacyGetEndpoints.has(url),
true: httpBatchStreamLink(shared),
false: httpBatchStreamLink({ ...shared, methodOverride: "POST" }),
true: transport(),
false: transport("POST"),
}),
];
}
Loading