Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge bed9031f02 Use Effect idioms in diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-05-19 16:17:36 +00:00
t3-code[bot] d1e85c4e8f chore(release): prepare v0.0.24 2026-05-15 06:40:13 +00:00
11 changed files with 595 additions and 385 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.23",
"version": "0.0.24",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.23",
"version": "0.0.24",
"license": "MIT",
"repository": {
"type": "git",
@@ -1,8 +1,9 @@
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, 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";
@@ -10,6 +11,7 @@ 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;
@@ -41,7 +43,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
expect(rows).toEqual([
assert.deepEqual(rows, [
{
pid: 10,
ppid: 1,
@@ -125,15 +127,21 @@ describe("ProcessDiagnostics", () => {
],
});
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]);
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]);
}),
);
@@ -176,7 +184,10 @@ describe("ProcessDiagnostics", () => {
],
});
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102, 103],
);
}),
);
@@ -184,9 +195,8 @@ describe("ProcessDiagnostics", () => {
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -200,8 +210,8 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
}),
);
}),
);
},
});
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
@@ -209,8 +219,11 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[4242],
);
assert.deepEqual(commands, [
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
@@ -219,11 +232,64 @@ 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.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: () =>
Effect.succeed(
mockHandle({
stdout: [
@@ -232,8 +298,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
}),
),
),
);
});
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
@@ -241,7 +306,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
expect(result).toEqual({
assert.deepEqual(result, {
pid: 4242,
signal: "SIGINT",
signaled: false,
+128 -31
View File
@@ -26,7 +26,7 @@ export interface ProcessRow {
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
@@ -43,17 +43,73 @@ export class ProcessDiagnostics extends Context.Service<
ProcessDiagnosticsShape
>()("t3/diagnostics/ProcessDiagnostics") {}
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
"ProcessDiagnosticsError",
class ProcessQueryError extends Schema.TaggedErrorClass<ProcessQueryError>()("ProcessQueryError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
class ProcessQueryTimeoutError extends Schema.TaggedErrorClass<ProcessQueryTimeoutError>()(
"ProcessQueryTimeoutError",
{
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);
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new 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({
message,
...(cause === undefined ? {} : { cause }),
});
@@ -74,6 +130,22 @@ 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 =
@@ -139,9 +211,7 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
function normalizeWindowsProcessRow(record: WindowsProcessRow): ProcessRow | null {
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
@@ -174,16 +244,15 @@ function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
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 [];
}
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] : [];
});
}
export function buildDescendantEntries(
@@ -309,17 +378,21 @@ const runProcess = Effect.fn("runProcess")(
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
onNone: () =>
Effect.fail(
new ProcessQueryTimeoutError({
message: `${input.errorMessage} timed out.`,
timeoutMillis: Duration.toMillis(PROCESS_QUERY_TIMEOUT),
}),
),
onSome: Effect.succeed,
}),
),
Effect.mapError((cause) =>
isProcessDiagnosticsError(cause)
? cause
: toProcessDiagnosticsError(input.errorMessage, cause),
isProcessDiagnosticsError(cause) ? cause : makeProcessQueryError(input.errorMessage, cause),
),
),
);
@@ -336,7 +409,14 @@ function readPosixProcessRows(): Effect.Effect<
}).pipe(
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
? Effect.fail(
new ProcessCommandExitError({
message: result.stderr.trim() || "ps failed.",
command: "ps",
exitCode: result.exitCode,
stderr: result.stderr,
}),
)
: Effect.succeed(parsePosixProcessRows(result.stdout)),
),
);
@@ -363,7 +443,12 @@ function readWindowsProcessRows(): Effect.Effect<
Effect.flatMap((result) =>
result.exitCode !== 0
? Effect.fail(
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
new ProcessCommandExitError({
message: result.stderr.trim() || "PowerShell process query failed.",
command: "powershell.exe",
exitCode: result.exitCode,
stderr: result.stderr,
}),
)
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
),
@@ -385,7 +470,13 @@ function assertDescendantPid(
pid: number,
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
if (pid === process.pid) {
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
return Effect.fail(
new ProcessSignalRejectedError({
message: "Refusing to signal the T3 server process.",
pid,
reason: "self",
}),
);
}
return readProcessRows().pipe(
@@ -397,7 +488,11 @@ function assertDescendantPid(
return descendant
? Effect.void
: Effect.fail(
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
new ProcessSignalRejectedError({
message: `Process ${pid} is not a live descendant of the T3 server.`,
pid,
reason: "not-descendant",
}),
);
}),
);
@@ -438,10 +533,12 @@ export const make = Effect.fn("makeProcessDiagnostics")(function* () {
};
},
catch: (cause) =>
toProcessDiagnosticsError(
`Failed to signal process ${input.pid} with ${input.signal}.`,
new ProcessSignalFailedError({
message: `Failed to signal process ${input.pid} with ${input.signal}.`,
pid: input.pid,
signal: input.signal,
cause,
),
}),
}),
),
Effect.catch((error: ProcessDiagnosticsError) =>
@@ -5,9 +5,12 @@ 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);
}
@@ -21,7 +24,7 @@ function record(input: {
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
readonly events?: ReadonlyArray<unknown>;
}) {
return JSON.stringify({
return encodeTraceRecordJson({
type: "effect-span",
name: input.name,
traceId: input.traceId,
+110 -77
View File
@@ -14,23 +14,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
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;
}
import * as Schema from "effect/Schema";
export interface TraceDiagnosticsOptions {
readonly traceFilePath: string;
@@ -65,6 +49,35 @@ 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(
@@ -74,47 +87,55 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
return [...backups, traceFilePath];
}
function isRecordObject(value: unknown): value is TraceRecordLike {
return typeof value === "object" && value !== null;
function toStringOption(value: unknown): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
}
function toStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
function toNumberOption(value: unknown): Option.Option<number> {
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : 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;
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
const text = toStringOption(value);
if (Option.isNone(text)) return Option.none();
try {
const millis = Number(BigInt(text) / 1_000_000n);
return Option.getOrNull(DateTime.make(millis));
const millis = Number(BigInt(text.value) / 1_000_000n);
return DateTime.make(millis);
} catch {
return null;
return Option.none();
}
}
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
return toStringValue(exit._tag);
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 readExitCause(exit: unknown): string {
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
return toStringValue(exit.cause)?.trim() ?? "Failure";
return Option.getOrElse(
Option.flatMap(decodeTraceExit(exit), (parsedExit) => toStringOption(parsedExit.cause)),
() => "Failure",
).trim();
}
function isTraceEvent(value: unknown): value is TraceEventLike {
return typeof value === "object" && value !== null;
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 readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
return typeof event.attributes === "object" && event.attributes !== null
? (event.attributes as Readonly<Record<string, unknown>>)
: {};
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 makeEmptyDiagnostics(input: {
@@ -199,8 +220,8 @@ export function aggregateTraceDiagnostics(
let failureCount = 0;
let interruptionCount = 0;
let slowSpanCount = 0;
let firstSpanAt: DateTime.Utc | null = null;
let lastSpanAt: DateTime.Utc | null = null;
let firstSpanAt = Option.none<DateTime.Utc>();
let lastSpanAt = Option.none<DateTime.Utc>();
const spansByName = new Map<
string,
@@ -217,42 +238,42 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
const decodedRecord = decodeTraceRecordJsonOption(line);
if (Option.isNone(decodedRecord)) {
parseErrorCount += 1;
continue;
}
const parsed = decodedRecord.value;
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 nameOption = toStringOption(parsed.name);
const traceIdOption = toStringOption(parsed.traceId);
const spanIdOption = toStringOption(parsed.spanId);
const durationMsOption = toNumberOption(parsed.durationMs);
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
if (
Option.isNone(nameOption) ||
Option.isNone(traceIdOption) ||
Option.isNone(spanIdOption) ||
Option.isNone(durationMsOption) ||
Option.isNone(endedAt)
) {
parseErrorCount += 1;
continue;
}
const name = nameOption.value;
const traceId = traceIdOption.value;
const spanId = spanIdOption.value;
const durationMs = durationMsOption.value;
recordCount += 1;
firstSpanAt =
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
firstSpanAt = minDateTimeOption(firstSpanAt, startedAt);
lastSpanAt = maxDateTime(lastSpanAt, endedAt.value);
const exitTag = readExitTag(parsed.exit);
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
const isFailure = Option.contains(exitTag, "Failure");
const isInterrupted = Option.contains(exitTag, "Interrupted");
if (isFailure) failureCount += 1;
if (isInterrupted) interruptionCount += 1;
@@ -268,7 +289,7 @@ export function aggregateTraceDiagnostics(
if (isFailure) spanSummary.failureCount += 1;
spansByName.set(name, spanSummary);
const spanItem = { name, durationMs, endedAt, traceId, spanId };
const spanItem = { name, durationMs, endedAt: endedAt.value, traceId, spanId };
if (durationMs >= slowSpanThresholdMs) {
slowSpanCount += 1;
}
@@ -280,12 +301,13 @@ export function aggregateTraceDiagnostics(
const failureKey = `${name}\0${cause}`;
const existing = failuresByKey.get(failureKey);
const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);
const isLatestFailure =
!existing || DateTime.isGreaterThan(endedAt.value, existing.lastSeenAt);
failuresByKey.set(failureKey, {
name,
cause,
count: (existing?.count ?? 0) + 1,
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
lastSeenAt: isLatestFailure ? endedAt.value : existing!.lastSeenAt,
traceId: isLatestFailure ? traceId : existing!.traceId,
spanId: isLatestFailure ? spanId : existing!.spanId,
});
@@ -293,10 +315,15 @@ export function aggregateTraceDiagnostics(
if (Array.isArray(parsed.events)) {
for (const rawEvent of parsed.events) {
if (!isTraceEvent(rawEvent)) continue;
const attributes = readEventAttributes(rawEvent);
const level = toStringValue(attributes["effect.logLevel"]);
if (!level) continue;
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;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
@@ -309,8 +336,14 @@ export function aggregateTraceDiagnostics(
continue;
}
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
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",
);
latestWarningAndErrorLogs.push({
spanName: name,
level,
@@ -342,8 +375,8 @@ export function aggregateTraceDiagnostics(
readAt,
recordCount,
parseErrorCount,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
firstSpanAt,
lastSpanAt,
failureCount,
interruptionCount,
slowSpanThresholdMs,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.23",
"version": "0.0.24",
"private": true,
"type": "module",
"scripts": {
@@ -2,7 +2,7 @@
import { CheckIcon } from "lucide-react";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { useCallback, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
ProviderInstanceId,
ProviderDriverKind,
@@ -114,21 +114,6 @@ interface AddProviderInstanceDialogProps {
}
export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderInstanceDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<AddProviderInstanceDialogContent
key={open ? "add-provider-open" : "add-provider-closed"}
onOpenChange={onOpenChange}
/>
</Dialog>
);
}
interface AddProviderInstanceDialogContentProps {
onOpenChange: (open: boolean) => void;
}
function AddProviderInstanceDialogContent({ onOpenChange }: AddProviderInstanceDialogContentProps) {
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
@@ -136,7 +121,8 @@ function AddProviderInstanceDialogContent({ onOpenChange }: AddProviderInstanceD
const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
const [label, setLabel] = useState("");
const [accentColor, setAccentColor] = useState<string>("");
const [customInstanceId, setCustomInstanceId] = useState<string | null>(null);
const [instanceId, setInstanceId] = useState("");
const [instanceIdDirty, setInstanceIdDirty] = useState(false);
// Driver-specific config drafts keyed by driver so toggling between drivers
// during the same dialog session does not lose in-progress input.
const [configByDriver, setConfigByDriver] = useState<Record<string, Record<string, unknown>>>({});
@@ -149,12 +135,32 @@ function AddProviderInstanceDialogContent({ onOpenChange }: AddProviderInstanceD
[settings.providerInstances],
);
// Reset the form every time the dialog opens so each creation starts
// from a clean slate.
useEffect(() => {
if (!open) return;
setDriver(DEFAULT_DRIVER_KIND);
setLabel("");
setAccentColor("");
setInstanceId("");
setWizardStep(0);
setInstanceIdDirty(false);
setConfigByDriver({});
setHasAttemptedSubmit(false);
}, [open]);
// Auto-derive the instance id from driver + label until the user types
// in the Instance ID field directly (after which they own its value).
useEffect(() => {
if (instanceIdDirty) return;
setInstanceId(deriveInstanceId(driver, label));
}, [driver, label, instanceIdDirty]);
const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION;
const driverSettingsFields = useMemo(
() => deriveProviderSettingsFields(driverOption),
[driverOption],
);
const instanceId = customInstanceId ?? deriveInstanceId(driver, label);
const instanceIdError = validateInstanceId(instanceId, existingIds);
const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null;
const previewLabel = label.trim() || `${driverOption.label} Workspace`;
@@ -230,250 +236,256 @@ function AddProviderInstanceDialogContent({ onOpenChange }: AddProviderInstanceD
]);
return (
<DialogPopup className="max-w-xl overflow-hidden">
<div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
<DialogHeader className="border-b border-border/70 bg-background">
<DialogTitle>Add provider instance</DialogTitle>
<DialogDescription>
Configure an additional provider instance — for example, a second Codex install pointed
at a different workspace.
</DialogDescription>
<div className="grid grid-cols-3 gap-2">
{wizardSteps.map((step, index) => (
<button
key={step}
type="button"
className={cn(
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
index === wizardStep
? "border-primary bg-primary/10 ring-1 ring-primary/25"
: index < wizardStep
? "border-border bg-background"
: "border-border bg-muted/40",
)}
onClick={() => setWizardStep(index)}
>
<span
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogPopup className="max-w-xl overflow-hidden">
<div className="flex min-h-0 flex-col overflow-hidden border-foreground/10 bg-background shadow-2xl">
<DialogHeader className="border-b border-border/70 bg-background">
<DialogTitle>Add provider instance</DialogTitle>
<DialogDescription>
Configure an additional provider instance — for example, a second Codex install
pointed at a different workspace.
</DialogDescription>
<div className="grid grid-cols-3 gap-2">
{wizardSteps.map((step, index) => (
<button
key={step}
type="button"
className={cn(
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
index < wizardStep
? "border-primary bg-primary text-primary-foreground"
: index === wizardStep
? "border-primary bg-background"
: "border-muted-foreground/35 bg-background",
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
index === wizardStep
? "border-primary bg-primary/10 ring-1 ring-primary/25"
: index < wizardStep
? "border-border bg-background"
: "border-border bg-muted/40",
)}
aria-hidden
onClick={() => setWizardStep(index)}
>
{index < wizardStep ? <CheckIcon className="size-3" /> : null}
</span>
<span className="text-[10px] font-medium uppercase text-muted-foreground">
Step {index + 1}
</span>
<span className="truncate text-xs font-semibold text-foreground">
{step}
{index < wizardStep && wizardStepSummaries[index]
? `: ${wizardStepSummaries[index]}`
: ""}
</span>
</button>
))}
</div>
</DialogHeader>
<div
data-slot="dialog-panel"
className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"
>
<AnimatedHeight>
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
<span id="add-instance-driver-label" className="text-xs font-medium text-foreground">
Driver
</span>
<RadioGroup
value={driver}
onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
aria-labelledby="add-instance-driver-label"
className="grid grid-cols-2 gap-2.5"
>
{DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
const isSelected = option.value === driver;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
className={cn(
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
)}
>
<IconComponent className="size-5 shrink-0" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
{option.badgeLabel ? (
<Badge variant="warning" size="sm">
{option.badgeLabel}
</Badge>
) : null}
</RadioPrimitive.Root>
);
})}
{COMING_SOON_DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
disabled
className={cn(
"relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",
)}
>
<IconComponent
className="size-5 shrink-0 text-muted-foreground"
aria-hidden
/>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
<Badge variant="warning" size="sm">
Coming Soon
</Badge>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
<span
className={cn(
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
index < wizardStep
? "border-primary bg-primary text-primary-foreground"
: index === wizardStep
? "border-primary bg-background"
: "border-muted-foreground/35 bg-background",
)}
aria-hidden
>
{index < wizardStep ? <CheckIcon className="size-3" /> : null}
</span>
<span className="text-[10px] font-medium uppercase text-muted-foreground">
Step {index + 1}
</span>
<span className="truncate text-xs font-semibold text-foreground">
{step}
{index < wizardStep && wizardStepSummaries[index]
? `: ${wizardStepSummaries[index]}`
: ""}
</span>
</button>
))}
</div>
</DialogHeader>
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Label</span>
<Input
className="bg-background"
placeholder="e.g. Work"
value={label}
onChange={(event) => setLabel(event.target.value)}
/>
<span className="text-[11px] text-muted-foreground">
Shown in the provider list. Optional.
</span>
</label>
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Instance ID</span>
<Input
className="bg-background"
placeholder={`${driver}_work`}
value={instanceId}
onChange={(event) => {
setCustomInstanceId(event.target.value);
}}
aria-invalid={showInstanceIdError}
/>
{showInstanceIdError ? (
<span className="text-[11px] text-destructive">{instanceIdError}</span>
) : (
<span className="text-[11px] text-muted-foreground">
Routing key used by threads and sessions. Letters, digits, '-', or '_'.
<div
data-slot="dialog-panel"
className="space-y-4 border-b border-border/70 bg-muted/20 px-6 py-5"
>
<AnimatedHeight>
<div className={cn("grid gap-2", wizardStep !== 0 && "hidden")}>
<span
id="add-instance-driver-label"
className="text-xs font-medium text-foreground"
>
Driver
</span>
)}
</label>
<div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Accent color</span>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<input
type="color"
value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
onChange={(event) => setAccentColor(event.target.value)}
aria-label="Provider instance accent color"
className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
/>
<div className="flex flex-wrap gap-1.5">
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
const selected = accentColor.toLowerCase() === swatch;
<RadioGroup
value={driver}
onValueChange={(value) => setDriver(ProviderDriverKind.make(value))}
aria-labelledby="add-instance-driver-label"
className="grid grid-cols-2 gap-2.5"
>
{DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
const isSelected = option.value === driver;
return (
<button
key={swatch}
type="button"
<RadioPrimitive.Root
key={option.value}
value={option.value}
className={cn(
"size-6 cursor-pointer rounded-full border transition",
selected
? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
: "border-black/10 hover:scale-105 dark:border-white/20",
"relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
isSelected
? "border-primary bg-background shadow-sm ring-2 ring-primary/35"
: "border-border bg-background hover:border-foreground/20 hover:bg-muted/50",
)}
style={{ backgroundColor: swatch }}
onClick={() => setAccentColor(swatch)}
aria-label={`Use ${swatch} accent`}
/>
>
<IconComponent className="size-5 shrink-0" aria-hidden />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
{option.badgeLabel ? (
<Badge variant="warning" size="sm">
{option.badgeLabel}
</Badge>
) : null}
</RadioPrimitive.Root>
);
})}
</div>
{accentColor ? (
<Button
type="button"
size="sm"
variant="ghost"
className="h-7 px-2 text-xs text-muted-foreground"
onClick={() => setAccentColor("")}
>
Clear
</Button>
) : null}
{COMING_SOON_DRIVER_OPTIONS.map((option) => {
const IconComponent = option.icon;
return (
<RadioPrimitive.Root
key={option.value}
value={option.value}
disabled
className={cn(
"relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-55 outline-none",
)}
>
<IconComponent
className="size-5 shrink-0 text-muted-foreground"
aria-hidden
/>
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
{option.label}
</span>
<Badge variant="warning" size="sm">
Coming Soon
</Badge>
</RadioPrimitive.Root>
);
})}
</RadioGroup>
</div>
<span className="text-[11px] text-muted-foreground">
Optional marker shown in the picker.
</span>
</div>
{driverSettingsFields.length > 0 ? (
<div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
<ProviderSettingsForm
definition={driverOption}
value={configDraft}
idPrefix={`add-provider-${driver}`}
variant="dialog"
onChange={setConfigDraft}
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Label</span>
<Input
className="bg-background"
placeholder="e.g. Work"
value={label}
onChange={(event) => setLabel(event.target.value)}
/>
</div>
) : wizardStep === 2 ? (
<div className="grid gap-2">
<p className="text-sm text-muted-foreground">
This driver has no required configuration. You can add the instance now.
</p>
</div>
) : null}
</AnimatedHeight>
</div>
<span className="text-[11px] text-muted-foreground">
Shown in the provider list. Optional.
</span>
</label>
<DialogFooter className="border-t bg-background">
<Button
variant="outline"
size="sm"
onClick={() => {
if (wizardStep === 0) {
onOpenChange(false);
return;
}
setWizardStep((step) => Math.max(0, step - 1));
}}
>
{wizardStep === 0 ? "Cancel" : "Back"}
</Button>
{wizardStep < wizardSteps.length - 1 ? (
<Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>
Next
<label className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Instance ID</span>
<Input
className="bg-background"
placeholder={`${driver}_work`}
value={instanceId}
onChange={(event) => {
setInstanceIdDirty(true);
setInstanceId(event.target.value);
}}
aria-invalid={showInstanceIdError}
/>
{showInstanceIdError ? (
<span className="text-[11px] text-destructive">{instanceIdError}</span>
) : (
<span className="text-[11px] text-muted-foreground">
Routing key used by threads and sessions. Letters, digits, '-', or '_'.
</span>
)}
</label>
<div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Accent color</span>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<input
type="color"
value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
onChange={(event) => setAccentColor(event.target.value)}
aria-label="Provider instance accent color"
className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
/>
<div className="flex flex-wrap gap-1.5">
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
const selected = accentColor.toLowerCase() === swatch;
return (
<button
key={swatch}
type="button"
className={cn(
"size-6 cursor-pointer rounded-full border transition",
selected
? "scale-110 border-foreground ring-2 ring-ring ring-offset-1 ring-offset-background"
: "border-black/10 hover:scale-105 dark:border-white/20",
)}
style={{ backgroundColor: swatch }}
onClick={() => setAccentColor(swatch)}
aria-label={`Use ${swatch} accent`}
/>
);
})}
</div>
{accentColor ? (
<Button
type="button"
size="sm"
variant="ghost"
className="h-7 px-2 text-xs text-muted-foreground"
onClick={() => setAccentColor("")}
>
Clear
</Button>
) : null}
</div>
<span className="text-[11px] text-muted-foreground">
Optional marker shown in the picker.
</span>
</div>
{driverSettingsFields.length > 0 ? (
<div className={cn("grid gap-4", wizardStep !== 2 && "hidden")}>
<ProviderSettingsForm
definition={driverOption}
value={configDraft}
idPrefix={`add-provider-${driver}`}
variant="dialog"
onChange={setConfigDraft}
/>
</div>
) : wizardStep === 2 ? (
<div className="grid gap-2">
<p className="text-sm text-muted-foreground">
This driver has no required configuration. You can add the instance now.
</p>
</div>
) : null}
</AnimatedHeight>
</div>
<DialogFooter className="border-t bg-background">
<Button
variant="outline"
size="sm"
onClick={() => {
if (wizardStep === 0) {
onOpenChange(false);
return;
}
setWizardStep((step) => Math.max(0, step - 1));
}}
>
{wizardStep === 0 ? "Cancel" : "Back"}
</Button>
) : (
<Button size="sm" onClick={handleSave}>
Add instance
</Button>
)}
</DialogFooter>
</div>
</DialogPopup>
{wizardStep < wizardSteps.length - 1 ? (
<Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>
Next
</Button>
) : (
<Button size="sm" onClick={handleSave}>
Add instance
</Button>
)}
</DialogFooter>
</div>
</DialogPopup>
</Dialog>
);
}
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.23",
"version": "0.0.24",
"private": true,
"files": [
"dist"