Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 993571a491 Add React Scan root shell recordings
Co-authored-by: Julius Marminge <[email protected]>
2026-05-21 16:24:45 +00:00
Cursor AgentandJulius Marminge 4b87dbf7d7 Stabilize root app shell renders
Co-authored-by: Julius Marminge <[email protected]>
2026-05-21 16:23:00 +00:00
7 changed files with 156 additions and 350 deletions

No files matched your search

@@ -1,9 +1,8 @@
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";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -11,7 +10,6 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
const encoder = new TextEncoder();
const encodeJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
function mockHandle(result: {
readonly stdout?: string;
@@ -43,7 +41,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
assert.deepEqual(rows, [
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
@@ -127,21 +125,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]);
}),
);
@@ -184,10 +176,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]);
}),
);
@@ -195,8 +184,9 @@ describe("ProcessDiagnostics", () => {
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) => {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -210,8 +200,8 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
}),
);
},
});
}),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
@@ -219,11 +209,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="],
@@ -232,64 +219,11 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("decodes Windows process rows through Schema JSON parsing", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (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: encodeJsonString([
{
ProcessId: 4242,
ParentProcessId: 100,
Name: "node.exe",
CommandLine: "node server.js",
Status: "Running",
WorkingSetSize: 2048,
PercentProcessorTime: 12.5,
},
{
ProcessId: 0,
ParentProcessId: 100,
Name: "invalid.exe",
},
]),
}),
);
},
});
const rows = yield* ProcessDiagnostics.readProcessRows("win32").pipe(
Effect.provide(spawnerLayer),
);
assert.deepEqual(rows, [
{
pid: 4242,
ppid: 100,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 2048,
elapsed: "",
command: "node server.js",
},
]);
assert.equal(commands[0]?.command, "powershell.exe");
}),
);
it.effect("does not allow signaling the diagnostics query process", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: () =>
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
mockHandle({
stdout: [
@@ -298,7 +232,8 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
}),
),
});
),
);
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
@@ -306,7 +241,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(result, {
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
+31 -128
View File
@@ -26,7 +26,7 @@ export interface ProcessRow {
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
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;
@@ -43,73 +43,17 @@ export class ProcessDiagnostics extends Context.Service<
ProcessDiagnosticsShape
>()("t3/diagnostics/ProcessDiagnostics") {}
class ProcessQueryError extends Schema.TaggedErrorClass<ProcessQueryError>()("ProcessQueryError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
class ProcessQueryTimeoutError extends Schema.TaggedErrorClass<ProcessQueryTimeoutError>()(
"ProcessQueryTimeoutError",
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
"ProcessDiagnosticsError",
{
message: Schema.String,
timeoutMillis: Schema.Number,
},
) {}
class ProcessCommandExitError extends Schema.TaggedErrorClass<ProcessCommandExitError>()(
"ProcessCommandExitError",
{
message: Schema.String,
command: Schema.String,
exitCode: Schema.Number,
stderr: Schema.String,
},
) {}
class ProcessSignalRejectedError extends Schema.TaggedErrorClass<ProcessSignalRejectedError>()(
"ProcessSignalRejectedError",
{
message: Schema.String,
pid: Schema.Number,
reason: Schema.String,
},
) {}
class ProcessSignalFailedError extends Schema.TaggedErrorClass<ProcessSignalFailedError>()(
"ProcessSignalFailedError",
{
message: Schema.String,
pid: Schema.Number,
signal: Schema.Literals(["SIGINT", "SIGKILL"]),
cause: Schema.optional(Schema.Defect),
},
) {}
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
type ProcessDiagnosticsError =
| ProcessQueryError
| ProcessQueryTimeoutError
| ProcessCommandExitError
| ProcessSignalRejectedError
| ProcessSignalFailedError;
const isProcessQueryError = Schema.is(ProcessQueryError);
const isProcessQueryTimeoutError = Schema.is(ProcessQueryTimeoutError);
const isProcessCommandExitError = Schema.is(ProcessCommandExitError);
const isProcessSignalRejectedError = Schema.is(ProcessSignalRejectedError);
const isProcessSignalFailedError = Schema.is(ProcessSignalFailedError);
function isProcessDiagnosticsError(error: unknown): error is ProcessDiagnosticsError {
return (
isProcessQueryError(error) ||
isProcessQueryTimeoutError(error) ||
isProcessCommandExitError(error) ||
isProcessSignalRejectedError(error) ||
isProcessSignalFailedError(error)
);
}
function makeProcessQueryError(message: string, cause?: unknown): ProcessQueryError {
return new ProcessQueryError({
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new ProcessDiagnosticsError({
message,
...(cause === undefined ? {} : { cause }),
});
@@ -130,22 +74,6 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
const WindowsProcessRowSchema = Schema.Struct({
ProcessId: Schema.optional(Schema.Number),
ParentProcessId: Schema.optional(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.Number),
PercentProcessorTime: Schema.optional(Schema.Number),
});
type WindowsProcessRow = typeof WindowsProcessRowSchema.Type;
const WindowsProcessRowsJsonSchema = Schema.fromJsonString(
Schema.Union([Schema.Array(WindowsProcessRowSchema), WindowsProcessRowSchema]),
);
const decodeWindowsProcessRowsJsonOption = Schema.decodeUnknownOption(WindowsProcessRowsJsonSchema);
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -211,7 +139,9 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(record: WindowsProcessRow): ProcessRow | null {
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 =
@@ -244,15 +174,16 @@ function normalizeWindowsProcessRow(record: WindowsProcessRow): ProcessRow | nul
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
const decoded = decodeWindowsProcessRowsJsonOption(output);
if (Option.isNone(decoded)) return [];
const records = Array.isArray(decoded.value) ? decoded.value : [decoded.value];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
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(
@@ -378,21 +309,17 @@ const runProcess = Effect.fn("runProcess")(
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new ProcessQueryTimeoutError({
message: `${input.errorMessage} timed out.`,
timeoutMillis: Duration.toMillis(PROCESS_QUERY_TIMEOUT),
}),
),
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
onSome: Effect.succeed,
}),
),
Effect.mapError((cause) =>
isProcessDiagnosticsError(cause) ? cause : makeProcessQueryError(input.errorMessage, cause),
isProcessDiagnosticsError(cause)
? cause
: toProcessDiagnosticsError(input.errorMessage, cause),
),
),
);
@@ -409,14 +336,7 @@ function readPosixProcessRows(): Effect.Effect<
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
new ProcessCommandExitError({
message: result.stderr.trim() || "ps failed.",
command: "ps",
exitCode: result.exitCode,
stderr: result.stderr,
}),
)
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
: Effect.succeed(parsePosixProcessRows(result.stdout)),
),
);
@@ -443,12 +363,7 @@ function readWindowsProcessRows(): Effect.Effect<
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
new ProcessCommandExitError({
message: result.stderr.trim() || "PowerShell process query failed.",
command: "powershell.exe",
exitCode: result.exitCode,
stderr: result.stderr,
}),
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
)
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
),
@@ -470,13 +385,7 @@ function assertDescendantPid(
pid: number,
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
if (pid === process.pid) {
return Effect.fail(
new ProcessSignalRejectedError({
message: "Refusing to signal the T3 server process.",
pid,
reason: "self",
}),
);
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
}
return readProcessRows().pipe(
@@ -488,11 +397,7 @@ function assertDescendantPid(
return descendant
? Effect.void
: Effect.fail(
new ProcessSignalRejectedError({
message: `Process ${pid} is not a live descendant of the T3 server.`,
pid,
reason: "not-descendant",
}),
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
);
}),
);
@@ -533,12 +438,10 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
};
},
catch: (cause) =>
new ProcessSignalFailedError({
message: `Failed to signal process ${input.pid} with ${input.signal}.`,
pid: input.pid,
signal: input.signal,
toProcessDiagnosticsError(
`Failed to signal process ${input.pid} with ${input.signal}.`,
cause,
}),
),
}),
),
Effect.catch((error: ProcessDiagnosticsError) =>
@@ -5,12 +5,9 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
const encodeTraceRecordJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
function ns(ms: number): string {
return String(BigInt(ms) * 1_000_000n);
}
@@ -24,7 +21,7 @@ function record(input: {
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
readonly events?: ReadonlyArray<unknown>;
}) {
return encodeTraceRecordJson({
return JSON.stringify({
type: "effect-span",
name: input.name,
traceId: input.traceId,
+77 -110
View File
@@ -14,7 +14,23 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
interface TraceRecordLike {
readonly name?: unknown;
readonly traceId?: unknown;
readonly spanId?: unknown;
readonly startTimeUnixNano?: unknown;
readonly endTimeUnixNano?: unknown;
readonly durationMs?: unknown;
readonly exit?: unknown;
readonly events?: unknown;
}
interface TraceEventLike {
readonly name?: unknown;
readonly timeUnixNano?: unknown;
readonly attributes?: unknown;
}
export interface TraceDiagnosticsOptions {
readonly traceFilePath: string;
@@ -49,35 +65,6 @@ interface TraceDiagnosticsErrorSummary {
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
const TOP_LIMIT = 10;
const RECENT_LIMIT = 20;
const TraceExitSchema = Schema.Struct({
_tag: Schema.optional(Schema.Unknown),
cause: Schema.optional(Schema.Unknown),
});
type TraceExit = typeof TraceExitSchema.Type;
const decodeTraceExitOption = Schema.decodeUnknownOption(TraceExitSchema);
const TraceEventSchema = Schema.Struct({
name: Schema.optional(Schema.Unknown),
timeUnixNano: Schema.optional(Schema.Unknown),
attributes: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
});
const decodeTraceEventOption = Schema.decodeUnknownOption(TraceEventSchema);
const TraceRecordJsonSchema = Schema.fromJsonString(
Schema.Struct({
name: Schema.optional(Schema.Unknown),
traceId: Schema.optional(Schema.Unknown),
spanId: Schema.optional(Schema.Unknown),
startTimeUnixNano: Schema.optional(Schema.Unknown),
endTimeUnixNano: Schema.optional(Schema.Unknown),
durationMs: Schema.optional(Schema.Unknown),
exit: Schema.optional(Schema.Unknown),
events: Schema.optional(Schema.Array(Schema.Unknown)),
}),
);
const decodeTraceRecordJsonOption = Schema.decodeUnknownOption(TraceRecordJsonSchema);
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
const backupCount = Math.max(0, Math.floor(maxFiles));
const backups = Array.from(
@@ -87,55 +74,47 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
return [...backups, traceFilePath];
}
function toStringOption(value: unknown): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
function isRecordObject(value: unknown): value is TraceRecordLike {
return typeof value === "object" && value !== null;
}
function toNumberOption(value: unknown): Option.Option<number> {
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
function toStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
const text = toStringOption(value);
if (Option.isNone(text)) return Option.none();
function toNumberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
const text = toStringValue(value);
if (!text) return null;
try {
const millis = Number(BigInt(text.value) / 1_000_000n);
return DateTime.make(millis);
const millis = Number(BigInt(text) / 1_000_000n);
return Option.getOrNull(DateTime.make(millis));
} catch {
return Option.none();
return null;
}
}
function decodeTraceExit(exit: unknown): Option.Option<TraceExit> {
return decodeTraceExitOption(exit);
}
function readExitTag(exit: unknown): Option.Option<string> {
return Option.flatMap(decodeTraceExit(exit), (parsedExit) => toStringOption(parsedExit._tag));
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
return toStringValue(exit._tag);
}
function readExitCause(exit: unknown): string {
return Option.getOrElse(
Option.flatMap(decodeTraceExit(exit), (parsedExit) => toStringOption(parsedExit.cause)),
() => "Failure",
).trim();
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
return toStringValue(exit.cause)?.trim() ?? "Failure";
}
function minDateTimeOption(
current: Option.Option<DateTime.Utc>,
candidate: Option.Option<DateTime.Utc>,
): Option.Option<DateTime.Utc> {
if (Option.isNone(candidate)) return current;
if (Option.isNone(current)) return candidate;
return DateTime.isLessThan(candidate.value, current.value) ? candidate : current;
function isTraceEvent(value: unknown): value is TraceEventLike {
return typeof value === "object" && value !== null;
}
function maxDateTime(
current: Option.Option<DateTime.Utc>,
candidate: DateTime.Utc,
): Option.Option<DateTime.Utc> {
if (Option.isNone(current)) return Option.some(candidate);
return DateTime.isGreaterThan(candidate, current.value) ? Option.some(candidate) : current;
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
return typeof event.attributes === "object" && event.attributes !== null
? (event.attributes as Readonly<Record<string, unknown>>)
: {};
}
function makeEmptyDiagnostics(input: {
@@ -220,8 +199,8 @@ export function aggregateTraceDiagnostics(
let failureCount = 0;
let interruptionCount = 0;
let slowSpanCount = 0;
let firstSpanAt = Option.none<DateTime.Utc>();
let lastSpanAt = Option.none<DateTime.Utc>();
let firstSpanAt: DateTime.Utc | null = null;
let lastSpanAt: DateTime.Utc | null = null;
const spansByName = new Map<
string,
@@ -238,42 +217,42 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
const decodedRecord = decodeTraceRecordJsonOption(line);
if (Option.isNone(decodedRecord)) {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
parseErrorCount += 1;
continue;
}
const parsed = decodedRecord.value;
const nameOption = toStringOption(parsed.name);
const traceIdOption = toStringOption(parsed.traceId);
const spanIdOption = toStringOption(parsed.spanId);
const durationMsOption = toNumberOption(parsed.durationMs);
if (!isRecordObject(parsed)) {
parseErrorCount += 1;
continue;
}
const name = toStringValue(parsed.name);
const traceId = toStringValue(parsed.traceId);
const spanId = toStringValue(parsed.spanId);
const durationMs = toNumberValue(parsed.durationMs);
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (
Option.isNone(nameOption) ||
Option.isNone(traceIdOption) ||
Option.isNone(spanIdOption) ||
Option.isNone(durationMsOption) ||
Option.isNone(endedAt)
) {
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
parseErrorCount += 1;
continue;
}
const name = nameOption.value;
const traceId = traceIdOption.value;
const spanId = spanIdOption.value;
const durationMs = durationMsOption.value;
recordCount += 1;
firstSpanAt = minDateTimeOption(firstSpanAt, startedAt);
lastSpanAt = maxDateTime(lastSpanAt, endedAt.value);
firstSpanAt =
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
const exitTag = readExitTag(parsed.exit);
const isFailure = Option.contains(exitTag, "Failure");
const isInterrupted = Option.contains(exitTag, "Interrupted");
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
if (isFailure) failureCount += 1;
if (isInterrupted) interruptionCount += 1;
@@ -289,7 +268,7 @@ export function aggregateTraceDiagnostics(
if (isFailure) spanSummary.failureCount += 1;
spansByName.set(name, spanSummary);
const spanItem = { name, durationMs, endedAt: endedAt.value, traceId, spanId };
const spanItem = { name, durationMs, endedAt, traceId, spanId };
if (durationMs >= slowSpanThresholdMs) {
slowSpanCount += 1;
}
@@ -301,13 +280,12 @@ export function aggregateTraceDiagnostics(
const failureKey = `${name}\0${cause}`;
const existing = failuresByKey.get(failureKey);
const isLatestFailure =
!existing || DateTime.isGreaterThan(endedAt.value, existing.lastSeenAt);
const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);
failuresByKey.set(failureKey, {
name,
cause,
count: (existing?.count ?? 0) + 1,
lastSeenAt: isLatestFailure ? endedAt.value : existing!.lastSeenAt,
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
traceId: isLatestFailure ? traceId : existing!.traceId,
spanId: isLatestFailure ? spanId : existing!.spanId,
});
@@ -315,15 +293,10 @@ export function aggregateTraceDiagnostics(
if (Array.isArray(parsed.events)) {
for (const rawEvent of parsed.events) {
const event = decodeTraceEventOption(rawEvent);
if (Option.isNone(event)) continue;
const attributes = Option.getOrElse(
Option.fromUndefinedOr(event.value.attributes),
() => ({}) as Readonly<Record<string, unknown>>,
);
const levelOption = toStringOption(attributes["effect.logLevel"]);
if (Option.isNone(levelOption)) continue;
const level = levelOption.value;
if (!isTraceEvent(rawEvent)) continue;
const attributes = readEventAttributes(rawEvent);
const level = toStringValue(attributes["effect.logLevel"]);
if (!level) continue;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
@@ -336,14 +309,8 @@ export function aggregateTraceDiagnostics(
continue;
}
const seenAt = Option.getOrElse(
unixNanoToDateTime(event.value.timeUnixNano),
() => endedAt.value,
);
const message = Option.getOrElse(
Option.map(toStringOption(event.value.name), (name) => name.trim()),
() => "Log event",
);
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
latestWarningAndErrorLogs.push({
spanName: name,
level,
@@ -375,8 +342,8 @@ export function aggregateTraceDiagnostics(
readAt,
recordCount,
parseErrorCount,
firstSpanAt,
lastSpanAt,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
failureCount,
interruptionCount,
slowSpanThresholdMs,
+22 -18
View File
@@ -99,19 +99,20 @@ export const Route = createRootRouteWithContext<{
}),
});
const APP_SHELL = (
<CommandPalette>
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</CommandPalette>
);
function RootRouteView() {
const pathname = useLocation({ select: (location) => location.pathname });
const { authGateState } = Route.useRouteContext();
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
useEffect(() => {
const frame = window.requestAnimationFrame(() => {
syncBrowserChromeTheme();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [pathname]);
useBrowserChromeThemeSync(pathname);
if (pathname === "/pair") {
return <Outlet />;
@@ -121,14 +122,6 @@ function RootRouteView() {
return <Outlet />;
}
const appShell = (
<CommandPalette>
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</CommandPalette>
);
return (
<ToastProvider>
<AnchoredToastProvider>
@@ -142,15 +135,26 @@ function RootRouteView() {
{primaryEnvironmentAuthenticated ? <WebSocketConnectionCoordinator /> : null}
{primaryEnvironmentAuthenticated ? <SlowRpcAckToastCoordinator /> : null}
{primaryEnvironmentAuthenticated ? (
<WebSocketConnectionSurface>{appShell}</WebSocketConnectionSurface>
<WebSocketConnectionSurface>{APP_SHELL}</WebSocketConnectionSurface>
) : (
appShell
APP_SHELL
)}
</AnchoredToastProvider>
</ToastProvider>
);
}
function useBrowserChromeThemeSync(pathname: string) {
useEffect(() => {
const frame = window.requestAnimationFrame(() => {
syncBrowserChromeTheme();
});
return () => {
window.cancelAnimationFrame(frame);
};
}, [pathname]);
}
function HostedStaticEnvironmentBootstrap() {
const savedEnvironmentCount = useSavedEnvironmentRegistryStore(
(state) => Object.keys(state.byId).length,