Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge bd0cd27d4b Format provider update pill optimization
Co-authored-by: Julius Marminge <[email protected]>
2026-07-12 16:14:57 +00:00
Cursor AgentandJulius Marminge c10530288c Optimize provider update sidebar pill renders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-12 16:10:53 +00:00
3 changed files with 159 additions and 271 deletions

No files matched your search

@@ -1,4 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -42,7 +42,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
assert.deepEqual(rows, [
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
@@ -126,21 +126,15 @@ describe("ProcessDiagnostics", () => {
],
});
assert.equal(diagnostics.serverPid, 100);
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
assert.equal(diagnostics.processCount, 2);
assert.equal(diagnostics.totalRssBytes, 6_000);
assert.equal(diagnostics.totalCpuPercent, 4.75);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102],
);
assert.deepEqual(
diagnostics.processes.map((process) => process.depth),
[0, 1],
);
assert.equal(Option.getOrNull(diagnostics.processes[0]!.pgid), 100);
assert.deepEqual(diagnostics.processes[0]?.childPids, [102]);
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
@@ -183,10 +177,7 @@ describe("ProcessDiagnostics", () => {
],
});
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102, 103],
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
@@ -219,11 +210,8 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[4242],
);
assert.deepEqual(commands, [
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
@@ -253,7 +241,7 @@ describe("ProcessDiagnostics", () => {
Effect.flip,
);
assert.deepInclude(error, {
expect(error).toMatchObject({
_tag: "ProcessDiagnosticsQueryFailedError",
command: "ps",
argCount: 2,
@@ -264,8 +252,7 @@ describe("ProcessDiagnostics", () => {
stdoutTruncated: false,
stderrTruncated: false,
});
assert.equal(
error.message,
expect(error.message).toBe(
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
);
}),
@@ -293,7 +280,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(result, {
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
@@ -301,85 +288,4 @@ describe("ProcessDiagnostics", () => {
});
}),
);
it.effect("parses Windows JSON process rows through Schema", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: JSON.stringify([
{
ProcessId: 4242,
ParentProcessId: process.pid,
Name: "agent.exe",
CommandLine: "agent.exe --flag",
Status: "Running",
WorkingSetSize: 4096,
PercentProcessorTime: 12.5,
},
{
ProcessId: 4243,
ParentProcessId: 4242,
Name: "fallback.exe",
CommandLine: null,
Status: null,
WorkingSetSize: null,
PercentProcessorTime: null,
},
{
ProcessId: "not-a-number",
ParentProcessId: process.pid,
Name: "ignored.exe",
CommandLine: "ignored.exe",
},
]),
}),
);
}),
);
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
Effect.provide(spawnerLayer),
Effect.provideService(HostProcessPlatform, "win32"),
);
assert.deepEqual(rows, [
{
pid: 4242,
ppid: process.pid,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 4096,
elapsed: "",
command: "agent.exe --flag",
},
{
pid: 4243,
ppid: 4242,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "fallback.exe",
},
]);
assert.equal(commands[0]?.command, "powershell.exe");
assert.deepEqual(commands[0]?.args.slice(0, 3), [
"-NoProfile",
"-NonInteractive",
"-Command",
]);
}),
);
});
@@ -32,19 +32,6 @@ const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Name: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeOption(Schema.UnknownFromJsonString);
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
export class ProcessDiagnostics extends Context.Service<
ProcessDiagnostics,
{
@@ -134,47 +121,19 @@ const ProcessDiagnosticsError = Schema.Union([
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
function parsePositiveInt(value: string): Option.Option<number> {
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? Option.some(parsed) : Option.none();
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function parseNonNegativeInt(value: string): Option.Option<number> {
function parseNonNegativeInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed >= 0 ? Option.some(parsed) : Option.none();
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function parseInteger(value: string): Option.Option<number> {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) ? Option.some(parsed) : Option.none();
}
function parseNumber(value: string): Option.Option<number> {
function parseNumber(value: string): number | null {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? Option.some(parsed) : Option.none();
}
function positiveInteger(value: number): Option.Option<number> {
return Number.isInteger(value) && value > 0 ? Option.some(value) : Option.none();
}
function nonNegativeInteger(value: number): Option.Option<number> {
return Number.isInteger(value) && value >= 0 ? Option.some(value) : Option.none();
}
function trimNonEmpty(value: string | null | undefined): Option.Option<string> {
return Option.fromNullishOr(value).pipe(
Option.map((text) => text.trim()),
Option.filter((text) => text.length > 0),
);
}
function finiteNonNegativeNumberOrZero(value: number | null | undefined): number {
return Option.fromNullishOr(value).pipe(
Option.filter(Number.isFinite),
Option.map((number) => Math.max(0, number)),
Option.getOrElse(() => 0),
);
return Number.isFinite(parsed) ? parsed : null;
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
@@ -209,24 +168,31 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
continue;
}
const parsed = Option.all({
pid: parsePositiveInt(pidText),
ppid: parseNonNegativeInt(ppidText),
pgid: parseInteger(pgidText),
cpuPercent: parseNumber(cpuText),
rssKiB: parseNonNegativeInt(rssText),
});
if (Option.isNone(parsed) || !status || !elapsed || !command) {
const pid = parsePositiveInt(pidText);
const ppid = parseNonNegativeInt(ppidText);
const pgid = Number.parseInt(pgidText, 10);
const cpuPercent = parseNumber(cpuText);
const rssKiB = parseNonNegativeInt(rssText);
if (
pid === null ||
ppid === null ||
!Number.isInteger(pgid) ||
cpuPercent === null ||
rssKiB === null ||
!status ||
!elapsed ||
!command
) {
continue;
}
rows.push({
pid: parsed.value.pid,
ppid: parsed.value.ppid,
pgid: parsed.value.pgid,
pid,
ppid,
pgid,
status,
cpuPercent: parsed.value.cpuPercent,
rssBytes: parsed.value.rssKiB * 1024,
cpuPercent,
rssBytes: rssKiB * 1024,
elapsed,
command,
});
@@ -235,38 +201,51 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return Option.gen(function* () {
const record: WindowsProcessRecord = yield* decodeWindowsProcessRecord(value);
const pid = yield* positiveInteger(record.ProcessId);
const ppid = yield* nonNegativeInteger(record.ParentProcessId);
const command = yield* Option.firstSomeOf([
trimNonEmpty(record.CommandLine),
trimNonEmpty(record.Name),
]);
const status = Option.getOrElse(trimNonEmpty(record.Status), () => "Live");
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
return {
pid,
ppid,
pgid: null,
status,
cpuPercent: finiteNonNegativeNumberOrZero(record.PercentProcessorTime),
rssBytes: Math.round(finiteNonNegativeNumberOrZero(record.WorkingSetSize)),
elapsed: "",
command,
};
});
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) return [];
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return Option.isSome(row) ? [row.value] : [];
});
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
}
export function buildDescendantEntries(
@@ -38,33 +38,75 @@ function latestProviderCheckedAt(
);
}
interface SidebarProviderUpdatePillContentProps {
readonly providers: ReadonlyArray<ServerProvider>;
readonly onOpenProviderSettings: () => void;
}
interface ProviderUpdatePillExitState {
readonly view: ProviderUpdateSidebarPillView;
readonly dismissAfterExitKey: string | null;
}
function useProviderUpdatePillAutoDismiss({
displayedView,
exitingKey,
startExit,
}: {
readonly displayedView: ProviderUpdateSidebarPillView | null;
readonly exitingKey: string | null;
readonly startExit: (view: ProviderUpdateSidebarPillView, dismissKey?: string) => void;
}) {
const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;
const viewKey = displayedView?.key ?? null;
useEffect(() => {
if (!displayedView || !dismissAfterVisibleMs || !viewKey) {
return;
}
if (exitingKey === viewKey) {
return;
}
const timeoutId = window.setTimeout(() => {
startExit(displayedView, viewKey);
}, dismissAfterVisibleMs);
return () => window.clearTimeout(timeoutId);
}, [dismissAfterVisibleMs, displayedView, exitingKey, startExit, viewKey]);
}
export function SidebarProviderUpdatePill() {
const navigate = useNavigate();
const providers = useAtomValue(primaryServerProvidersAtom);
const [dismissedKeys, setDismissedKeys] = useState<ReadonlySet<string>>(() => new Set());
const [renderedView, setRenderedView] = useState<ProviderUpdateSidebarPillView | null>(null);
const [pendingView, setPendingView] = useState<ProviderUpdateSidebarPillView | null>(null);
const [exitingKey, setExitingKey] = useState<string | null>(null);
const [dismissAfterExitKey, setDismissAfterExitKey] = useState<string | null>(null);
const [visibleAfterIso, setVisibleAfterIso] = useState<string | undefined>();
const effectiveVisibleAfterIso = visibleAfterIso ?? latestProviderCheckedAt(providers);
const view = getProviderUpdateSidebarPillView(providers, {
...(effectiveVisibleAfterIso !== undefined
? { visibleAfterIso: effectiveVisibleAfterIso }
: {}),
dismissedKeys,
});
useEffect(() => {
if (visibleAfterIso === undefined && effectiveVisibleAfterIso !== undefined) {
setVisibleAfterIso(effectiveVisibleAfterIso);
}
}, [effectiveVisibleAfterIso, visibleAfterIso]);
const openProviderSettings = useCallback(() => {
void navigate({ to: "/settings/providers" });
}, [navigate]);
const displayedView = renderedView ?? view;
if (providers.length === 0) {
return null;
}
return (
<SidebarProviderUpdatePillContent
providers={providers}
onOpenProviderSettings={openProviderSettings}
/>
);
}
export function SidebarProviderUpdatePillContent({
providers,
onOpenProviderSettings,
}: SidebarProviderUpdatePillContentProps) {
const [dismissedKeys, setDismissedKeys] = useState<ReadonlySet<string>>(() => new Set());
const [visibleAfterIso] = useState(() => latestProviderCheckedAt(providers));
const view = getProviderUpdateSidebarPillView(providers, {
...(visibleAfterIso !== undefined ? { visibleAfterIso } : {}),
dismissedKeys,
});
const [exitState, setExitState] = useState<ProviderUpdatePillExitState | null>(null);
const displayedView = exitState?.view ?? view;
const exitingKey = exitState?.view.key ?? null;
const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;
const viewKey = displayedView?.key ?? null;
const showDismissProgress =
@@ -72,51 +114,15 @@ export function SidebarProviderUpdatePill() {
displayedView?.tone !== "loading" &&
exitingKey !== viewKey;
const startExit = useCallback(
(key: string, nextView: ProviderUpdateSidebarPillView | null, dismissKey?: string) => {
if (exitingKey === key) {
return;
}
setPendingView(nextView);
setExitingKey(key);
setDismissAfterExitKey(dismissKey ?? null);
},
[exitingKey],
);
const startExit = useCallback((exitView: ProviderUpdateSidebarPillView, dismissKey?: string) => {
setExitState((current) =>
current?.view.key === exitView.key
? current
: { view: exitView, dismissAfterExitKey: dismissKey ?? null },
);
}, []);
useEffect(() => {
if (exitingKey !== null) {
return;
}
if (!renderedView) {
if (view) {
setRenderedView(view);
}
return;
}
if (!view) {
startExit(renderedView.key, null);
return;
}
if (view.key !== renderedView.key) {
startExit(renderedView.key, view);
return;
}
}, [exitingKey, renderedView, startExit, view]);
useEffect(() => {
if (!dismissAfterVisibleMs || !viewKey) {
return;
}
if (exitingKey === viewKey) {
return;
}
const timeoutId = window.setTimeout(() => {
startExit(viewKey, null, viewKey);
}, dismissAfterVisibleMs);
return () => window.clearTimeout(timeoutId);
}, [dismissAfterVisibleMs, exitingKey, startExit, viewKey]);
useProviderUpdatePillAutoDismiss({ displayedView, exitingKey, startExit });
if (!displayedView) {
return null;
@@ -138,13 +144,10 @@ export function SidebarProviderUpdatePill() {
if (!displayedView || exitingKey !== displayedView.key) {
return;
}
if (dismissAfterExitKey === displayedView.key) {
if (exitState?.dismissAfterExitKey === displayedView.key) {
setDismissedKeys((previous) => new Set(previous).add(displayedView.key));
}
setRenderedView(pendingView);
setPendingView(null);
setExitingKey(null);
setDismissAfterExitKey(null);
setExitState(null);
}}
>
{showDismissProgress ? (
@@ -169,7 +172,7 @@ export function SidebarProviderUpdatePill() {
type="button"
aria-label={displayedView.description}
className="provider-update-main relative z-[1] flex h-full flex-1 items-center gap-2 px-2 text-left"
onClick={openProviderSettings}
onClick={onOpenProviderSettings}
>
{displayedView.tone === "loading" ? (
<LoaderIcon className="size-3.5 animate-spin" />
@@ -194,7 +197,7 @@ export function SidebarProviderUpdatePill() {
type="button"
aria-label="Dismiss provider update notice"
className="relative z-[1] mr-1 inline-flex size-5 items-center justify-center rounded-md opacity-70 transition-opacity hover:opacity-100"
onClick={() => startExit(displayedView.key, null, displayedView.key)}
onClick={() => startExit(displayedView, displayedView.key)}
>
<XIcon className="size-3.5" />
</button>