Merge origin/main into t3code/mobile-remote-connect
Co-authored-by: codex <[email protected]>
This commit is contained in:
commit
ef1ed88c18
114 files changed
+13683
-2340
No files matched your search
@@ -52,6 +52,7 @@ const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
|
||||
@@ -15,7 +15,7 @@ import * as CliError from "effect/unstable/cli/CliError";
|
||||
import * as TestConsole from "effect/testing/TestConsole";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./cli.ts";
|
||||
import { cli } from "./bin.ts";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
@@ -148,7 +148,7 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Ef
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
+16
-5
@@ -5,13 +5,24 @@ import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { cli } from "./cli.ts";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { authCommand } from "./cli/auth.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) => runServerCommand(flags)),
|
||||
Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,243 @@
|
||||
import { AuthSessionId } from "@t3tools/contracts";
|
||||
import { Console, Effect, Layer, Option, References } from "effect";
|
||||
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
|
||||
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
|
||||
import {
|
||||
formatIssuedPairingCredential,
|
||||
formatIssuedSession,
|
||||
formatPairingCredentialList,
|
||||
formatSessionList,
|
||||
} from "../cliAuthFormat.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import {
|
||||
authLocationFlags,
|
||||
type CliAuthLocationFlags,
|
||||
DurationFromString,
|
||||
resolveCliAuthConfig,
|
||||
} from "./config.ts";
|
||||
|
||||
const runWithAuthControlPlane = <A, E>(
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
|
||||
options?: {
|
||||
readonly quietLogs?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
|
||||
return yield* Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
return yield* run(authControlPlane);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const ttlFlag = Flag.string("ttl").pipe(
|
||||
Flag.withSchema(DurationFromString),
|
||||
Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const jsonFlag = Flag.boolean("json").pipe(
|
||||
Flag.withDescription("Emit JSON instead of human-readable output."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
|
||||
Flag.withDescription("Role for the issued bearer session."),
|
||||
Flag.withDefault("owner"),
|
||||
);
|
||||
|
||||
const labelFlag = Flag.string("label").pipe(
|
||||
Flag.withDescription("Optional human-readable label."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const subjectFlag = Flag.string("subject").pipe(
|
||||
Flag.withDescription("Optional session subject."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const baseUrlFlag = Flag.string("base-url").pipe(
|
||||
Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const tokenOnlyFlag = Flag.boolean("token-only").pipe(
|
||||
Flag.withDescription("Print only the issued bearer token."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const pairingCreateCommand = Command.make("create", {
|
||||
...authLocationFlags,
|
||||
ttl: ttlFlag,
|
||||
label: labelFlag,
|
||||
baseUrl: baseUrlFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Issue a new client pairing token."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* authControlPlane.createPairingLink({
|
||||
role: "client",
|
||||
subject: "one-time-token",
|
||||
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
|
||||
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
|
||||
});
|
||||
const output = formatIssuedPairingCredential(issued, {
|
||||
json: flags.json,
|
||||
...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingListCommand = Command.make("list", {
|
||||
...authLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List active client pairing tokens without revealing their secrets."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
|
||||
yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingRevokeCommand = Command.make("revoke", {
|
||||
...authLocationFlags,
|
||||
id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke an active client pairing token."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(flags, (authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const revoked = yield* authControlPlane.revokePairingLink(flags.id);
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked pairing credential ${flags.id}.\n`
|
||||
: `No active pairing credential found for ${flags.id}.\n`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingCommand = Command.make("pairing").pipe(
|
||||
Command.withDescription("Manage one-time client pairing tokens."),
|
||||
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
|
||||
);
|
||||
|
||||
const sessionIssueCommand = Command.make("issue", {
|
||||
...authLocationFlags,
|
||||
ttl: ttlFlag,
|
||||
role: sessionRoleFlag,
|
||||
label: labelFlag,
|
||||
subject: subjectFlag,
|
||||
tokenOnly: tokenOnlyFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Issue a bearer session token for headless or remote clients."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* authControlPlane.issueSession({
|
||||
role: flags.role,
|
||||
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
|
||||
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
|
||||
...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
|
||||
});
|
||||
yield* Console.log(
|
||||
formatIssuedSession(issued, {
|
||||
json: flags.json,
|
||||
tokenOnly: flags.tokenOnly,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json || flags.tokenOnly,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionListCommand = Command.make("list", {
|
||||
...authLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List active sessions without revealing bearer tokens."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* authControlPlane.listSessions();
|
||||
yield* Console.log(formatSessionList(sessions, { json: flags.json }));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionRevokeCommand = Command.make("revoke", {
|
||||
...authLocationFlags,
|
||||
sessionId: Argument.string("session-id").pipe(
|
||||
Argument.withDescription("Session id to revoke."),
|
||||
Argument.withSchema(AuthSessionId),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke an active session."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(flags, (authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked session ${flags.sessionId}.\n`
|
||||
: `No active session found for ${flags.sessionId}.\n`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionCommand = Command.make("session").pipe(
|
||||
Command.withDescription("Manage bearer sessions."),
|
||||
Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
|
||||
);
|
||||
|
||||
export const authCommand = Command.make("auth").pipe(
|
||||
Command.withDescription("Manage the local auth control plane for headless deployments."),
|
||||
Command.withSubcommands([pairingCommand, sessionCommand]),
|
||||
);
|
||||
@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { deriveServerPaths } from "./config.ts";
|
||||
import { resolveServerConfig } from "./cli.ts";
|
||||
import { deriveServerPaths } from "../config.ts";
|
||||
import { resolveServerConfig } from "./config.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
@@ -0,0 +1,490 @@
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import {
|
||||
Config,
|
||||
Duration,
|
||||
Effect,
|
||||
FileSystem,
|
||||
LogLevel,
|
||||
Option,
|
||||
Path,
|
||||
Schema,
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
} from "effect";
|
||||
import { Argument, Flag } from "effect/unstable/cli";
|
||||
|
||||
import { readBootstrapEnvelope } from "../bootstrap.ts";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
ensureServerDirectories,
|
||||
resolveStaticDir,
|
||||
RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
type StartupPresentation,
|
||||
} from "../config.ts";
|
||||
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
|
||||
|
||||
export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(RuntimeMode),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
desktopBootstrapToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optional(PortSchema),
|
||||
otlpTracesUrl: Schema.optional(Schema.String),
|
||||
otlpMetricsUrl: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const baseDirFlag = Flag.string("base-dir").pipe(
|
||||
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
export const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
export const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
|
||||
Flag.withDescription(
|
||||
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
export const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const EnvServerConfig = Config.all({
|
||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
||||
traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
|
||||
traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
|
||||
traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
|
||||
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
|
||||
Config.withDefault(10_000),
|
||||
),
|
||||
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
|
||||
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
export interface CliServerFlags {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly cwd: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
readonly tailscaleServeEnabled: Option.Option<boolean>;
|
||||
readonly tailscaleServePort: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface CliAuthLocationFlags {
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly devUrl?: Option.Option<URL>;
|
||||
}
|
||||
|
||||
export const sharedServerLocationFlags = {
|
||||
baseDir: baseDirFlag,
|
||||
devUrl: devUrlFlag,
|
||||
} as const;
|
||||
|
||||
export const projectLocationFlags = {
|
||||
baseDir: baseDirFlag,
|
||||
} as const;
|
||||
|
||||
export const sharedServerCommandFlags = {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
baseDir: baseDirFlag,
|
||||
cwd: Argument.string("cwd").pipe(
|
||||
Argument.withDescription(
|
||||
"Working directory for provider sessions (defaults to the current directory).",
|
||||
),
|
||||
Argument.optional,
|
||||
),
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
tailscaleServeEnabled: tailscaleServeFlag,
|
||||
tailscaleServePort: tailscaleServePortFlag,
|
||||
} as const;
|
||||
|
||||
export const authLocationFlags = sharedServerLocationFlags;
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
|
||||
}
|
||||
|
||||
const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
|
||||
return parsePersistedServerObservabilitySettings(raw);
|
||||
});
|
||||
|
||||
export const resolveServerConfig = (
|
||||
flags: CliServerFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
options?: {
|
||||
readonly startupPresentation?: StartupPresentation;
|
||||
readonly forceAutoBootstrapProjectFromCwd?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const env = yield* EnvServerConfig;
|
||||
const normalizedFlags = {
|
||||
mode: flags.mode ?? Option.none(),
|
||||
port: flags.port ?? Option.none(),
|
||||
host: flags.host ?? Option.none(),
|
||||
baseDir: flags.baseDir ?? Option.none(),
|
||||
cwd: flags.cwd ?? Option.none(),
|
||||
devUrl: flags.devUrl ?? Option.none(),
|
||||
noBrowser: flags.noBrowser ?? Option.none(),
|
||||
bootstrapFd: flags.bootstrapFd ?? Option.none(),
|
||||
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
|
||||
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
|
||||
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
|
||||
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
|
||||
} satisfies CliServerFlags;
|
||||
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.fromUndefinedOr(bootstrap?.mode),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.fromUndefinedOr(bootstrap?.port),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.fromUndefinedOr(bootstrap?.devUrl),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.fromUndefinedOr(bootstrap?.t3Home),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
|
||||
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
|
||||
yield* fs.makeDirectory(cwd, { recursive: true });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
yield* ensureServerDirectories(derivedPaths);
|
||||
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
|
||||
derivedPaths.settingsPath,
|
||||
);
|
||||
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
|
||||
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
|
||||
const startupPresentation = options?.startupPresentation ?? "browser";
|
||||
const isHeadlessStartup = startupPresentation === "headless";
|
||||
const noBrowser = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
isHeadlessStartup ? Option.some(true) : Option.none(),
|
||||
normalizedFlags.noBrowser,
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.fromUndefinedOr(bootstrap?.noBrowser),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
);
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
|
||||
isHeadlessStartup ? Option.some(false) : Option.none(),
|
||||
normalizedFlags.autoBootstrapProjectFromCwd,
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
() => mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.logWebSocketEvents,
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
);
|
||||
const tailscaleServeEnabled = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.tailscaleServeEnabled,
|
||||
Option.fromUndefinedOr(env.tailscaleServeEnabled),
|
||||
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
|
||||
),
|
||||
() => false,
|
||||
);
|
||||
const tailscaleServePort = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.tailscaleServePort,
|
||||
Option.fromUndefinedOr(env.tailscaleServePort),
|
||||
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
|
||||
),
|
||||
() => 443,
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.fromUndefinedOr(bootstrap?.host),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
logLevel,
|
||||
traceMinLevel: env.traceMinLevel,
|
||||
traceTimingEnabled: env.traceTimingEnabled,
|
||||
traceBatchWindowMs: env.traceBatchWindowMs,
|
||||
traceMaxBytes: env.traceMaxBytes,
|
||||
traceMaxFiles: env.traceMaxFiles,
|
||||
otlpTracesUrl:
|
||||
env.otlpTracesUrl ??
|
||||
bootstrap?.otlpTracesUrl ??
|
||||
persistedObservabilitySettings.otlpTracesUrl,
|
||||
otlpMetricsUrl:
|
||||
env.otlpMetricsUrl ??
|
||||
bootstrap?.otlpMetricsUrl ??
|
||||
persistedObservabilitySettings.otlpMetricsUrl,
|
||||
otlpExportIntervalMs: env.otlpExportIntervalMs,
|
||||
otlpServiceName: env.otlpServiceName,
|
||||
mode,
|
||||
port,
|
||||
cwd,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
serverTracePath,
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
tailscaleServePort,
|
||||
};
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
export const resolveCliAuthConfig = (
|
||||
flags: CliAuthLocationFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
) =>
|
||||
resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: flags.baseDir,
|
||||
cwd: Option.none(),
|
||||
devUrl: flags.devUrl ?? Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
cliLogLevel,
|
||||
);
|
||||
|
||||
const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
|
||||
|
||||
const parseDurationInput = (value: string): Duration.Duration | null => {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
const shorthand = DurationShorthandPattern.exec(trimmed);
|
||||
const normalizedInput = shorthand?.groups
|
||||
? (() => {
|
||||
const amountText = shorthand.groups.value;
|
||||
const unitText = shorthand.groups.unit;
|
||||
if (typeof amountText !== "string" || typeof unitText !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const amount = Number.parseInt(amountText, 10);
|
||||
if (!Number.isFinite(amount)) return null;
|
||||
|
||||
switch (unitText.toLowerCase()) {
|
||||
case "ms":
|
||||
return `${amount} millis`;
|
||||
case "s":
|
||||
return `${amount} seconds`;
|
||||
case "m":
|
||||
return `${amount} minutes`;
|
||||
case "h":
|
||||
return `${amount} hours`;
|
||||
case "d":
|
||||
return `${amount} days`;
|
||||
case "w":
|
||||
return `${amount} weeks`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})()
|
||||
: (trimmed as Duration.Input);
|
||||
|
||||
if (normalizedInput === null) return null;
|
||||
|
||||
const decoded = Duration.fromInput(normalizedInput as Duration.Input);
|
||||
return Option.isSome(decoded) ? decoded.value : null;
|
||||
};
|
||||
|
||||
export const DurationFromString = Schema.String.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.Duration,
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (value) => {
|
||||
const duration = parseDurationInput(value);
|
||||
if (duration !== null) {
|
||||
return Effect.succeed(duration);
|
||||
}
|
||||
return Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
|
||||
}),
|
||||
);
|
||||
},
|
||||
encode: (duration) => Effect.succeed(Duration.format(duration)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,434 @@
|
||||
import {
|
||||
CommandId,
|
||||
OrchestrationReadModel,
|
||||
ProjectId,
|
||||
type ClientOrchestrationCommand,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Console,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
References,
|
||||
Schema,
|
||||
} from "effect";
|
||||
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
HttpClientRequest,
|
||||
HttpClientResponse,
|
||||
} from "effect/unstable/http";
|
||||
|
||||
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
|
||||
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
|
||||
import { ServerConfig, type ServerConfigShape } from "../config.ts";
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { getAutoBootstrapDefaultModelSelection } from "../serverRuntimeStartup.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "../serverRuntimeState.ts";
|
||||
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
|
||||
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
type ProjectMutationTarget = {
|
||||
readonly id: ProjectId;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
};
|
||||
|
||||
type ProjectCommandExecutionMode = "live" | "offline";
|
||||
type ProjectCliDispatchCommand = Extract<
|
||||
ClientOrchestrationCommand,
|
||||
{ type: "project.create" | "project.meta.update" | "project.delete" }
|
||||
>;
|
||||
|
||||
const ProjectCliRuntimeLive = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
OrchestrationLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
),
|
||||
);
|
||||
|
||||
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
|
||||
const OrchestrationHttpErrorResponse = Schema.Struct({
|
||||
error: Schema.String,
|
||||
});
|
||||
|
||||
const withProjectCliSessionToken = <A, E, R>(
|
||||
authControlPlane: AuthControlPlaneShape,
|
||||
run: (token: string) => Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.acquireUseRelease(
|
||||
authControlPlane.issueSession({
|
||||
role: "owner",
|
||||
label: "t3 project cli",
|
||||
}),
|
||||
(issued) => run(issued.token),
|
||||
(issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
|
||||
);
|
||||
|
||||
const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
|
||||
|
||||
const runLiveServerRequest = <A, E extends Error, R>(
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const response = yield* httpClient.execute(request);
|
||||
return yield* handle(response);
|
||||
}).pipe(withProjectCliLiveServerTimeout);
|
||||
|
||||
const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
|
||||
HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
|
||||
|
||||
const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
|
||||
HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
|
||||
Effect.map((body) => body.error),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.map((body) => {
|
||||
if (typeof body === "string" && body.trim().length > 0) {
|
||||
return body;
|
||||
}
|
||||
return `Server request failed with status ${response.status}.`;
|
||||
}),
|
||||
);
|
||||
|
||||
const normalizeWorkspaceRootForProjectCommand = Effect.fn(
|
||||
"normalizeWorkspaceRootForProjectCommand",
|
||||
)(function* (workspaceRoot: string) {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
|
||||
});
|
||||
|
||||
const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
workspaceRoot: string,
|
||||
explicitTitle?: string,
|
||||
) {
|
||||
if (explicitTitle !== undefined) {
|
||||
const trimmed = explicitTitle.trim();
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* Effect.fail(new Error("Project title cannot be empty."));
|
||||
}
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const basename = path.basename(workspaceRoot).trim();
|
||||
return basename.length > 0 ? basename : "project";
|
||||
});
|
||||
|
||||
const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly identifier: string;
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* Effect.fail(new Error("Project identifier cannot be empty."));
|
||||
}
|
||||
|
||||
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
|
||||
const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
|
||||
if (exactIdMatch) {
|
||||
return {
|
||||
id: exactIdMatch.id,
|
||||
title: exactIdMatch.title,
|
||||
workspaceRoot: exactIdMatch.workspaceRoot,
|
||||
} satisfies ProjectMutationTarget;
|
||||
}
|
||||
|
||||
const normalizedWorkspaceRootResult = yield* Effect.exit(
|
||||
normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
|
||||
);
|
||||
const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
|
||||
? normalizedWorkspaceRootResult.value
|
||||
: null;
|
||||
|
||||
const exactWorkspaceMatch =
|
||||
normalizedWorkspaceRoot === null
|
||||
? undefined
|
||||
: activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
|
||||
}
|
||||
|
||||
return {
|
||||
id: resolved.id,
|
||||
title: resolved.title,
|
||||
workspaceRoot: resolved.workspaceRoot,
|
||||
} satisfies ProjectMutationTarget;
|
||||
});
|
||||
|
||||
const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
runLiveServerRequest(
|
||||
HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(bearerToken),
|
||||
),
|
||||
HttpClientResponse.matchStatus({
|
||||
"2xx": decodeOrchestrationReadModelResponse,
|
||||
orElse: (response) =>
|
||||
readErrorMessageFromResponse(response).pipe(
|
||||
Effect.flatMap((message) => Effect.fail(new Error(message))),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
origin: string,
|
||||
bearerToken: string,
|
||||
command: ProjectCliDispatchCommand,
|
||||
) =>
|
||||
HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(bearerToken),
|
||||
HttpClientRequest.bodyJson(command),
|
||||
Effect.flatMap((request) =>
|
||||
runLiveServerRequest(
|
||||
request,
|
||||
HttpClientResponse.matchStatus({
|
||||
"2xx": () => Effect.void,
|
||||
orElse: (response) =>
|
||||
readErrorMessageFromResponse(response).pipe(
|
||||
Effect.flatMap((message) => Effect.fail(new Error(message))),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
});
|
||||
|
||||
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
|
||||
function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
|
||||
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
|
||||
if (Option.isNone(runtimeState)) {
|
||||
return Option.none<{ readonly origin: string }>();
|
||||
}
|
||||
|
||||
const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
|
||||
fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
|
||||
Effect.as({
|
||||
origin: runtimeState.value.origin,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const attempted = yield* Effect.exit(attempt);
|
||||
if (Exit.isSuccess(attempted)) {
|
||||
return Option.some(attempted.value);
|
||||
}
|
||||
|
||||
yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
|
||||
return Option.none<{ readonly origin: string }>();
|
||||
},
|
||||
);
|
||||
|
||||
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
readonly mode: ProjectCommandExecutionMode;
|
||||
}) => Effect.Effect<
|
||||
string,
|
||||
Error,
|
||||
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
|
||||
>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = config.logLevel;
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
|
||||
|
||||
if (Option.isSome(liveMode)) {
|
||||
return yield* withProjectCliSessionToken(authControlPlane, (token) =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
|
||||
const output = yield* run({
|
||||
snapshot,
|
||||
dispatch: (command) =>
|
||||
dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
|
||||
mode: "live",
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const snapshot = yield* getOfflineSnapshot();
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const output = yield* run({
|
||||
snapshot,
|
||||
dispatch: (command) => orchestrationEngine.dispatch(command),
|
||||
mode: "offline",
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}).pipe(Effect.provide(offlineRuntimeLayer));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const projectAddCommand = Command.make("add", {
|
||||
...projectLocationFlags,
|
||||
workspaceRoot: Argument.string("path").pipe(
|
||||
Argument.withDescription("Workspace root to add as a project."),
|
||||
),
|
||||
title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
|
||||
}).pipe(
|
||||
Command.withDescription("Add a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectAddMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
|
||||
const existingProject = snapshot.projects.find(
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* Effect.fail(
|
||||
new Error(`An active project already exists for '${workspaceRoot}'.`),
|
||||
);
|
||||
}
|
||||
|
||||
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
|
||||
const projectId = ProjectId.make(crypto.randomUUID());
|
||||
yield* dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const projectRemoveCommand = Command.make("remove", {
|
||||
...projectLocationFlags,
|
||||
project: Argument.string("project").pipe(
|
||||
Argument.withDescription("Project id or workspace root to remove."),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Remove a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectRemoveMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const project = yield* findActiveProjectTarget({
|
||||
snapshot,
|
||||
identifier: flags.project,
|
||||
});
|
||||
yield* dispatch({
|
||||
type: "project.delete",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const projectRenameCommand = Command.make("rename", {
|
||||
...projectLocationFlags,
|
||||
project: Argument.string("project").pipe(
|
||||
Argument.withDescription("Project id or workspace root to rename."),
|
||||
),
|
||||
title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
|
||||
}).pipe(
|
||||
Command.withDescription("Rename a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectRenameMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const project = yield* findActiveProjectTarget({
|
||||
snapshot,
|
||||
identifier: flags.project,
|
||||
});
|
||||
const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
|
||||
if (nextTitle === project.title) {
|
||||
return `Project ${project.id} is already named ${nextTitle}.`;
|
||||
}
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
title: nextTitle,
|
||||
});
|
||||
return `Renamed project ${project.id} to ${nextTitle}.`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const projectCommand = Command.make("project").pipe(
|
||||
Command.withDescription("Manage projects."),
|
||||
Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
|
||||
);
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Effect } from "effect";
|
||||
import { Command, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import { ServerConfig, type StartupPresentation } from "../config.ts";
|
||||
import { runServer } from "../server.ts";
|
||||
import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
|
||||
|
||||
export const runServerCommand = (
|
||||
flags: CliServerFlags,
|
||||
options?: {
|
||||
readonly startupPresentation?: StartupPresentation;
|
||||
readonly forceAutoBootstrapProjectFromCwd?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveServerConfig(flags, logLevel, options);
|
||||
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
|
||||
});
|
||||
|
||||
export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) => runServerCommand(flags)),
|
||||
);
|
||||
|
||||
export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription(
|
||||
"Run the T3 Code server without opening a browser and print headless pairing details.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runServerCommand(flags, {
|
||||
startupPresentation: "headless",
|
||||
forceAutoBootstrapProjectFromCwd: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,252 @@
|
||||
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 Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
describe("ProcessDiagnostics", () => {
|
||||
it.effect("parses POSIX ps rows with full commands", () =>
|
||||
Effect.sync(() => {
|
||||
const rows = ProcessDiagnostics.parsePosixProcessRows(
|
||||
[
|
||||
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
|
||||
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
pid: 10,
|
||||
ppid: 1,
|
||||
pgid: 10,
|
||||
status: "Ss",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1024 * 1024,
|
||||
elapsed: "01:02.03",
|
||||
command: "/usr/bin/node server.js",
|
||||
},
|
||||
{
|
||||
pid: 11,
|
||||
ppid: 10,
|
||||
pgid: 10,
|
||||
status: "S+",
|
||||
cpuPercent: 12.5,
|
||||
rssBytes: 20480 * 1024,
|
||||
elapsed: "00:04",
|
||||
command: "codex app-server --config /tmp/one two",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("aggregates only descendants of the server process", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1.5,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 3.25,
|
||||
rssBytes: 4_000,
|
||||
elapsed: "00:05",
|
||||
command: "git status",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "S",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 8_000,
|
||||
elapsed: "00:01",
|
||||
command: "unrelated",
|
||||
},
|
||||
{
|
||||
pid: 201,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 9,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:00",
|
||||
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
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]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves ascending sibling order for nested descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "agent",
|
||||
},
|
||||
{
|
||||
pid: 103,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-b",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-a",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queries processes through the ChildProcessSpawner service", () =>
|
||||
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: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.read),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
command: "ps",
|
||||
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
pid: 4242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,461 @@
|
||||
import type {
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessSignal,
|
||||
ServerSignalProcessResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly pgid: number | null;
|
||||
readonly status: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly elapsed: string;
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
export interface ProcessDiagnosticsShape {
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
|
||||
"ProcessDiagnosticsError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
|
||||
return new ProcessDiagnosticsError({
|
||||
message,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
}
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNonNegativeInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNumber(value: string): number | null {
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
const rowPattern =
|
||||
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
|
||||
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
const match = rowPattern.exec(line);
|
||||
if (!match) continue;
|
||||
|
||||
const pidText = match[1];
|
||||
const ppidText = match[2];
|
||||
const pgidText = match[3];
|
||||
const status = match[4];
|
||||
const cpuText = match[5];
|
||||
const rssText = match[6];
|
||||
const elapsed = match[7];
|
||||
const command = match[8];
|
||||
if (
|
||||
pidText === undefined ||
|
||||
ppidText === undefined ||
|
||||
pgidText === undefined ||
|
||||
status === undefined ||
|
||||
cpuText === undefined ||
|
||||
rssText === undefined ||
|
||||
elapsed === undefined ||
|
||||
command === undefined
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
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,
|
||||
ppid,
|
||||
pgid,
|
||||
status,
|
||||
cpuPercent,
|
||||
rssBytes: rssKiB * 1024,
|
||||
elapsed,
|
||||
command,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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> {
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
|
||||
function buildDescendantEntries(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const children = childrenByParent.get(row.ppid) ?? [];
|
||||
children.push(row);
|
||||
childrenByParent.set(row.ppid, children);
|
||||
}
|
||||
|
||||
const entries: ServerProcessDiagnosticsEntry[] = [];
|
||||
const visited = new Set<number>();
|
||||
const stack = [...(childrenByParent.get(serverPid) ?? [])]
|
||||
.toSorted((left, right) => left.pid - right.pid)
|
||||
.map((row) => ({ row, depth: 0 }));
|
||||
|
||||
while (stack.length > 0) {
|
||||
const item = stack.shift();
|
||||
if (!item || visited.has(item.row.pid)) continue;
|
||||
visited.add(item.row.pid);
|
||||
|
||||
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
|
||||
(left, right) => left.pid - right.pid,
|
||||
);
|
||||
entries.push({
|
||||
pid: item.row.pid,
|
||||
ppid: item.row.ppid,
|
||||
pgid: Option.fromNullishOr(item.row.pgid),
|
||||
status: item.row.status,
|
||||
cpuPercent: item.row.cpuPercent,
|
||||
rssBytes: item.row.rssBytes,
|
||||
elapsed: item.row.elapsed || "n/a",
|
||||
command: item.row.command,
|
||||
depth: item.depth,
|
||||
childPids: children.map((child) => child.pid),
|
||||
});
|
||||
|
||||
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
if (row.ppid !== serverPid) return false;
|
||||
|
||||
const command = row.command.trim();
|
||||
return (
|
||||
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
|
||||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
|
||||
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
|
||||
);
|
||||
}
|
||||
|
||||
function makeResult(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: string;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const processes = buildDescendantEntries(rows, input.serverPid);
|
||||
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
|
||||
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
|
||||
|
||||
return {
|
||||
serverPid: input.serverPid,
|
||||
readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes,
|
||||
totalCpuPercent,
|
||||
processes,
|
||||
error: input.error ? Option.some({ message: input.error }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
interface ProcessOutput {
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(
|
||||
function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly errorMessage: string;
|
||||
}) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd: process.cwd(),
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
} satisfies ProcessOutput;
|
||||
},
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(ProcessDiagnosticsError)(cause)
|
||||
? cause
|
||||
: toProcessDiagnosticsError(input.errorMessage, cause),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function readPosixProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return runProcess({
|
||||
command: "ps",
|
||||
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function readWindowsProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const command = [
|
||||
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
|
||||
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
|
||||
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
|
||||
"};",
|
||||
"$processes | ConvertTo-Json -Compress -Depth 3",
|
||||
].join(" ");
|
||||
|
||||
return runProcess({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const readProcessRows = (platform = process.platform) =>
|
||||
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
return makeResult(input);
|
||||
}
|
||||
|
||||
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 readProcessRows().pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
|
||||
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
|
||||
(entry) => entry.pid === pid,
|
||||
);
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
return makeResult({ serverPid: process.pid, rows, readAt });
|
||||
}).pipe(
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.map((readAt) =>
|
||||
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
function* (input) {
|
||||
return yield* assertDescendantPid(input.pid).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
toProcessDiagnosticsError(
|
||||
`Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(error.message),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
@@ -0,0 +1,258 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
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 TraceDiagnostics from "./TraceDiagnostics.ts";
|
||||
|
||||
function ns(ms: number): string {
|
||||
return String(BigInt(ms) * 1_000_000n);
|
||||
}
|
||||
|
||||
function record(input: {
|
||||
readonly name: string;
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly startMs: number;
|
||||
readonly durationMs: number;
|
||||
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
|
||||
readonly events?: ReadonlyArray<unknown>;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
type: "effect-span",
|
||||
name: input.name,
|
||||
traceId: input.traceId,
|
||||
spanId: input.spanId,
|
||||
sampled: true,
|
||||
kind: "internal",
|
||||
startTimeUnixNano: ns(input.startMs),
|
||||
endTimeUnixNano: ns(input.startMs + input.durationMs),
|
||||
durationMs: input.durationMs,
|
||||
attributes: {},
|
||||
events: input.events ?? [],
|
||||
links: [],
|
||||
exit: input.exit ?? { _tag: "Success" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("TraceDiagnostics", () => {
|
||||
it.effect("aggregates failures, slow spans, log levels, and parse errors", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
slowSpanThresholdMs: 1_000,
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson.1",
|
||||
text: [
|
||||
record({
|
||||
name: "server.getConfig",
|
||||
traceId: "trace-a",
|
||||
spanId: "span-a",
|
||||
startMs: 1_000,
|
||||
durationMs: 50,
|
||||
}),
|
||||
"not-json",
|
||||
].join("\n"),
|
||||
},
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: [
|
||||
record({
|
||||
name: "orchestration.dispatch",
|
||||
traceId: "trace-b",
|
||||
spanId: "span-b",
|
||||
startMs: 2_000,
|
||||
durationMs: 1_500,
|
||||
exit: { _tag: "Failure", cause: "Provider crashed" },
|
||||
events: [
|
||||
{
|
||||
name: "provider failed",
|
||||
timeUnixNano: ns(3_400),
|
||||
attributes: { "effect.logLevel": "Error" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
record({
|
||||
name: "orchestration.dispatch",
|
||||
traceId: "trace-c",
|
||||
spanId: "span-c",
|
||||
startMs: 4_000,
|
||||
durationMs: 250,
|
||||
exit: { _tag: "Failure", cause: "Provider crashed" },
|
||||
}),
|
||||
record({
|
||||
name: "git.status",
|
||||
traceId: "trace-d",
|
||||
spanId: "span-d",
|
||||
startMs: 5_000,
|
||||
durationMs: 25,
|
||||
exit: { _tag: "Interrupted", cause: "Interrupted" },
|
||||
events: [
|
||||
{
|
||||
name: "status delayed",
|
||||
timeUnixNano: ns(5_010),
|
||||
attributes: { "effect.logLevel": "Warning" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
].join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 4);
|
||||
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
|
||||
assert.equal(
|
||||
Option.match(diagnostics.firstSpanAt, {
|
||||
onNone: () => null,
|
||||
onSome: DateTime.formatIso,
|
||||
}),
|
||||
"1970-01-01T00:00:01.000Z",
|
||||
);
|
||||
assert.equal(
|
||||
Option.match(diagnostics.lastSpanAt, {
|
||||
onNone: () => null,
|
||||
onSome: DateTime.formatIso,
|
||||
}),
|
||||
"1970-01-01T00:00:05.025Z",
|
||||
);
|
||||
assert.equal(diagnostics.parseErrorCount, 1);
|
||||
assert.equal(diagnostics.failureCount, 2);
|
||||
assert.equal(diagnostics.interruptionCount, 1);
|
||||
assert.equal(diagnostics.slowSpanCount, 1);
|
||||
assert.equal(diagnostics.logLevelCounts.Error, 1);
|
||||
assert.equal(diagnostics.logLevelCounts.Warning, 1);
|
||||
assert.equal(diagnostics.commonFailures[0]?.name, "orchestration.dispatch");
|
||||
assert.equal(diagnostics.commonFailures[0]?.count, 2);
|
||||
assert.equal(diagnostics.latestFailures[0]?.traceId, "trace-c");
|
||||
assert.equal(diagnostics.slowestSpans[0]?.traceId, "trace-b");
|
||||
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, "status delayed");
|
||||
assert.equal(diagnostics.topSpansByCount[0]?.name, "orchestration.dispatch");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a not-found diagnostic when no files are available", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/missing.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 0);
|
||||
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-not-found");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves full failure causes and log messages", () =>
|
||||
Effect.sync(() => {
|
||||
const longCause = `VcsProcessSpawnError: ${"missing executable ".repeat(80)}`.trim();
|
||||
const longMessage = `provider warning: ${"retrying command ".repeat(80)}`.trim();
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: record({
|
||||
name: "VcsProcess.run",
|
||||
traceId: "trace-long",
|
||||
spanId: "span-long",
|
||||
startMs: 1_000,
|
||||
durationMs: 25,
|
||||
exit: { _tag: "Failure", cause: longCause },
|
||||
events: [
|
||||
{
|
||||
name: longMessage,
|
||||
timeUnixNano: ns(1_010),
|
||||
attributes: { "effect.logLevel": "Warning" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.latestFailures[0]?.cause, longCause);
|
||||
assert.equal(diagnostics.commonFailures[0]?.cause, longCause);
|
||||
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, longMessage);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
|
||||
Effect.gen(function* () {
|
||||
const traceFilePath = "/tmp/server.trace.ndjson";
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
readFileString: (path) =>
|
||||
path === `${traceFilePath}.1`
|
||||
? Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(
|
||||
record({
|
||||
name: "server.getConfig",
|
||||
traceId: "trace-a",
|
||||
spanId: "span-a",
|
||||
startMs: 1_000,
|
||||
durationMs: 50,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
|
||||
traceFilePath,
|
||||
maxFiles: 1,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
|
||||
|
||||
assert.equal(diagnostics.recordCount, 1);
|
||||
assert.equal(
|
||||
Option.getOrElse(diagnostics.partialFailure, () => false),
|
||||
true,
|
||||
);
|
||||
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-read-failed");
|
||||
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps only the slowest span occurrences while aggregating large inputs", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: Array.from({ length: 25 }, (_, index) =>
|
||||
record({
|
||||
name: `span-${index}`,
|
||||
traceId: `trace-${index}`,
|
||||
spanId: `span-${index}`,
|
||||
startMs: index * 1_000,
|
||||
durationMs: index,
|
||||
}),
|
||||
).join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 25);
|
||||
assert.equal(diagnostics.slowestSpans.length, 10);
|
||||
assert.deepStrictEqual(
|
||||
diagnostics.slowestSpans.map((span) => span.durationMs),
|
||||
[24, 23, 22, 21, 20, 19, 18, 17, 16, 15],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,470 @@
|
||||
import type {
|
||||
ServerTraceDiagnosticsErrorKind,
|
||||
ServerTraceDiagnosticsFailureSummary,
|
||||
ServerTraceDiagnosticsLogEvent,
|
||||
ServerTraceDiagnosticsRecentFailure,
|
||||
ServerTraceDiagnosticsResult,
|
||||
ServerTraceDiagnosticsSpanOccurrence,
|
||||
ServerTraceDiagnosticsSpanSummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
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;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsOptions {
|
||||
readonly traceFilePath: string;
|
||||
readonly maxFiles: number;
|
||||
readonly slowSpanThresholdMs?: number;
|
||||
readonly readAt?: DateTime.Utc;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsShape {
|
||||
readonly read: (options: TraceDiagnosticsOptions) => Effect.Effect<ServerTraceDiagnosticsResult>;
|
||||
}
|
||||
|
||||
export class TraceDiagnostics extends Context.Service<TraceDiagnostics, TraceDiagnosticsShape>()(
|
||||
"t3/diagnostics/TraceDiagnostics",
|
||||
) {}
|
||||
|
||||
interface TraceDiagnosticsInput {
|
||||
readonly traceFilePath: string;
|
||||
readonly files: ReadonlyArray<{ readonly path: string; readonly text: string }>;
|
||||
readonly scannedFilePaths?: ReadonlyArray<string>;
|
||||
readonly slowSpanThresholdMs?: number;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: TraceDiagnosticsErrorSummary;
|
||||
readonly partialFailure?: boolean;
|
||||
}
|
||||
|
||||
interface TraceDiagnosticsErrorSummary {
|
||||
readonly kind: ServerTraceDiagnosticsErrorKind;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
|
||||
const TOP_LIMIT = 10;
|
||||
const RECENT_LIMIT = 20;
|
||||
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
|
||||
const backupCount = Math.max(0, Math.floor(maxFiles));
|
||||
const backups = Array.from(
|
||||
{ length: backupCount },
|
||||
(_, index) => `${traceFilePath}.${backupCount - index}`,
|
||||
);
|
||||
return [...backups, traceFilePath];
|
||||
}
|
||||
|
||||
function isRecordObject(value: unknown): value is TraceRecordLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function toStringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
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) / 1_000_000n);
|
||||
if (!Number.isFinite(millis)) return null;
|
||||
return DateTime.makeUnsafe(millis);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isAfter(left: DateTime.Utc, right: DateTime.Utc): boolean {
|
||||
return DateTime.toEpochMillis(left) > DateTime.toEpochMillis(right);
|
||||
}
|
||||
|
||||
function isBefore(left: DateTime.Utc, right: DateTime.Utc): boolean {
|
||||
return DateTime.toEpochMillis(left) < DateTime.toEpochMillis(right);
|
||||
}
|
||||
|
||||
function readExitTag(exit: unknown): string | null {
|
||||
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
|
||||
return toStringValue(exit._tag);
|
||||
}
|
||||
|
||||
function readExitCause(exit: unknown): string {
|
||||
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
|
||||
return toStringValue(exit.cause)?.trim() ?? "Failure";
|
||||
}
|
||||
|
||||
function isTraceEvent(value: unknown): value is TraceEventLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
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: {
|
||||
readonly traceFilePath: string;
|
||||
readonly scannedFilePaths: ReadonlyArray<string>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly slowSpanThresholdMs: number;
|
||||
readonly error?: TraceDiagnosticsErrorSummary;
|
||||
readonly partialFailure?: boolean;
|
||||
}): ServerTraceDiagnosticsResult {
|
||||
return {
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths: [...input.scannedFilePaths],
|
||||
readAt: input.readAt,
|
||||
recordCount: 0,
|
||||
parseErrorCount: 0,
|
||||
firstSpanAt: Option.none(),
|
||||
lastSpanAt: Option.none(),
|
||||
failureCount: 0,
|
||||
interruptionCount: 0,
|
||||
slowSpanThresholdMs: input.slowSpanThresholdMs,
|
||||
slowSpanCount: 0,
|
||||
logLevelCounts: {},
|
||||
topSpansByCount: [],
|
||||
slowestSpans: [],
|
||||
commonFailures: [],
|
||||
latestFailures: [],
|
||||
latestWarningAndErrorLogs: [],
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
}
|
||||
|
||||
function isNotFoundError(error: PlatformError.PlatformError): boolean {
|
||||
return error.reason._tag === "NotFound";
|
||||
}
|
||||
|
||||
function platformErrorMessage(error: PlatformError.PlatformError): string {
|
||||
return error.message || String(error);
|
||||
}
|
||||
|
||||
function insertBoundedSlowestSpan(
|
||||
slowestSpans: ServerTraceDiagnosticsSpanOccurrence[],
|
||||
span: ServerTraceDiagnosticsSpanOccurrence,
|
||||
): void {
|
||||
if (
|
||||
slowestSpans.length >= TOP_LIMIT &&
|
||||
span.durationMs <= slowestSpans[slowestSpans.length - 1]!.durationMs
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
slowestSpans.push(span);
|
||||
slowestSpans.sort((left, right) => right.durationMs - left.durationMs);
|
||||
if (slowestSpans.length > TOP_LIMIT) {
|
||||
slowestSpans.length = TOP_LIMIT;
|
||||
}
|
||||
}
|
||||
|
||||
export function aggregateTraceDiagnostics(
|
||||
input: TraceDiagnosticsInput,
|
||||
): ServerTraceDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
|
||||
if (input.files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error: input.error ?? {
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
},
|
||||
...(input.partialFailure ? { partialFailure: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
let parseErrorCount = 0;
|
||||
let recordCount = 0;
|
||||
let failureCount = 0;
|
||||
let interruptionCount = 0;
|
||||
let slowSpanCount = 0;
|
||||
let firstSpanAt: DateTime.Utc | null = null;
|
||||
let lastSpanAt: DateTime.Utc | null = null;
|
||||
|
||||
const spansByName = new Map<
|
||||
string,
|
||||
{ count: number; failureCount: number; totalDurationMs: number; maxDurationMs: number }
|
||||
>();
|
||||
const failuresByKey = new Map<string, ServerTraceDiagnosticsFailureSummary>();
|
||||
const latestFailures: ServerTraceDiagnosticsRecentFailure[] = [];
|
||||
const slowestSpans: ServerTraceDiagnosticsSpanOccurrence[] = [];
|
||||
const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];
|
||||
const logLevelCounts: Record<string, number> = {};
|
||||
|
||||
for (const file of input.files) {
|
||||
const lines = file.text.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
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 (!name || !traceId || !spanId || durationMs === null || !endedAt) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
recordCount += 1;
|
||||
firstSpanAt =
|
||||
startedAt && (firstSpanAt === null || isBefore(startedAt, firstSpanAt))
|
||||
? startedAt
|
||||
: firstSpanAt;
|
||||
lastSpanAt = lastSpanAt === null || isAfter(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
|
||||
|
||||
const exitTag = readExitTag(parsed.exit);
|
||||
const isFailure = exitTag === "Failure";
|
||||
const isInterrupted = exitTag === "Interrupted";
|
||||
if (isFailure) failureCount += 1;
|
||||
if (isInterrupted) interruptionCount += 1;
|
||||
|
||||
const spanSummary = spansByName.get(name) ?? {
|
||||
count: 0,
|
||||
failureCount: 0,
|
||||
totalDurationMs: 0,
|
||||
maxDurationMs: 0,
|
||||
};
|
||||
spanSummary.count += 1;
|
||||
spanSummary.totalDurationMs += durationMs;
|
||||
spanSummary.maxDurationMs = Math.max(spanSummary.maxDurationMs, durationMs);
|
||||
if (isFailure) spanSummary.failureCount += 1;
|
||||
spansByName.set(name, spanSummary);
|
||||
|
||||
const spanItem = { name, durationMs, endedAt, traceId, spanId };
|
||||
if (durationMs >= slowSpanThresholdMs) {
|
||||
slowSpanCount += 1;
|
||||
}
|
||||
insertBoundedSlowestSpan(slowestSpans, spanItem);
|
||||
|
||||
if (isFailure) {
|
||||
const cause = readExitCause(parsed.exit);
|
||||
latestFailures.push({ ...spanItem, cause });
|
||||
|
||||
const failureKey = `${name}\0${cause}`;
|
||||
const existing = failuresByKey.get(failureKey);
|
||||
const isLatestFailure = !existing || isAfter(endedAt, existing.lastSeenAt);
|
||||
failuresByKey.set(failureKey, {
|
||||
name,
|
||||
cause,
|
||||
count: (existing?.count ?? 0) + 1,
|
||||
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
|
||||
traceId: isLatestFailure ? traceId : existing!.traceId,
|
||||
spanId: isLatestFailure ? spanId : existing!.spanId,
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
|
||||
const normalizedLevel = level.toLowerCase();
|
||||
if (
|
||||
normalizedLevel !== "warning" &&
|
||||
normalizedLevel !== "warn" &&
|
||||
normalizedLevel !== "error" &&
|
||||
normalizedLevel !== "fatal"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
|
||||
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
|
||||
latestWarningAndErrorLogs.push({
|
||||
spanName: name,
|
||||
level,
|
||||
message,
|
||||
seenAt,
|
||||
traceId,
|
||||
spanId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
|
||||
.map(([name, span]) => ({
|
||||
name,
|
||||
count: span.count,
|
||||
failureCount: span.failureCount,
|
||||
totalDurationMs: span.totalDurationMs,
|
||||
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
|
||||
maxDurationMs: span.maxDurationMs,
|
||||
}))
|
||||
.toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs)
|
||||
.slice(0, TOP_LIMIT);
|
||||
|
||||
return {
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
recordCount,
|
||||
parseErrorCount,
|
||||
firstSpanAt: Option.fromNullishOr(firstSpanAt),
|
||||
lastSpanAt: Option.fromNullishOr(lastSpanAt),
|
||||
failureCount,
|
||||
interruptionCount,
|
||||
slowSpanThresholdMs,
|
||||
slowSpanCount,
|
||||
logLevelCounts,
|
||||
topSpansByCount,
|
||||
slowestSpans,
|
||||
commonFailures: [...failuresByKey.values()]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
right.count - left.count ||
|
||||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
|
||||
)
|
||||
.slice(0, TOP_LIMIT),
|
||||
latestFailures: latestFailures
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
latestWarningAndErrorLogs: latestWarningAndErrorLogs
|
||||
.toSorted(
|
||||
(left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
}
|
||||
|
||||
type TraceFileReadResult =
|
||||
| { readonly _tag: "Loaded"; readonly path: string; readonly text: string }
|
||||
| { readonly _tag: "Missing"; readonly path: string }
|
||||
| { readonly _tag: "Failed"; readonly path: string; readonly message: string };
|
||||
|
||||
function readTraceFile(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
path: string,
|
||||
): Effect.Effect<TraceFileReadResult> {
|
||||
return fileSystem.readFileString(path).pipe(
|
||||
Effect.map((text) => ({ _tag: "Loaded" as const, path, text })),
|
||||
Effect.catch((error: PlatformError.PlatformError) =>
|
||||
Effect.succeed(
|
||||
isNotFoundError(error)
|
||||
? { _tag: "Missing" as const, path }
|
||||
: { _tag: "Failed" as const, path, message: platformErrorMessage(error) },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeTraceDiagnostics")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const read: TraceDiagnosticsShape["read"] = Effect.fn("TraceDiagnostics.read")(
|
||||
function* (options) {
|
||||
const readAt = options.readAt ?? (yield* DateTime.now);
|
||||
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
|
||||
const results = yield* Effect.all(
|
||||
paths.map((path) => readTraceFile(fileSystem, path)),
|
||||
{
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
const files = results.flatMap((result) =>
|
||||
result._tag === "Loaded" ? [{ path: result.path, text: result.text }] : [],
|
||||
);
|
||||
const readFailure = results.find((result) => result._tag === "Failed");
|
||||
const readFailureError = readFailure
|
||||
? ({
|
||||
kind: "trace-file-read-failed",
|
||||
message: readFailure.message.trim() || `Failed to read ${readFailure.path}.`,
|
||||
} satisfies TraceDiagnosticsErrorSummary)
|
||||
: undefined;
|
||||
|
||||
if (files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: options.traceFilePath,
|
||||
scannedFilePaths: paths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error:
|
||||
readFailureError ??
|
||||
({
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
} satisfies TraceDiagnosticsErrorSummary),
|
||||
});
|
||||
}
|
||||
|
||||
return aggregateTraceDiagnostics({
|
||||
traceFilePath: options.traceFilePath,
|
||||
files,
|
||||
scannedFilePaths: paths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return TraceDiagnostics.of({ read });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(TraceDiagnostics, make());
|
||||
|
||||
export function readTraceDiagnostics(
|
||||
options: TraceDiagnosticsOptions,
|
||||
): Effect.Effect<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {
|
||||
return Effect.gen(function* () {
|
||||
const diagnostics = yield* TraceDiagnostics;
|
||||
return yield* diagnostics.read(options);
|
||||
});
|
||||
}
|
||||
@@ -294,6 +294,18 @@ function configureRemote(
|
||||
});
|
||||
}
|
||||
|
||||
function configureVisibleRemoteUrlWithLocalRewrite(
|
||||
cwd: string,
|
||||
remoteName: string,
|
||||
visibleUrl: string,
|
||||
localRemotePath: string,
|
||||
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
|
||||
return Effect.gen(function* () {
|
||||
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, visibleUrl]);
|
||||
yield* runGit(cwd, ["config", `url.${localRemotePath}.insteadOf`, visibleUrl]);
|
||||
});
|
||||
}
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: (input) =>
|
||||
@@ -1012,11 +1024,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-488/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
"[email protected]:jasonLaster/codething-mvp.git",
|
||||
]);
|
||||
forkDir,
|
||||
);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -1076,17 +1089,19 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.origin.url",
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"origin",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
]);
|
||||
originDir,
|
||||
);
|
||||
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.my-org/upstream.url",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"my-org/upstream",
|
||||
"ssh://[email protected]/pingdotgg/codething-mvp.git",
|
||||
upstreamDir,
|
||||
);
|
||||
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
|
||||
@@ -1861,11 +1876,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const forkDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
]);
|
||||
forkDir,
|
||||
);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -1923,17 +1939,19 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.origin.url",
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"origin",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
]);
|
||||
originDir,
|
||||
);
|
||||
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.my-org/upstream.url",
|
||||
"[email protected]:pingdotgg/codething-mvp.git",
|
||||
]);
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"my-org/upstream",
|
||||
"ssh://[email protected]/pingdotgg/codething-mvp.git",
|
||||
upstreamDir,
|
||||
);
|
||||
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
|
||||
yield* runGit(repoDir, ["checkout", "main"]);
|
||||
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
|
||||
@@ -2013,11 +2031,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
]);
|
||||
forkDir,
|
||||
);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -2083,11 +2102,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-142/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
]);
|
||||
forkDir,
|
||||
);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -2263,11 +2283,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "t3code/pr-91/statemachine"]);
|
||||
yield* runGit(repoDir, ["branch", "--set-upstream-to", "fork-seed/statemachine"]);
|
||||
yield* runGit(repoDir, [
|
||||
"config",
|
||||
"remote.fork-seed.url",
|
||||
yield* configureVisibleRemoteUrlWithLocalRewrite(
|
||||
repoDir,
|
||||
"fork-seed",
|
||||
"[email protected]:octocat/codething-mvp.git",
|
||||
]);
|
||||
forkDir,
|
||||
);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
@@ -3147,7 +3168,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
|
||||
fs.writeFileSync(
|
||||
path.join(repoDir, ".git", "hooks", "pre-commit"),
|
||||
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
|
||||
'#!/bin/sh\necho "hook: start" >&2\nsleep 0.05\necho "hook: end" >&2\n',
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
|
||||
@@ -354,7 +354,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("replaces existing custom keybinding for the same command", () =>
|
||||
it.effect("appends additional custom keybindings for the same command", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
@@ -368,6 +368,55 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("replaces only the targeted custom keybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+alt+r",
|
||||
command: "script.run-tests.run",
|
||||
replace: { key: "mod+r", command: "script.run-tests.run" },
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+alt+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("removes only the targeted custom keybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.removeKeybindingRule({
|
||||
key: "mod+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
type ServerRemoveKeybindingInput,
|
||||
type ServerUpsertKeybindingInput,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -124,6 +126,25 @@ function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): bo
|
||||
return leftContext === rightContext;
|
||||
}
|
||||
|
||||
function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
|
||||
return input.when === undefined
|
||||
? { key: input.key, command: input.command }
|
||||
: { key: input.key, command: input.command, when: input.when };
|
||||
}
|
||||
|
||||
function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
|
||||
if (!input.replace) return null;
|
||||
return input.replace.when === undefined
|
||||
? { key: input.replace.key, command: input.replace.command }
|
||||
: { key: input.replace.key, command: input.replace.command, when: input.replace.when };
|
||||
}
|
||||
|
||||
function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
|
||||
return input.when === undefined
|
||||
? { key: input.key, command: input.command }
|
||||
: { key: input.key, command: input.command, when: input.when };
|
||||
}
|
||||
|
||||
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
|
||||
const modifiers: string[] = [];
|
||||
if (shortcut.modKey) modifiers.push("mod");
|
||||
@@ -259,7 +280,14 @@ export interface KeybindingsShape {
|
||||
* oldest entries when needed.
|
||||
*/
|
||||
readonly upsertKeybindingRule: (
|
||||
rule: KeybindingRule,
|
||||
input: ServerUpsertKeybindingInput,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
|
||||
/**
|
||||
* Remove a single persisted keybinding rule by exact key/command/when match.
|
||||
*/
|
||||
readonly removeKeybindingRule: (
|
||||
input: ServerRemoveKeybindingInput,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
}
|
||||
|
||||
@@ -616,12 +644,19 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
upsertKeybindingRule: (rule) =>
|
||||
upsertKeybindingRule: (input) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const rule = keybindingRuleFromUpsertInput(input);
|
||||
const replaceTarget = replaceTargetFromUpsertInput(input);
|
||||
const nextConfig = [
|
||||
...customConfig.filter((entry) => entry.command !== rule.command),
|
||||
...customConfig.filter((entry) => {
|
||||
if (replaceTarget) {
|
||||
return !isSameKeybindingRule(entry, replaceTarget);
|
||||
}
|
||||
return !isSameKeybindingRule(entry, rule);
|
||||
}),
|
||||
rule,
|
||||
];
|
||||
const cappedConfig =
|
||||
@@ -649,6 +684,27 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
return nextResolved;
|
||||
}),
|
||||
),
|
||||
removeKeybindingRule: (input) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const target = keybindingRuleFromRemoveInput(input);
|
||||
const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
|
||||
yield* writeConfigAtomically(nextConfig);
|
||||
const nextResolved = mergeWithDefaultKeybindings(
|
||||
compileResolvedKeybindingsConfig(nextConfig),
|
||||
);
|
||||
yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
|
||||
keybindings: nextResolved,
|
||||
issues: [],
|
||||
});
|
||||
yield* emitChange({
|
||||
keybindings: nextResolved,
|
||||
issues: [],
|
||||
});
|
||||
return nextResolved;
|
||||
}),
|
||||
),
|
||||
} satisfies KeybindingsShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { Effect, Metric } from "effect";
|
||||
import { Duration, Effect, Fiber, Metric } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { withMetrics } from "./Metrics.ts";
|
||||
|
||||
@@ -15,6 +16,18 @@ const hasMetricSnapshot = (
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
const findHistogramSnapshot = (
|
||||
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
|
||||
id: string,
|
||||
attributes: Readonly<Record<string, string>>,
|
||||
) =>
|
||||
snapshots.find(
|
||||
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Histogram" }> =>
|
||||
snapshot.type === "Histogram" &&
|
||||
snapshot.id === id &&
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
describe("withMetrics", () => {
|
||||
it.effect("supports pipe-style usage", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -110,4 +123,35 @@ describe("withMetrics", () => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records timer durations from nanosecond clock readings", () =>
|
||||
Effect.gen(function* () {
|
||||
const duration = Duration.nanos(1_500_000n);
|
||||
const timer = Metric.timer("with_metrics_nanos_duration");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const fiber = yield* Effect.sleep(duration).pipe(
|
||||
withMetrics({
|
||||
timer,
|
||||
attributes: {
|
||||
operation: "nanos",
|
||||
},
|
||||
}),
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(duration);
|
||||
yield* Fiber.join(fiber);
|
||||
}).pipe(Effect.provide(TestClock.layer()));
|
||||
|
||||
const snapshots = yield* Metric.snapshot;
|
||||
const snapshot = findHistogramSnapshot(snapshots, "with_metrics_nanos_duration", {
|
||||
operation: "nanos",
|
||||
});
|
||||
|
||||
assert.equal(snapshot?.state.count, 1);
|
||||
assert.equal(snapshot?.state.sum, 1.5);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Duration, Effect, Exit, Metric } from "effect";
|
||||
import { Clock, Duration, Effect, Exit, Metric } from "effect";
|
||||
import { dual } from "effect/Function";
|
||||
|
||||
import {
|
||||
@@ -96,9 +96,11 @@ const withMetricsImpl = <A, E, R>(
|
||||
options: WithMetricsOptions,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
const startedAt = Date.now();
|
||||
const startedAt = yield* Clock.currentTimeNanos;
|
||||
const exit = yield* Effect.exit(effect);
|
||||
const duration = Duration.millis(Math.max(0, Date.now() - startedAt));
|
||||
const endedAt = yield* Clock.currentTimeNanos;
|
||||
const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;
|
||||
const duration = Duration.nanos(elapsedNanos);
|
||||
const baseAttributes =
|
||||
typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Exit, Metric, Stream } from "effect";
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { Duration, Effect, Exit, Fiber, Metric, Stream, Tracer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import {
|
||||
observeRpcEffect,
|
||||
@@ -18,6 +20,44 @@ const hasMetricSnapshot = (
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
const findHistogramSnapshot = (
|
||||
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
|
||||
id: string,
|
||||
attributes: Readonly<Record<string, string>>,
|
||||
) =>
|
||||
snapshots.find(
|
||||
(snapshot): snapshot is Extract<Metric.Metric.Snapshot, { readonly type: "Histogram" }> =>
|
||||
snapshot.type === "Histogram" &&
|
||||
snapshot.id === id &&
|
||||
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
|
||||
);
|
||||
|
||||
const collectSpanNames = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<ReadonlyArray<string>, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames: Array<string> = [];
|
||||
const tracer = Tracer.make({
|
||||
span: (options) => {
|
||||
const span = new Tracer.NativeSpan(options);
|
||||
const end = span.end.bind(span);
|
||||
|
||||
span.end = (endTime, exit) => {
|
||||
end(endTime, exit);
|
||||
if (span.sampled) {
|
||||
spanNames.push(span.name);
|
||||
}
|
||||
};
|
||||
|
||||
return span;
|
||||
},
|
||||
});
|
||||
|
||||
yield* effect.pipe(Effect.withTracer(tracer));
|
||||
|
||||
return spanNames;
|
||||
});
|
||||
|
||||
describe("RpcInstrumentation", () => {
|
||||
it.effect("records success metrics for unary RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -129,6 +169,37 @@ describe("RpcInstrumentation", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records direct stream durations from nanosecond clock readings", () =>
|
||||
Effect.gen(function* () {
|
||||
const duration = Duration.nanos(1_500_000n);
|
||||
const events = yield* Effect.gen(function* () {
|
||||
const fiber = yield* Stream.runCollect(
|
||||
observeRpcStream(
|
||||
WS_METHODS.serverGetProcessDiagnostics,
|
||||
Stream.fromEffect(Effect.sleep(duration).pipe(Effect.as("ok"))),
|
||||
{
|
||||
"rpc.aggregate": "test",
|
||||
},
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(duration);
|
||||
return yield* Fiber.join(fiber);
|
||||
}).pipe(Effect.provide(TestClock.layer()));
|
||||
|
||||
assert.deepStrictEqual(Array.from(events), ["ok"]);
|
||||
|
||||
const snapshots = yield* Metric.snapshot;
|
||||
const snapshot = findHistogramSnapshot(snapshots, "t3_rpc_request_duration", {
|
||||
method: WS_METHODS.serverGetProcessDiagnostics,
|
||||
});
|
||||
|
||||
assert.equal(snapshot?.state.count, 1);
|
||||
assert.equal(snapshot?.state.sum, 1.5);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
|
||||
Effect.gen(function* () {
|
||||
const exit = yield* Stream.runCollect(
|
||||
@@ -158,4 +229,79 @@ describe("RpcInstrumentation", () => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records spans for traced stream RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
Stream.runCollect(
|
||||
observeRpcStream(
|
||||
"rpc.instrumentation.traced.stream",
|
||||
Stream.fromEffect(
|
||||
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.traced.stream.child")),
|
||||
),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(spanNames.includes("ws.rpc.rpc.instrumentation.traced.stream"), true);
|
||||
assert.equal(spanNames.includes("rpc.instrumentation.traced.stream.child"), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create spans for disabled unary RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
Effect.succeed("ok").pipe(Effect.withSpan("rpc.instrumentation.disabled.unary.child")),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(spanNames, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create spans for disabled direct stream RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
Stream.runCollect(
|
||||
observeRpcStream(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
Stream.fromEffect(
|
||||
Effect.succeed("ok").pipe(
|
||||
Effect.withSpan("rpc.instrumentation.disabled.stream.child"),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(spanNames, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create spans for disabled stream effect RPC handlers", () =>
|
||||
Effect.gen(function* () {
|
||||
const spanNames = yield* collectSpanNames(
|
||||
Stream.runCollect(
|
||||
observeRpcStreamEffect(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
Effect.succeed(
|
||||
Stream.fromEffect(
|
||||
Effect.succeed("ok").pipe(
|
||||
Effect.withSpan("rpc.instrumentation.disabled.stream.effect.consume"),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.withSpan("rpc.instrumentation.disabled.stream.effect.create")),
|
||||
{ "rpc.aggregate": "test" },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(spanNames, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,26 +1,71 @@
|
||||
import { Duration, Effect, Exit, Metric, Stream } from "effect";
|
||||
import { WS_METHODS } from "@t3tools/contracts";
|
||||
import { Clock, Duration, Effect, Exit, Metric, References, Stream } from "effect";
|
||||
|
||||
import { outcomeFromExit } from "./Attributes.ts";
|
||||
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
|
||||
|
||||
const annotateRpcSpan = (
|
||||
const RPC_SPAN_PREFIX = "ws.rpc";
|
||||
const DEFAULT_RPC_SPAN_ATTRIBUTES = {
|
||||
"rpc.transport": "websocket",
|
||||
"rpc.system": "effect-rpc",
|
||||
} as const;
|
||||
const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
WS_METHODS.serverGetProcessDiagnostics,
|
||||
WS_METHODS.serverSignalProcess,
|
||||
]);
|
||||
|
||||
function shouldTraceRpc(method: string): boolean {
|
||||
return !RPC_METHODS_WITH_TRACING_DISABLED.has(method);
|
||||
}
|
||||
|
||||
const rpcSpanAttributes = (
|
||||
method: string,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Effect.Effect<void, never, never> =>
|
||||
Effect.annotateCurrentSpan({
|
||||
"rpc.method": method,
|
||||
...traceAttributes,
|
||||
});
|
||||
): Record<string, unknown> => ({
|
||||
...DEFAULT_RPC_SPAN_ATTRIBUTES,
|
||||
"rpc.method": method,
|
||||
...traceAttributes,
|
||||
});
|
||||
|
||||
const withRpcEffectTracing = <A, E, R>(
|
||||
method: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
shouldTraceRpc(method)
|
||||
? effect.pipe(
|
||||
Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
|
||||
attributes: rpcSpanAttributes(method, traceAttributes),
|
||||
}),
|
||||
)
|
||||
: effect.pipe(Effect.provideService(References.TracerEnabled, false));
|
||||
|
||||
const withRpcStreamTracing = <A, E, R>(
|
||||
method: string,
|
||||
stream: Stream.Stream<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, E, R> =>
|
||||
shouldTraceRpc(method)
|
||||
? stream.pipe(
|
||||
Stream.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
|
||||
attributes: rpcSpanAttributes(method, traceAttributes),
|
||||
}),
|
||||
)
|
||||
: stream.pipe(Stream.provideService(References.TracerEnabled, false));
|
||||
|
||||
const recordRpcStreamMetrics = <E>(
|
||||
method: string,
|
||||
startedAt: number,
|
||||
startedAt: bigint,
|
||||
exit: Exit.Exit<unknown, E>,
|
||||
): Effect.Effect<void, never, never> =>
|
||||
Effect.gen(function* () {
|
||||
const endedAt = yield* Clock.currentTimeNanos;
|
||||
const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;
|
||||
|
||||
yield* Metric.update(
|
||||
Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
|
||||
Duration.millis(Math.max(0, Date.now() - startedAt)),
|
||||
Duration.nanos(elapsedNanos),
|
||||
);
|
||||
yield* Metric.update(
|
||||
Metric.withAttributes(
|
||||
@@ -38,43 +83,43 @@ export const observeRpcEffect = <A, E, R>(
|
||||
method: string,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Effect.Effect<A, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
yield* annotateRpcSpan(method, traceAttributes);
|
||||
): Effect.Effect<A, E, R> => {
|
||||
const instrumented = effect.pipe(
|
||||
withMetrics({
|
||||
counter: rpcRequestsTotal,
|
||||
timer: rpcRequestDuration,
|
||||
attributes: {
|
||||
method,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
return yield* effect.pipe(
|
||||
withMetrics({
|
||||
counter: rpcRequestsTotal,
|
||||
timer: rpcRequestDuration,
|
||||
attributes: {
|
||||
method,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
return withRpcEffectTracing(method, instrumented, traceAttributes);
|
||||
};
|
||||
|
||||
export const observeRpcStream = <A, E, R>(
|
||||
method: string,
|
||||
stream: Stream.Stream<A, E, R>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, E, R> =>
|
||||
Stream.unwrap(
|
||||
): Stream.Stream<A, E, R> => {
|
||||
const instrumented = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
yield* annotateRpcSpan(method, traceAttributes);
|
||||
const startedAt = Date.now();
|
||||
const startedAt = yield* Clock.currentTimeNanos;
|
||||
return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
|
||||
}),
|
||||
);
|
||||
|
||||
return withRpcStreamTracing(method, instrumented, traceAttributes);
|
||||
};
|
||||
|
||||
export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
|
||||
method: string,
|
||||
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
|
||||
traceAttributes?: Readonly<Record<string, unknown>>,
|
||||
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
|
||||
Stream.unwrap(
|
||||
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> => {
|
||||
const instrumented = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
yield* annotateRpcSpan(method, traceAttributes);
|
||||
const startedAt = Date.now();
|
||||
const startedAt = yield* Clock.currentTimeNanos;
|
||||
const exit = yield* Effect.exit(effect);
|
||||
|
||||
if (Exit.isFailure(exit)) {
|
||||
@@ -87,3 +132,6 @@ export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectErro
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return withRpcStreamTracing(method, instrumented, traceAttributes);
|
||||
};
|
||||
@@ -98,6 +98,105 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
command: "idea",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const aquaLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLaunch, {
|
||||
command: "aqua",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const clionLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLaunch, {
|
||||
command: "clion",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const datagripLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLaunch, {
|
||||
command: "datagrip",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const dataspellLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLaunch, {
|
||||
command: "dataspell",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const golandLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLaunch, {
|
||||
command: "goland",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const phpstormLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLaunch, {
|
||||
command: "phpstorm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const pycharmLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLaunch, {
|
||||
command: "pycharm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const riderLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLaunch, {
|
||||
command: "rider",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const rubymineLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLaunch, {
|
||||
command: "rubymine",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const rustroverLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLaunch, {
|
||||
command: "rustrover",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const webstormLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "webstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(webstormLaunch, {
|
||||
command: "webstorm",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -207,6 +306,105 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
command: "idea",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const aquaLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "aqua" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(aquaLineAndColumn, {
|
||||
command: "aqua",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const clionLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "clion" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(clionLineAndColumn, {
|
||||
command: "clion",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const datagripLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "datagrip" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(datagripLineAndColumn, {
|
||||
command: "datagrip",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const dataspellLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "dataspell" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(dataspellLineAndColumn, {
|
||||
command: "dataspell",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const golandLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "goland" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(golandLineAndColumn, {
|
||||
command: "goland",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const phpstormLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "phpstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(phpstormLineAndColumn, {
|
||||
command: "phpstorm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const pycharmLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "pycharm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(pycharmLineAndColumn, {
|
||||
command: "pycharm",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const riderLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rider" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(riderLineAndColumn, {
|
||||
command: "rider",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const rubymineLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rubymine" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rubymineLineAndColumn, {
|
||||
command: "rubymine",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const rustroverLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rustrover" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(rustroverLineAndColumn, {
|
||||
command: "rustrover",
|
||||
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
|
||||
});
|
||||
|
||||
const webstormLineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "webstorm" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(webstormLineOnly, {
|
||||
command: "webstorm",
|
||||
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -377,12 +575,40 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "aqua.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "clion.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "datagrip.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "dataspell.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "goland.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "phpstorm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "pycharm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rider.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rubymine.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "rustrover.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "webstorm.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, [
|
||||
"trae",
|
||||
"kiro",
|
||||
"vscode-insiders",
|
||||
"vscodium",
|
||||
"aqua",
|
||||
"clion",
|
||||
"datagrip",
|
||||
"dataspell",
|
||||
"goland",
|
||||
"phpstorm",
|
||||
"pycharm",
|
||||
"rider",
|
||||
"rubymine",
|
||||
"rustrover",
|
||||
"webstorm",
|
||||
"file-manager",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
@@ -34,15 +35,43 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
|
||||
|
||||
function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.local/bin/claude") ||
|
||||
normalized.endsWith("/.local/bin/claude.exe") ||
|
||||
normalized.includes("/.local/share/claude/")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@anthropic-ai/claude-code",
|
||||
homebrewFormula: "claude-code",
|
||||
nativeUpdate: {
|
||||
executable: "claude",
|
||||
args: ["update"],
|
||||
lockKey: "claude-native",
|
||||
isCommandPath: isClaudeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -75,6 +104,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -82,6 +112,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
instanceId,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
@@ -121,11 +155,17 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
*/
|
||||
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
@@ -35,6 +36,11 @@ import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import {
|
||||
codexContinuationIdentity,
|
||||
materializeCodexShadowHome,
|
||||
@@ -43,6 +49,12 @@ import {
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
homebrewFormula: "codex",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
|
||||
/**
|
||||
* Services the driver needs to materialize an instance. Surfaced as the
|
||||
@@ -52,6 +64,7 @@ const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
export type CodexDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -89,6 +102,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const homeLayout = yield* resolveCodexHomeLayout(config);
|
||||
@@ -115,6 +129,10 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
enabled,
|
||||
homePath: homeLayout.effectiveHomePath ?? "",
|
||||
} satisfies CodexSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
|
||||
// channels at construction time — their failure modes are all on the
|
||||
@@ -138,11 +156,17 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
const snapshot = yield* makeManagedServerProvider<CodexSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingCodexProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -34,13 +35,28 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
}),
|
||||
);
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
| ServerConfig;
|
||||
@@ -74,6 +90,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -87,6 +104,10 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeCursorAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
@@ -103,6 +124,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
);
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<CursorSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
@@ -117,8 +139,10 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
settings,
|
||||
environment: processEnv,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
|
||||
@@ -34,13 +35,40 @@ import {
|
||||
} from "../ProviderDriver.ts";
|
||||
import type { ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("opencode");
|
||||
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
|
||||
|
||||
function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.endsWith("/.opencode/bin/opencode") ||
|
||||
normalized.endsWith("/.opencode/bin/opencode.exe")
|
||||
);
|
||||
}
|
||||
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "opencode-ai",
|
||||
homebrewFormula: "anomalyco/tap/opencode",
|
||||
nativeUpdate: {
|
||||
executable: "opencode",
|
||||
args: ["upgrade"],
|
||||
lockKey: "opencode-native",
|
||||
isCommandPath: isOpenCodeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
| Path.Path
|
||||
| ProviderEventLoggers
|
||||
@@ -74,6 +102,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
Effect.gen(function* () {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -87,6 +116,10 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
|
||||
instanceId,
|
||||
@@ -102,11 +135,17 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
|
||||
|
||||
const snapshot = yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed(effectiveConfig),
|
||||
streamSettings: Stream.never,
|
||||
haveSettingsChanged: () => false,
|
||||
initialSnapshot: (settings) => stampIdentity(makePendingOpenCodeProvider(settings)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -15,7 +15,6 @@ import type {
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { Cause, Effect, Exit, FileSystem, Layer, Option, Path, Result } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
createModelCapabilities,
|
||||
@@ -29,6 +30,10 @@ import {
|
||||
type CommandResult,
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("cursor");
|
||||
@@ -1216,42 +1221,67 @@ export const enrichCursorSnapshot = (input: {
|
||||
readonly settings: CursorSettings;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
|
||||
readonly httpClient: HttpClient.HttpClient;
|
||||
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
const { settings, snapshot, publishSnapshot } = input;
|
||||
const stampIdentity = input.stampIdentity ?? ((value) => value);
|
||||
|
||||
if (
|
||||
!settings.enabled ||
|
||||
snapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(snapshot)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return discoverCursorModelCapabilitiesViaAcp(settings, snapshot.models, input.environment).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...snapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
const enrichVersionAdvisory = enrichProviderSnapshotWithVersionAdvisory(
|
||||
snapshot,
|
||||
input.maintenanceCapabilities,
|
||||
).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, input.httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) =>
|
||||
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: snapshot.models.map((model) => model.slug),
|
||||
Effect.logWarning("Cursor version advisory enrichment failed", {
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
}).pipe(Effect.as(snapshot)),
|
||||
),
|
||||
);
|
||||
|
||||
return enrichVersionAdvisory.pipe(
|
||||
Effect.flatMap((baseSnapshot) => {
|
||||
if (
|
||||
!settings.enabled ||
|
||||
baseSnapshot.auth.status === "unauthenticated" ||
|
||||
!hasUncapturedCursorModels(baseSnapshot)
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return discoverCursorModelCapabilitiesViaAcp(
|
||||
settings,
|
||||
baseSnapshot.models,
|
||||
input.environment,
|
||||
).pipe(
|
||||
Effect.flatMap((discoveredModels) => {
|
||||
if (discoveredModels.length === 0) {
|
||||
return Effect.void;
|
||||
}
|
||||
return publishSnapshot(
|
||||
stampIdentity({
|
||||
...baseSnapshot,
|
||||
models: providerModelsFromSettings(
|
||||
discoveredModels,
|
||||
PROVIDER,
|
||||
settings.customModels,
|
||||
EMPTY_CAPABILITIES,
|
||||
),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Cursor ACP background capability enrichment failed", {
|
||||
models: baseSnapshot.models.map((model) => model.slug),
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
import { Cause, Data, Effect } from "effect";
|
||||
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
nonEmptyTrimmed,
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
@@ -111,6 +112,10 @@ const makeFakeInstance = (
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driverKind,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
|
||||
refresh: Effect.succeed({} as unknown as ServerProvider),
|
||||
streamChanges: Stream.empty,
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
@@ -44,6 +45,13 @@ import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
|
||||
import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
|
||||
enabled: false,
|
||||
binaryPath: "codex",
|
||||
@@ -89,6 +97,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
prefix: "provider-instance-registry-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
@@ -225,6 +234,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
|
||||
prefix: "provider-instance-registry-all-drivers-test",
|
||||
}).pipe(
|
||||
Layer.provideMerge(infraLayer),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type ServerSettings as ContractServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
@@ -26,13 +27,17 @@ import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistr
|
||||
import {
|
||||
haveProvidersChanged,
|
||||
mergeProviderSnapshot,
|
||||
mergeProviderSnapshots,
|
||||
ProviderRegistryLive,
|
||||
selectProvidersByKind,
|
||||
} from "./ProviderRegistry.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
|
||||
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
|
||||
@@ -46,6 +51,13 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const TestHttpClientLive = Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
|
||||
),
|
||||
);
|
||||
|
||||
function selectDescriptor(
|
||||
id: string,
|
||||
label: string,
|
||||
@@ -246,7 +258,7 @@ function makeMutableServerSettingsService(
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), TestHttpClientLive))(
|
||||
"ProviderRegistry",
|
||||
(it) => {
|
||||
describe("checkCodexProviderStatus", () => {
|
||||
@@ -500,6 +512,182 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
]);
|
||||
});
|
||||
|
||||
it("persists merged provider snapshots for the providers that were refreshed", () => {
|
||||
const previousProviders = [
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("cursor"),
|
||||
driver: ProviderDriverKind.make("cursor"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
booleanDescriptor("fastMode", "Fast Mode"),
|
||||
booleanDescriptor("thinking", "Thinking"),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
{
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
] as const satisfies ReadonlyArray<ServerProvider>;
|
||||
const refreshedCursor = {
|
||||
...previousProviders[0],
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]);
|
||||
const persistedProviders = selectProvidersByKind(
|
||||
mergedProviders,
|
||||
new Set([ProviderDriverKind.make("cursor")]),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(persistedProviders, [
|
||||
{
|
||||
...refreshedCursor,
|
||||
models: [...previousProviders[0].models],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("persists the merged snapshot when a live update has empty models", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorDriver = ProviderDriverKind.make("cursor");
|
||||
const cursorInstanceId = ProviderInstanceId.make("cursor");
|
||||
const initialProvider = {
|
||||
instanceId: cursorInstanceId,
|
||||
driver: cursorDriver,
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
selectDescriptor("reasoning", "Reasoning", [
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...initialProvider,
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
const changes = yield* PubSub.unbounded<ServerProvider>();
|
||||
const instance = {
|
||||
instanceId: cursorInstanceId,
|
||||
driverKind: cursorDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: cursorDriver,
|
||||
continuationKey: "cursor:instance:cursor",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cursorDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Effect.succeed(refreshedProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === cursorInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
|
||||
PubSub.subscribe(pubsub),
|
||||
),
|
||||
});
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-merged-persist-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
const config = yield* ServerConfig;
|
||||
const filePath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: config.providerStatusCacheDir,
|
||||
instanceId: cursorInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
|
||||
...initialProvider.models,
|
||||
]);
|
||||
yield* PubSub.publish(changes, refreshedProvider);
|
||||
|
||||
let cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
|
||||
attempt += 1
|
||||
) {
|
||||
yield* Effect.sleep("10 millis");
|
||||
cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(cachedProvider, {
|
||||
...refreshedProvider,
|
||||
models: [...initialProvider.models],
|
||||
});
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the cached provider list when a manual refresh fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
@@ -527,6 +715,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(cachedProvider),
|
||||
refresh: Effect.die(new Error("simulated refresh failure")),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -612,6 +804,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: provider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(provider),
|
||||
refresh: Effect.succeed(provider),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -748,6 +944,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// NO spawner mock — `ChildProcessSpawner` is supplied by the
|
||||
@@ -832,6 +1029,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
// `it.live` does not inherit layers from the outer `it.layer`
|
||||
@@ -936,6 +1134,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -986,6 +1185,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(TestHttpClientLive),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
Layer.provideMerge(
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
@@ -43,6 +44,7 @@ import {
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
import type { ProviderInstance } from "../ProviderDriver.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import type { ProviderSnapshotSource } from "../builtInProviderCatalog.ts";
|
||||
|
||||
const loadProviders = (
|
||||
@@ -59,6 +61,12 @@ const loadProviders = (
|
||||
},
|
||||
);
|
||||
|
||||
const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.optionDescriptors?.length ?? 0) > 0;
|
||||
|
||||
@@ -96,6 +104,30 @@ export const mergeProviderSnapshot = (
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(
|
||||
snapshotInstanceKey(provider),
|
||||
mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),
|
||||
);
|
||||
}
|
||||
|
||||
return orderProviderSnapshots([...mergedProviders.values()]);
|
||||
};
|
||||
|
||||
export const selectProvidersByKind = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
providerKinds: ReadonlySet<ProviderDriverKind>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
providers.filter((provider) => providerKinds.has(provider.driver));
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
@@ -227,6 +259,9 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
),
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);
|
||||
const maintenanceActionStatesRef = yield* Ref.make<
|
||||
ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>
|
||||
>(new Map());
|
||||
|
||||
// Live-source registry — the dynamic counterpart to the boot-time
|
||||
// `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`
|
||||
@@ -264,6 +299,21 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
);
|
||||
});
|
||||
|
||||
const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
|
||||
provider: ServerProvider,
|
||||
) {
|
||||
const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);
|
||||
const updateState = maintenanceActionStates.get(provider.instanceId)?.update;
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = provider;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...provider,
|
||||
updateState,
|
||||
};
|
||||
});
|
||||
|
||||
const upsertProviders = Effect.fn("upsertProviders")(function* (
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
options?: {
|
||||
@@ -272,15 +322,24 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
readonly replace?: boolean;
|
||||
},
|
||||
) {
|
||||
const [previousProviders, providers] = yield* Ref.modify(
|
||||
const nextProvidersWithUpdateState = yield* Effect.forEach(
|
||||
nextProviders,
|
||||
applyProviderUpdateState,
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
|
||||
providersRef,
|
||||
(previousProviders) => {
|
||||
const mergedProviders = new Map(
|
||||
previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),
|
||||
);
|
||||
const updatedKeys = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
for (const provider of nextProvidersWithUpdateState) {
|
||||
const key = snapshotInstanceKey(provider);
|
||||
updatedKeys.add(key);
|
||||
mergedProviders.set(
|
||||
key,
|
||||
options?.replace === true
|
||||
@@ -290,13 +349,16 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
return [[previousProviders, providers] as const, providers];
|
||||
const providersToPersist = providers.filter((provider) =>
|
||||
updatedKeys.has(snapshotInstanceKey(provider)),
|
||||
);
|
||||
return [[previousProviders, providers, providersToPersist] as const, providers];
|
||||
},
|
||||
);
|
||||
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
if (options?.persist !== false) {
|
||||
yield* Effect.forEach(nextProviders, persistProvider, {
|
||||
yield* Effect.forEach(providersToPersist, persistProvider, {
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
});
|
||||
@@ -318,6 +380,45 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* upsertProviders([provider], options);
|
||||
});
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn("setProviderMaintenanceActionState")(
|
||||
function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const previousActions = previous.get(input.instanceId);
|
||||
const nextActions = { ...previousActions };
|
||||
if (input.state === null || input.state.status === "idle") {
|
||||
delete nextActions[input.action];
|
||||
} else {
|
||||
nextActions[input.action] = input.state;
|
||||
}
|
||||
|
||||
const next = new Map(previous);
|
||||
if (Object.keys(nextActions).length === 0) {
|
||||
next.delete(input.instanceId);
|
||||
} else {
|
||||
next.set(input.instanceId, nextActions);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
const existingProviders = yield* Ref.get(providersRef);
|
||||
const matchingProvider = existingProviders.find(
|
||||
(candidate) => candidate.instanceId === input.instanceId,
|
||||
);
|
||||
if (!matchingProvider) {
|
||||
return existingProviders;
|
||||
}
|
||||
|
||||
const nextProvider = yield* applyProviderUpdateState(matchingProvider);
|
||||
return yield* upsertProviders([nextProvider], {
|
||||
persist: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
|
||||
providerSource: ProviderSnapshotSource,
|
||||
) {
|
||||
@@ -365,6 +466,18 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
return yield* refreshOneSource(providerSource);
|
||||
});
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Diff the aggregator's live-source set against the current
|
||||
* `ProviderInstanceRegistry` and:
|
||||
@@ -472,6 +585,15 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
if (haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
yield* Ref.update(maintenanceActionStatesRef, (previous) => {
|
||||
const next = new Map(previous);
|
||||
for (const instanceId of previous.keys()) {
|
||||
if (!knownInstanceIds.has(instanceId)) {
|
||||
next.delete(instanceId);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
);
|
||||
const syncLiveSourcesAndContinue = syncLiveSources.pipe(
|
||||
@@ -555,6 +677,8 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
refreshInstance: (instanceId: ProviderInstanceId) =>
|
||||
refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),
|
||||
getProviderMaintenanceCapabilitiesForInstance,
|
||||
setProviderMaintenanceActionState,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
|
||||
@@ -6,9 +6,17 @@
|
||||
*
|
||||
* @module ProviderRegistry
|
||||
*/
|
||||
import type { ProviderInstanceId, ProviderDriverKind, ServerProvider } from "@t3tools/contracts";
|
||||
import type {
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ServerProvider,
|
||||
ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export type ProviderMaintenanceActionKind = "update";
|
||||
|
||||
export interface ProviderRegistryShape {
|
||||
/**
|
||||
@@ -39,6 +47,27 @@ export interface ProviderRegistryShape {
|
||||
instanceId: ProviderInstanceId,
|
||||
) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Resolve the maintenance capabilities owned by one live provider instance.
|
||||
* Falls back to manual-only capabilities when the instance is not live.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
* Apply volatile maintenance-action state to one configured instance.
|
||||
* This state is never persisted to disk. Today only update actions are
|
||||
* projected onto `ServerProvider.updateState`; install/auth actions can
|
||||
* extend this action map without adding driver-scoped APIs.
|
||||
*/
|
||||
readonly setProviderMaintenanceActionState: (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: ProviderMaintenanceActionKind;
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProvider>>;
|
||||
|
||||
/**
|
||||
* Stream of provider snapshot updates — one emission per aggregated
|
||||
* change. The array contains the full current state.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export interface ServerProviderShape {
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
|
||||
@@ -20,6 +20,20 @@ interface TestSettings {
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
const maintenanceCapabilities = {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
packageName: "@openai/codex",
|
||||
update: {
|
||||
command: "npm install -g @openai/codex@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
} as const;
|
||||
|
||||
const initialSnapshot: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
@@ -90,6 +104,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -131,6 +146,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseInitialCheck = yield* Deferred.make<void>();
|
||||
const releaseSettingsCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Ref.get(settingsRef),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -172,6 +188,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseEnrichment = yield* Deferred.make<void>();
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -212,6 +229,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const secondCallbackReady = yield* Deferred.make<void>();
|
||||
const allowFirstRefresh = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
|
||||
@@ -13,6 +13,7 @@ interface ProviderSnapshotState {
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
@@ -143,6 +144,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
);
|
||||
|
||||
return {
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { Effect, Random } from "effect";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
createProviderVersionAdvisory,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const makeTempDir = Effect.fn("makeTempDir")(function* (name: string) {
|
||||
const id = yield* Random.nextUUIDv4;
|
||||
return path.join(os.tmpdir(), `${name}-${id}`);
|
||||
});
|
||||
const isNativeTestCommandPath =
|
||||
(expectedPathSegment: string) =>
|
||||
(commandPath: string): boolean =>
|
||||
normalizeCommandPath(commandPath).includes(expectedPathSegment);
|
||||
const packageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("packageTool"),
|
||||
npmPackageName: "@example/package-tool",
|
||||
homebrewFormula: "package-tool",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("nativePackageTool"),
|
||||
npmPackageName: "@example/native-package-tool",
|
||||
homebrewFormula: "native-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "native-package-tool",
|
||||
args: ["update"],
|
||||
lockKey: "native-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"),
|
||||
},
|
||||
});
|
||||
const scopedPackageToolUpdate = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: driver("scopedPackageTool"),
|
||||
npmPackageName: "@example/scoped-package-tool",
|
||||
homebrewFormula: "example/tap/scoped-package-tool",
|
||||
nativeUpdate: {
|
||||
executable: "scoped-package-tool",
|
||||
args: ["upgrade"],
|
||||
lockKey: "scoped-package-tool-native",
|
||||
isCommandPath: isNativeTestCommandPath("/.scoped-package-tool/bin/scoped-package-tool"),
|
||||
},
|
||||
});
|
||||
const staticToolUpdate = makeStaticProviderMaintenanceResolver(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
updateExecutable: "static-tool",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "static-tool",
|
||||
}),
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
describe("providerMaintenance", () => {
|
||||
it("marks providers with unknown current versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: null,
|
||||
latestVersion: "9.9.9",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks providers with unknown latest versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("packageTool"),
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: null,
|
||||
message: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("marks installed providers behind latest when a newer provider version is available", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
driver: driver("nativePackageTool"),
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
maintenanceCapabilities: nativePackageToolUpdate.resolve(),
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.1.110",
|
||||
latestVersion: "2.1.117",
|
||||
updateCommand: "npm install -g @example/native-package-tool@latest",
|
||||
canUpdate: true,
|
||||
message: "Install the update now or review provider settings.",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps update commands owned by provider maintenance capabilities", () => {
|
||||
expect(staticToolUpdate.resolve()).toEqual({
|
||||
provider: driver("staticTool"),
|
||||
packageName: null,
|
||||
update: {
|
||||
command: "static-tool update",
|
||||
|
||||
executable: "static-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "static-tool",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to vite-plus updates when the resolved binary lives in vite-plus global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-vite-plus-capabilities");
|
||||
const vitePlusBinDir = path.join(tempDir, ".vite-plus", "bin");
|
||||
mkdirSync(vitePlusBinDir, { recursive: true });
|
||||
const packageToolPath = path.join(vitePlusBinDir, "package-tool");
|
||||
writeFileSync(packageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(packageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: vitePlusBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "vp i -g @example/package-tool",
|
||||
|
||||
executable: "vp",
|
||||
|
||||
args: ["i", "-g", "@example/package-tool"],
|
||||
|
||||
lockKey: "vite-plus-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to bun updates when the resolved binary lives in bun's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-bun-capabilities");
|
||||
const bunBinDir = path.join(tempDir, ".bun", "bin");
|
||||
mkdirSync(bunBinDir, { recursive: true });
|
||||
writeFileSync(path.join(bunBinDir, "native-package-tool.exe"), "MZ");
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: bunBinDir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "bun i -g @example/native-package-tool@latest",
|
||||
|
||||
executable: "bun",
|
||||
|
||||
args: ["i", "-g", "@example/native-package-tool@latest"],
|
||||
|
||||
lockKey: "bun-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches package-managed providers to pnpm updates when the resolved binary lives in pnpm's global bin",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-capabilities");
|
||||
const pnpmHomeDir = path.join(tempDir, ".local", "share", "pnpm");
|
||||
mkdirSync(pnpmHomeDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(pnpmHomeDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: pnpmHomeDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/scoped-package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/scoped-package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "brew upgrade package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"switches native-package-tool to native updates when the binary resolves through the native installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-native-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".local", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const nativePackageToolPath = path.join(nativeBinDir, "native-package-tool");
|
||||
writeFileSync(nativePackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(nativePackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "native-package-tool update",
|
||||
|
||||
executable: "native-package-tool",
|
||||
|
||||
args: ["update"],
|
||||
|
||||
lockKey: "native-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"switches scoped-package-tool to native upgrades when the binary resolves through the standalone installer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-scoped-package-tool-native-capabilities");
|
||||
const nativeBinDir = path.join(tempDir, ".scoped-package-tool", "bin");
|
||||
mkdirSync(nativeBinDir, { recursive: true });
|
||||
const scopedPackageToolPath = path.join(nativeBinDir, "scoped-package-tool");
|
||||
writeFileSync(scopedPackageToolPath, "#!/bin/sh\n");
|
||||
chmodSync(scopedPackageToolPath, 0o755);
|
||||
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: nativeBinDir,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "scoped-package-tool upgrade",
|
||||
|
||||
executable: "scoped-package-tool",
|
||||
|
||||
args: ["upgrade"],
|
||||
|
||||
lockKey: "scoped-package-tool-native",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("switches native-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
nativePackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/native-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("nativePackageTool"),
|
||||
packageName: "@example/native-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade native-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "native-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("switches scoped-package-tool to Homebrew updates when the binary resolves through Homebrew", () => {
|
||||
expect(
|
||||
scopedPackageToolUpdate.resolve({
|
||||
binaryPath: "/opt/homebrew/bin/scoped-package-tool",
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("scopedPackageTool"),
|
||||
packageName: "@example/scoped-package-tool",
|
||||
update: {
|
||||
command: "brew upgrade example/tap/scoped-package-tool",
|
||||
|
||||
executable: "brew",
|
||||
|
||||
args: ["upgrade", "example/tap/scoped-package-tool"],
|
||||
|
||||
lockKey: "homebrew",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("keeps npm updates for binaries symlinked into npm's global node_modules tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-npm-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
"lib",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "npm install -g @example/package-tool@latest",
|
||||
|
||||
executable: "npm",
|
||||
|
||||
args: ["install", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "npm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses Effect FileSystem realPath when detecting pnpm global symlinks", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = yield* makeTempDir("t3-pnpm-realpath-capabilities");
|
||||
const binDir = path.join(tempDir, "bin");
|
||||
const packageBinDir = path.join(
|
||||
tempDir,
|
||||
".local",
|
||||
"share",
|
||||
"pnpm",
|
||||
"global",
|
||||
"5",
|
||||
"node_modules",
|
||||
"@example",
|
||||
"package-tool",
|
||||
"bin",
|
||||
);
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(packageBinDir, { recursive: true });
|
||||
const packageBinPath = path.join(packageBinDir, "package-tool.js");
|
||||
const symlinkPath = path.join(binDir, "package-tool");
|
||||
writeFileSync(packageBinPath, "#!/usr/bin/env node\n");
|
||||
chmodSync(packageBinPath, 0o755);
|
||||
symlinkSync(packageBinPath, symlinkPath);
|
||||
|
||||
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, {
|
||||
binaryPath: symlinkPath,
|
||||
platform: "darwin",
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: {
|
||||
command: "pnpm add -g @example/package-tool@latest",
|
||||
|
||||
executable: "pnpm",
|
||||
|
||||
args: ["add", "-g", "@example/package-tool@latest"],
|
||||
|
||||
lockKey: "pnpm-global",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("disables one-click updates for explicit custom binary paths it cannot safely map", () => {
|
||||
expect(
|
||||
packageToolUpdate.resolve({
|
||||
binaryPath: "C:\\Tools\\package-tool\\package-tool.exe",
|
||||
platform: "win32",
|
||||
env: {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
packageName: "@example/package-tool",
|
||||
update: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,472 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderVersionAdvisory,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveCommandPath } from "@t3tools/shared/shell";
|
||||
import { DateTime, Effect, FileSystem, Option, Schema } from "effect";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import { compareCliVersions } from "./cliVersion.ts";
|
||||
|
||||
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
|
||||
const LATEST_VERSION_TIMEOUT_MS = 4_000;
|
||||
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
|
||||
|
||||
export interface ProviderMaintenanceCapabilities {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly update: ProviderMaintenanceCommandAction | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCommandAction {
|
||||
readonly command: string;
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilityResolutionOptions {
|
||||
readonly binaryPath?: string | null;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly realCommandPath?: string | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilitiesResolver {
|
||||
readonly resolve: (
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
) => ProviderMaintenanceCapabilities;
|
||||
}
|
||||
|
||||
export interface PackageManagedProviderMaintenanceDefinition {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly npmPackageName: string;
|
||||
readonly homebrewFormula: string | null;
|
||||
readonly nativeUpdate: {
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
readonly isCommandPath: (commandPath: string) => boolean;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface LatestVersionCacheEntry {
|
||||
readonly expiresAt: number;
|
||||
readonly version: string | null;
|
||||
}
|
||||
|
||||
const latestVersionCache = new Map<string, LatestVersionCacheEntry>();
|
||||
const NpmLatestVersionResponse = Schema.Struct({
|
||||
version: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export function clearLatestProviderVersionCacheForTests(): void {
|
||||
latestVersionCache.clear();
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
export function makeProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly updateExecutable: string | null;
|
||||
readonly updateArgs: ReadonlyArray<string>;
|
||||
readonly updateLockKey: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
const update =
|
||||
input.updateExecutable === null || input.updateLockKey === null
|
||||
? null
|
||||
: {
|
||||
command: [input.updateExecutable, ...input.updateArgs].join(" "),
|
||||
executable: input.updateExecutable,
|
||||
args: input.updateArgs,
|
||||
lockKey: input.updateLockKey,
|
||||
};
|
||||
return {
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
update,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeManualOnlyProviderMaintenanceCapabilities(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
updateExecutable: null,
|
||||
updateArgs: [],
|
||||
updateLockKey: null,
|
||||
});
|
||||
}
|
||||
|
||||
function makeNpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeBunGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "bun-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makePnpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "pnpm",
|
||||
updateArgs: ["add", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "pnpm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeVitePlusGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", definition.npmPackageName],
|
||||
updateLockKey: "vite-plus-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeHomebrewProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
if (!definition.homebrewFormula) {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "brew",
|
||||
updateArgs: ["upgrade", definition.homebrewFormula],
|
||||
updateLockKey: "homebrew",
|
||||
});
|
||||
}
|
||||
|
||||
function makeNativeProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities | null {
|
||||
if (!definition.nativeUpdate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: definition.nativeUpdate.executable,
|
||||
updateArgs: definition.nativeUpdate.args,
|
||||
updateLockKey: definition.nativeUpdate.lockKey,
|
||||
});
|
||||
}
|
||||
|
||||
export function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
}
|
||||
|
||||
export function normalizeCommandPath(commandPath: string): string {
|
||||
return commandPath.replaceAll("\\", "/").toLowerCase();
|
||||
}
|
||||
|
||||
function isBunGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.bun/bin/");
|
||||
}
|
||||
|
||||
function isVitePlusGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
|
||||
}
|
||||
|
||||
function isPnpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/.local/share/pnpm/") ||
|
||||
normalized.includes("/library/pnpm/") ||
|
||||
normalized.includes("/local/share/pnpm/") ||
|
||||
normalized.includes("/appdata/local/pnpm/") ||
|
||||
normalized.includes("/pnpm/global/")
|
||||
);
|
||||
}
|
||||
|
||||
function isNpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/node_modules/.bin/") ||
|
||||
normalized.includes("/lib/node_modules/") ||
|
||||
normalized.includes("/npm/node_modules/")
|
||||
);
|
||||
}
|
||||
|
||||
function isHomebrewCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/opt/homebrew/cellar/") ||
|
||||
normalized.includes("/usr/local/cellar/") ||
|
||||
normalized.includes("/homebrew/cellar/") ||
|
||||
normalized.includes("/opt/homebrew/caskroom/") ||
|
||||
normalized.includes("/usr/local/caskroom/") ||
|
||||
normalized.includes("/homebrew/caskroom/") ||
|
||||
normalized.startsWith("/opt/homebrew/bin/") ||
|
||||
normalized.startsWith("/usr/local/bin/")
|
||||
);
|
||||
}
|
||||
|
||||
export function resolvePackageManagedProviderMaintenance(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
|
||||
if (resolvedCommandPath) {
|
||||
const commandPaths = [
|
||||
resolvedCommandPath,
|
||||
...(options?.realCommandPath ? [options.realCommandPath] : []),
|
||||
];
|
||||
|
||||
const nativeUpdate = definition.nativeUpdate;
|
||||
if (
|
||||
nativeUpdate &&
|
||||
commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))
|
||||
) {
|
||||
return (
|
||||
makeNativeProviderMaintenanceCapabilities(definition) ??
|
||||
makeNpmGlobalProviderMaintenanceCapabilities(definition)
|
||||
);
|
||||
}
|
||||
if (commandPaths.some(isVitePlusGlobalCommandPath)) {
|
||||
return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isBunGlobalCommandPath)) {
|
||||
return makeBunGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isPnpmGlobalCommandPath)) {
|
||||
return makePnpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isNpmGlobalCommandPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isHomebrewCommandPath)) {
|
||||
return makeHomebrewProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasPathSeparator(binaryPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
export function makePackageManagedProviderMaintenanceResolver(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeStaticProviderMaintenanceResolver(
|
||||
capabilities: ProviderMaintenanceCapabilities,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: () => capabilities,
|
||||
};
|
||||
}
|
||||
|
||||
function makeManualProviderMaintenanceCapabilities(
|
||||
provider: ProviderDriverKind,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
"resolveProviderMaintenanceCapabilitiesEffect",
|
||||
)(function* (
|
||||
resolver: ProviderMaintenanceCapabilitiesResolver,
|
||||
options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, "realCommandPath">,
|
||||
) {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
resolveCommandPath(binaryPath, {
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
...(options?.env ? { env: options.env } : {}),
|
||||
}) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
if (!resolvedCommandPath) {
|
||||
return resolver.resolve(options);
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCommandPath = yield* fileSystem
|
||||
.realPath(resolvedCommandPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(resolvedCommandPath)));
|
||||
return resolver.resolve({
|
||||
...options,
|
||||
realCommandPath,
|
||||
});
|
||||
});
|
||||
|
||||
function deriveVersionAdvisory(input: {
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion: string | null;
|
||||
}): Pick<ServerProviderVersionAdvisory, "status" | "message"> {
|
||||
if (!input.currentVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (!input.latestVersion) {
|
||||
return { status: "unknown", message: null };
|
||||
}
|
||||
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
|
||||
return {
|
||||
status: "behind_latest",
|
||||
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
|
||||
};
|
||||
}
|
||||
return { status: "current", message: null };
|
||||
}
|
||||
|
||||
export function createProviderVersionAdvisory(input: {
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion?: string | null;
|
||||
readonly checkedAt?: string | null;
|
||||
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
|
||||
}): ServerProviderVersionAdvisory {
|
||||
const capabilities =
|
||||
input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);
|
||||
const latestVersion = input.latestVersion ?? null;
|
||||
const advisory = deriveVersionAdvisory({
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
});
|
||||
|
||||
return {
|
||||
status: advisory.status,
|
||||
currentVersion: input.currentVersion,
|
||||
latestVersion,
|
||||
updateCommand: capabilities.update?.command ?? null,
|
||||
canUpdate: capabilities.update !== null,
|
||||
checkedAt: input.checkedAt ?? null,
|
||||
message: advisory.message,
|
||||
};
|
||||
}
|
||||
|
||||
const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (packageName: string) {
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const request = HttpClientRequest.get(
|
||||
`https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,
|
||||
).pipe(HttpClientRequest.setHeader("accept", "application/json"));
|
||||
const response = yield* client.execute(request).pipe(
|
||||
Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),
|
||||
Effect.catch(() => Effect.succeed(Option.none())),
|
||||
);
|
||||
if (Option.isNone(response)) {
|
||||
return null;
|
||||
}
|
||||
const httpResponse = response.value;
|
||||
if (httpResponse.status < 200 || httpResponse.status >= 300) {
|
||||
return null;
|
||||
}
|
||||
const payload = yield* httpResponse.json.pipe(
|
||||
Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
return payload ? nonEmptyString(payload.version) : null;
|
||||
});
|
||||
|
||||
export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
) {
|
||||
const packageName = maintenanceCapabilities.packageName;
|
||||
if (!packageName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cached = latestVersionCache.get(packageName);
|
||||
const now = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
if (cached && cached.expiresAt > now) {
|
||||
return cached.version;
|
||||
}
|
||||
|
||||
const version = yield* fetchNpmLatestVersion(packageName);
|
||||
latestVersionCache.set(packageName, {
|
||||
expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,
|
||||
version,
|
||||
});
|
||||
return version;
|
||||
});
|
||||
|
||||
export const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(
|
||||
"enrichProviderSnapshotWithVersionAdvisory",
|
||||
)(function* (snapshot: ServerProvider, maintenanceCapabilities?: ProviderMaintenanceCapabilities) {
|
||||
const capabilities =
|
||||
maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);
|
||||
if (!snapshot.enabled || !snapshot.installed || !snapshot.version) {
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
checkedAt: snapshot.checkedAt,
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const latestVersion = yield* resolveLatestProviderVersion(capabilities);
|
||||
return {
|
||||
...snapshot,
|
||||
versionAdvisory: createProviderVersionAdvisory({
|
||||
driver: snapshot.driver,
|
||||
currentVersion: snapshot.version,
|
||||
latestVersion,
|
||||
checkedAt: DateTime.formatIso(yield* DateTime.now),
|
||||
maintenanceCapabilities: capabilities,
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Effect, Ref } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
export interface ProviderMaintenanceCommandCoordinatorShape<E> {
|
||||
readonly withCommandLock: <A, R>(input: {
|
||||
readonly targetKey: string;
|
||||
readonly lockKey: string;
|
||||
readonly onQueued?: Effect.Effect<void, E, R>;
|
||||
readonly run: Effect.Effect<A, E, R>;
|
||||
}) => Effect.Effect<A, E, R>;
|
||||
}
|
||||
|
||||
export const makeProviderMaintenanceCommandCoordinator = Effect.fn(
|
||||
"makeProviderMaintenanceCommandCoordinator",
|
||||
)(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {
|
||||
const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());
|
||||
const locksRef = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());
|
||||
|
||||
const acquireTarget = Effect.fn("acquireTarget")(function* (targetKey: string) {
|
||||
return yield* Ref.modify(runningTargetsRef, (runningTargets) => {
|
||||
if (runningTargets.has(targetKey)) {
|
||||
return [false, runningTargets] as const;
|
||||
}
|
||||
const next = new Set(runningTargets);
|
||||
next.add(targetKey);
|
||||
return [true, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const releaseTarget = (targetKey: string) =>
|
||||
Ref.update(runningTargetsRef, (runningTargets) => {
|
||||
const next = new Set(runningTargets);
|
||||
next.delete(targetKey);
|
||||
return next;
|
||||
});
|
||||
|
||||
const getLock = Effect.fn("getProviderMaintenanceCommandLock")(function* (lockKey: string) {
|
||||
const existing = (yield* Ref.get(locksRef)).get(lockKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const lock = yield* Semaphore.make(1);
|
||||
return yield* Ref.modify(locksRef, (locks) => {
|
||||
const current = locks.get(lockKey);
|
||||
if (current) {
|
||||
return [current, locks] as const;
|
||||
}
|
||||
const next = new Map(locks);
|
||||
next.set(lockKey, lock);
|
||||
return [lock, next] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] = ({
|
||||
targetKey,
|
||||
lockKey,
|
||||
onQueued,
|
||||
run,
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const acquired = yield* acquireTarget(targetKey);
|
||||
if (!acquired) {
|
||||
return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));
|
||||
}
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const lock = yield* getLock(lockKey);
|
||||
if (onQueued) {
|
||||
yield* onQueued;
|
||||
}
|
||||
return yield* lock.withPermits(1)(run);
|
||||
}).pipe(Effect.ensuring(releaseTarget(targetKey)));
|
||||
});
|
||||
|
||||
return {
|
||||
withCommandLock,
|
||||
} satisfies ProviderMaintenanceCommandCoordinatorShape<E>;
|
||||
});
|
||||
@@ -0,0 +1,640 @@
|
||||
import { afterEach, describe, it, assert } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServerProviderUpdateError } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Exit, Fiber, Layer, Ref, Schema, Sink, Stream } from "effect";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts";
|
||||
import {
|
||||
clearLatestProviderVersionCacheForTests,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
|
||||
const OPENCODE_DRIVER = ProviderDriverKind.make("opencode");
|
||||
const CODEX_INSTANCE_ID = ProviderInstanceId.make("codex");
|
||||
const CURSOR_INSTANCE_ID = ProviderInstanceId.make("cursor");
|
||||
const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode");
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities {
|
||||
if (provider === CURSOR_DRIVER) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: null,
|
||||
updateExecutable: "agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
});
|
||||
}
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
const baseProvider: ServerProvider = {
|
||||
instanceId: CODEX_INSTANCE_ID,
|
||||
driver: CODEX_DRIVER,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const baseCursorProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: CURSOR_INSTANCE_ID,
|
||||
driver: CURSOR_DRIVER,
|
||||
};
|
||||
|
||||
const baseOpenCodeProvider: ServerProvider = {
|
||||
...baseProvider,
|
||||
instanceId: OPENCODE_INSTANCE_ID,
|
||||
driver: OPENCODE_DRIVER,
|
||||
};
|
||||
|
||||
const latestVersionHttpClient = (version: string) =>
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
Effect.succeed(
|
||||
HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ version }, { headers: { "content-type": "application/json" } }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: result.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
function mockSpawnerLayer(
|
||||
handler: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
) => {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
|
||||
},
|
||||
) {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeRegistry(
|
||||
initialProviders: ServerProvider | ReadonlyArray<ServerProvider> = baseProvider,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
Array.isArray(initialProviders) ? initialProviders : [initialProviders],
|
||||
);
|
||||
const updateStatesRef = yield* Ref.make<ReadonlyArray<ServerProviderUpdateState>>([]);
|
||||
|
||||
const setProviderMaintenanceActionState = Effect.fn(
|
||||
"providerMaintenanceRunner.test.setProviderMaintenanceActionState",
|
||||
)(function* (input: {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly action: "update";
|
||||
readonly state: ServerProviderUpdateState | null;
|
||||
}) {
|
||||
const updateState = input.state;
|
||||
if (updateState) {
|
||||
yield* Ref.update(updateStatesRef, (states) => [...states, updateState]);
|
||||
}
|
||||
return yield* Ref.updateAndGet(providersRef, (providers) =>
|
||||
providers.map((candidate) => {
|
||||
if (candidate.instanceId !== input.instanceId) {
|
||||
return candidate;
|
||||
}
|
||||
if (!updateState) {
|
||||
const { updateState: _updateState, ...providerWithoutUpdateState } = candidate;
|
||||
return providerWithoutUpdateState;
|
||||
}
|
||||
return {
|
||||
...candidate,
|
||||
updateState,
|
||||
};
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const registry: ProviderRegistryShape = {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: () => Ref.get(providersRef),
|
||||
refreshInstance: () => Ref.get(providersRef),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(lifecycleFor(provider)),
|
||||
setProviderMaintenanceActionState,
|
||||
streamChanges: Stream.empty,
|
||||
};
|
||||
|
||||
return {
|
||||
registry,
|
||||
updateStatesRef,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const makeTestRunner = (registry: ProviderRegistryShape) =>
|
||||
Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe(
|
||||
Effect.provide(
|
||||
ProviderMaintenanceRunner.layer.pipe(
|
||||
Layer.provide(Layer.succeed(ProviderRegistry, registry)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("providerMaintenanceRunner", () => {
|
||||
it.effect("runs the allowlisted provider update command and records success", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry, updateStatesRef } = yield* makeRegistry(baseCursorProvider);
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CURSOR_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "agent",
|
||||
args: ["update"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(updateStatesRef)).map((state) => state.status),
|
||||
["queued", "running", "succeeded"],
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("uses the resolved provider capabilities when choosing the update executable", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
versionAdvisory: {
|
||||
status: "behind_latest",
|
||||
currentVersion: "2.0.14",
|
||||
latestVersion: "2.1.123",
|
||||
updateCommand: "bun i -g @anthropic-ai/claude-code@latest",
|
||||
canUpdate: true,
|
||||
checkedAt: "2026-04-30T12:00:00.000Z",
|
||||
message: "Update available.",
|
||||
},
|
||||
});
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: () =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: CODEX_DRIVER,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "bun-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "bun",
|
||||
args: ["i", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"runs update commands through Effect ChildProcess when no test runner is injected",
|
||||
() => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const runner = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* runner.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "npm",
|
||||
args: ["install", "-g", "@openai/codex@latest"],
|
||||
},
|
||||
]);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("updates a single provider instance without touching sibling instances", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
const personalInstanceId = ProviderInstanceId.make("codex_personal");
|
||||
const workInstanceId = ProviderInstanceId.make("codex_work");
|
||||
const refreshedInstanceIds: Array<ProviderInstanceId> = [];
|
||||
const { registry } = yield* makeRegistry([
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: personalInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
{
|
||||
...baseProvider,
|
||||
instanceId: workInstanceId,
|
||||
version: "0.124.0-alpha.3",
|
||||
},
|
||||
]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex-instance-test",
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", "@openai/codex"],
|
||||
updateLockKey: "vite-plus-global",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.tap(() => Effect.sync(() => assert.strictEqual(instanceId, personalInstanceId))),
|
||||
),
|
||||
refreshInstance: (instanceId) =>
|
||||
registry.refreshInstance(instanceId).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
refreshedInstanceIds.push(instanceId);
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider({
|
||||
provider: CODEX_DRIVER,
|
||||
instanceId: personalInstanceId,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(calls, [
|
||||
{
|
||||
command: "vp",
|
||||
args: ["i", "-g", "@openai/codex"],
|
||||
},
|
||||
]);
|
||||
assert.deepStrictEqual(refreshedInstanceIds, [personalInstanceId]);
|
||||
assert.strictEqual(result.providers[0]?.instanceId, personalInstanceId);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.strictEqual(result.providers[1]?.instanceId, workInstanceId);
|
||||
assert.strictEqual(result.providers[1]?.updateState, undefined);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.124.0-alpha.3"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("records command failure output in provider update state", () =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
const updateState = result.providers[0]?.updateState;
|
||||
|
||||
assert.strictEqual(updateState?.status, "failed");
|
||||
assert.strictEqual(updateState?.message, "Update command exited with code 1.");
|
||||
assert.include(updateState?.output ?? "", "permission denied");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stderr: "permission denied", code: 1 })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks successful commands as unchanged when the refreshed provider is still outdated",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry({
|
||||
...baseProvider,
|
||||
installed: true,
|
||||
version: "0.1.0",
|
||||
});
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "unchanged");
|
||||
assert.include(result.providers[0]?.updateState?.message ?? "", "still detects");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("9.9.9"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("prevents concurrent updates for the same provider", () => {
|
||||
const startedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const started = new Promise<void>((resolve) => {
|
||||
startedLatch.resolve = resolve;
|
||||
});
|
||||
const release = new Promise<void>((resolve) => {
|
||||
releaseLatch.resolve = resolve;
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry();
|
||||
const updater = yield* makeTestRunner(registry);
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => started);
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isFailure(second), true);
|
||||
if (Exit.isFailure(second)) {
|
||||
const error = Cause.squash(second.cause);
|
||||
assert.strictEqual(Schema.is(ServerProviderUpdateError)(error), true);
|
||||
if (Schema.is(ServerProviderUpdateError)(error)) {
|
||||
assert.include(error.reason, "already running");
|
||||
}
|
||||
}
|
||||
|
||||
releaseLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => {
|
||||
startedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => release).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("serializes different providers that share the same update lock key", () => {
|
||||
const firstStartedLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseFirstLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const firstStarted = new Promise<void>((resolve) => {
|
||||
firstStartedLatch.resolve = resolve;
|
||||
});
|
||||
const releaseFirst = new Promise<void>((resolve) => {
|
||||
releaseFirstLatch.resolve = resolve;
|
||||
});
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry([baseProvider, baseOpenCodeProvider]);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs:
|
||||
provider === OPENCODE_DRIVER
|
||||
? ["install", "-g", "opencode-ai@latest"]
|
||||
: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "npm-global",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => firstStarted);
|
||||
|
||||
const second = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped);
|
||||
let providersWhileQueued: ReadonlyArray<ServerProvider> = [];
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
providersWhileQueued = yield* registry.getProviders;
|
||||
const queuedStatus = providersWhileQueued.find(
|
||||
(provider) => provider.instanceId === OPENCODE_INSTANCE_ID,
|
||||
)?.updateState?.status;
|
||||
if (queuedStatus === "queued") {
|
||||
break;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
assert.strictEqual(
|
||||
providersWhileQueued.find((provider) => provider.instanceId === OPENCODE_INSTANCE_ID)
|
||||
?.updateState?.status,
|
||||
"queued",
|
||||
);
|
||||
|
||||
releaseFirstLatch.resolve();
|
||||
yield* Fiber.join(first);
|
||||
yield* Fiber.join(second);
|
||||
assert.deepStrictEqual(calls, [
|
||||
"install -g @openai/codex@latest",
|
||||
"install -g opencode-ai@latest",
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
if (calls.length === 1) {
|
||||
firstStartedLatch.resolve();
|
||||
return {
|
||||
stdout: "updated",
|
||||
exitCode: Effect.promise(() => releaseFirst).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts arbitrary driver-provided update lock keys", () => {
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: "npm",
|
||||
updateArgs: ["install", "-g", "@openai/codex@latest"],
|
||||
updateLockKey: "unknown-lock-key",
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, args) => {
|
||||
calls.push(args.join(" "));
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"releases the running-provider marker when interrupted after queuing but before the lock run starts",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
let blockQueuedState = true;
|
||||
const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} };
|
||||
const queuedStateWritten = new Promise<void>((resolve) => {
|
||||
queuedStateWrittenLatch.resolve = resolve;
|
||||
});
|
||||
const releaseQueuedState = new Promise<void>((resolve) => {
|
||||
releaseQueuedStateLatch.resolve = resolve;
|
||||
});
|
||||
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
setProviderMaintenanceActionState: Effect.fn(
|
||||
"providerMaintenanceRunner.test.blockQueuedState",
|
||||
)(function* (input) {
|
||||
const providers = yield* registry.setProviderMaintenanceActionState(input);
|
||||
if (input.state?.status === "queued" && blockQueuedState) {
|
||||
queuedStateWrittenLatch.resolve();
|
||||
yield* Effect.promise(() => releaseQueuedState);
|
||||
}
|
||||
return providers;
|
||||
}),
|
||||
});
|
||||
|
||||
const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped);
|
||||
yield* Effect.promise(() => queuedStateWritten);
|
||||
blockQueuedState = false;
|
||||
|
||||
yield* Fiber.interrupt(first);
|
||||
releaseQueuedStateLatch.resolve();
|
||||
|
||||
const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit);
|
||||
assert.strictEqual(Exit.isSuccess(second), true);
|
||||
if (Exit.isSuccess(second)) {
|
||||
assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,395 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind,
|
||||
ServerProviderUpdateError,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
type ServerProviderUpdatedPayload,
|
||||
type ServerProviderUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Context, DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
|
||||
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
|
||||
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
const UPDATE_TIMEOUT_MS = 5 * 60_000;
|
||||
const UPDATE_OUTPUT_MAX_BYTES = 10_000;
|
||||
|
||||
export interface ProviderMaintenanceCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number | null;
|
||||
readonly timedOut: boolean;
|
||||
readonly stdoutTruncated: boolean;
|
||||
readonly stderrTruncated: boolean;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceRunnerShape {
|
||||
readonly updateProvider: (
|
||||
target:
|
||||
| ProviderDriverKind
|
||||
| {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly instanceId?: ProviderInstanceId | undefined;
|
||||
},
|
||||
) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
|
||||
}
|
||||
|
||||
export class ProviderMaintenanceRunner extends Context.Service<
|
||||
ProviderMaintenanceRunner,
|
||||
ProviderMaintenanceRunnerShape
|
||||
>()("t3/provider/ProviderMaintenanceRunner") {}
|
||||
|
||||
interface VerifiedProviderRefresh {
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
readonly verifiedProviders: ReadonlyArray<ServerProvider>;
|
||||
}
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
|
||||
function* (input: {
|
||||
readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
|
||||
function* () {
|
||||
const child = yield* input.spawner
|
||||
.spawn(ChildProcess.make(input.command, [...input.args]))
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(`Failed to run update command ${input.command}: ${cause.message}`),
|
||||
),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: UPDATE_OUTPUT_MAX_BYTES,
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new Error(cause instanceof Error ? cause.message : "Update command failed to run."),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
exitCode: Number(exitCode),
|
||||
timedOut: false,
|
||||
stdoutTruncated: stdout.truncated,
|
||||
stderrTruncated: stderr.truncated,
|
||||
} satisfies ProviderMaintenanceCommandResult;
|
||||
},
|
||||
);
|
||||
|
||||
return yield* collectCommandResult().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),
|
||||
Effect.map((result) =>
|
||||
Option.match(result, {
|
||||
onSome: (value) => value,
|
||||
onNone: () =>
|
||||
({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: null,
|
||||
timedOut: true,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}) satisfies ProviderMaintenanceCommandResult,
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
function trimNullable(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function truncateText(value: string, maxLength: number): string {
|
||||
return value.length <= maxLength ? value : value.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
|
||||
const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
|
||||
if (!output) {
|
||||
return null;
|
||||
}
|
||||
return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
|
||||
}
|
||||
|
||||
function failureMessage(result: ProviderMaintenanceCommandResult): string {
|
||||
if (result.timedOut) {
|
||||
return "Update timed out.";
|
||||
}
|
||||
if (result.exitCode !== null && result.exitCode !== 0) {
|
||||
return `Update command exited with code ${result.exitCode}.`;
|
||||
}
|
||||
return "Update command failed.";
|
||||
}
|
||||
|
||||
function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
|
||||
return provider?.versionAdvisory?.status === "behind_latest";
|
||||
}
|
||||
|
||||
function makeUpdateState(input: {
|
||||
readonly status: ServerProviderUpdateState["status"];
|
||||
readonly startedAt: string | null;
|
||||
readonly finishedAt: string | null;
|
||||
readonly message: string | null;
|
||||
readonly output?: string | null;
|
||||
}): ServerProviderUpdateState {
|
||||
return {
|
||||
status: input.status,
|
||||
startedAt: input.startedAt,
|
||||
finishedAt: input.finishedAt,
|
||||
message: input.message,
|
||||
output: input.output ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
|
||||
runProviderMaintenanceCommandWithSpawner({
|
||||
spawner,
|
||||
command,
|
||||
args,
|
||||
});
|
||||
const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
|
||||
makeAlreadyRunningError: () =>
|
||||
new ServerProviderUpdateError({
|
||||
provider: ProviderDriverKind.make("unknown"),
|
||||
reason: "An update is already running for this provider.",
|
||||
}),
|
||||
});
|
||||
|
||||
const verifyRefreshedProvider = (
|
||||
provider: ProviderDriverKind,
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<VerifiedProviderRefresh> =>
|
||||
providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) =>
|
||||
providers
|
||||
.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
)
|
||||
.map((candidate) => candidate.instanceId),
|
||||
),
|
||||
Effect.flatMap((instanceIds) =>
|
||||
instanceIds.length === 0
|
||||
? providerRegistry.refreshInstance(instanceId)
|
||||
: Effect.forEach(
|
||||
instanceIds,
|
||||
(instanceId) => providerRegistry.refreshInstance(instanceId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(providerRegistry.getProviders)),
|
||||
),
|
||||
Effect.flatMap((providers) => {
|
||||
const refreshedProviders = providers.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
);
|
||||
if (refreshedProviders.length === 0) {
|
||||
return Effect.succeed<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: [],
|
||||
});
|
||||
}
|
||||
return Effect.forEach(
|
||||
refreshedProviders,
|
||||
(refreshedProvider) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(
|
||||
refreshedProvider,
|
||||
maintenanceCapabilities,
|
||||
).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(
|
||||
Effect.map(
|
||||
(verifiedProviders): VerifiedProviderRefresh => ({
|
||||
providers,
|
||||
verifiedProviders,
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Provider post-update version verification failed", {
|
||||
provider,
|
||||
cause: Cause.pretty(cause),
|
||||
}).pipe(
|
||||
Effect.as<VerifiedProviderRefresh>({
|
||||
providers,
|
||||
verifiedProviders: refreshedProviders,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
|
||||
"ProviderMaintenanceRunner.updateProvider",
|
||||
)(function* (target) {
|
||||
const provider = typeof target === "string" ? target : target.provider;
|
||||
const instanceId =
|
||||
typeof target === "string"
|
||||
? defaultInstanceIdForDriver(provider)
|
||||
: (target.instanceId ?? defaultInstanceIdForDriver(provider));
|
||||
const targetKey = `instance:${instanceId}`;
|
||||
const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
|
||||
instanceId,
|
||||
provider,
|
||||
);
|
||||
const update = capabilities.update;
|
||||
if (!update) {
|
||||
return yield* new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: "This provider does not support one-click updates.",
|
||||
});
|
||||
}
|
||||
|
||||
const setUpdateState = (state: ServerProviderUpdateState | null) =>
|
||||
providerRegistry.setProviderMaintenanceActionState({
|
||||
instanceId,
|
||||
action: "update",
|
||||
state,
|
||||
});
|
||||
const setQueuedState = setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
message: "Waiting for another provider update to finish.",
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
|
||||
function* () {
|
||||
const finish = (state: ServerProviderUpdateState) =>
|
||||
setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));
|
||||
const startedAtRef = yield* Ref.make<string | null>(null);
|
||||
|
||||
const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
|
||||
function* () {
|
||||
const startedAt = yield* nowIso;
|
||||
yield* Ref.set(startedAtRef, startedAt);
|
||||
yield* setUpdateState(
|
||||
makeUpdateState({
|
||||
status: "running",
|
||||
startedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* runMaintenanceCommand(update.executable, update.args);
|
||||
const finishedAt = yield* nowIso;
|
||||
if (result.timedOut || result.exitCode !== 0) {
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: failureMessage(result),
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const { verifiedProviders } = yield* verifyRefreshedProvider(
|
||||
provider,
|
||||
capabilities,
|
||||
instanceId,
|
||||
);
|
||||
const couldNotVerify = verifiedProviders.length === 0;
|
||||
const stillOutdated =
|
||||
couldNotVerify ||
|
||||
verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: stillOutdated ? "unchanged" : "succeeded",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: couldNotVerify
|
||||
? "Update command completed, but T3 Code could not verify the provider version."
|
||||
: stillOutdated
|
||||
? "Update command completed, but T3 Code still detects an outdated provider version."
|
||||
: "Provider updated.",
|
||||
output: commandOutput(result),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
|
||||
function* (cause: Cause.Cause<unknown>) {
|
||||
const failure = Cause.squash(cause);
|
||||
const startedAt = yield* Ref.get(startedAtRef);
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt: yield* nowIso,
|
||||
message: failure instanceof Error ? failure.message : "Update command failed.",
|
||||
output: null,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
|
||||
},
|
||||
);
|
||||
|
||||
return yield* commandCoordinator
|
||||
.withCommandLock({
|
||||
targetKey,
|
||||
lockKey: update.lockKey,
|
||||
onQueued: setQueuedState,
|
||||
run: runProviderUpdate(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(ServerProviderUpdateError)(error)
|
||||
? new ServerProviderUpdateError({
|
||||
provider,
|
||||
reason: error.reason,
|
||||
})
|
||||
: error,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return ProviderMaintenanceRunner.of({
|
||||
updateProvider,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProviderMaintenanceRunner, make());
|
||||
@@ -12,6 +12,8 @@ import { Effect, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)
|
||||
@@ -182,6 +184,7 @@ export function buildBooleanOptionDescriptor(input: {
|
||||
}
|
||||
|
||||
export function buildServerProvider(input: {
|
||||
driver?: ProviderDriverKind;
|
||||
presentation: ServerProviderPresentation;
|
||||
enabled: boolean;
|
||||
checkedAt: string;
|
||||
@@ -190,6 +193,13 @@ export function buildServerProvider(input: {
|
||||
skills?: ReadonlyArray<ServerProviderSkill>;
|
||||
probe: ProviderProbeResult;
|
||||
}): ServerProviderDraft {
|
||||
const versionAdvisory = input.driver
|
||||
? createProviderVersionAdvisory({
|
||||
driver: input.driver,
|
||||
currentVersion: input.probe.version,
|
||||
checkedAt: input.checkedAt,
|
||||
})
|
||||
: undefined;
|
||||
return {
|
||||
displayName: input.presentation.displayName,
|
||||
...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
|
||||
@@ -206,16 +216,11 @@ export function buildServerProvider(input: {
|
||||
models: input.models,
|
||||
slashCommands: [...(input.slashCommands ?? [])],
|
||||
skills: [...(input.skills ?? [])],
|
||||
...(versionAdvisory ? { versionAdvisory } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const collectStreamAsString = <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, E> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
);
|
||||
collectUint8StreamText({ stream }).pipe(Effect.map((collected) => collected.text));
|
||||
@@ -140,8 +140,10 @@ export const readProviderStatusCache = (filePath: string) =>
|
||||
export const writeProviderStatusCache = (input: {
|
||||
readonly filePath: string;
|
||||
readonly provider: ServerProvider;
|
||||
}) =>
|
||||
writeFileStringAtomically({
|
||||
}) => {
|
||||
const { updateState: _updateState, ...cacheableProvider } = input.provider;
|
||||
return writeFileStringAtomically({
|
||||
filePath: input.filePath,
|
||||
contents: `${JSON.stringify(input.provider, null, 2)}\n`,
|
||||
contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
|
||||
});
|
||||
};
|
||||
@@ -80,6 +80,7 @@ import {
|
||||
ProviderRegistry,
|
||||
type ProviderRegistryShape,
|
||||
} from "./provider/Services/ProviderRegistry.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
|
||||
@@ -114,6 +115,8 @@ import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
|
||||
const defaultProjectId = ProjectId.make("project-default");
|
||||
const defaultThreadId = ThreadId.make("thread-default");
|
||||
@@ -527,6 +530,12 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.mock(ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
refresh: () => Effect.succeed([]),
|
||||
refreshInstance: () => Effect.succeed([]),
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }),
|
||||
),
|
||||
setProviderMaintenanceActionState: () => Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
...options?.layers?.providerRegistry,
|
||||
}),
|
||||
@@ -546,6 +555,52 @@ const buildAppUnderTest = (options?: {
|
||||
...options?.layers?.open,
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({
|
||||
read: Effect.succeed({
|
||||
serverPid: process.pid,
|
||||
readAt: TEST_EPOCH,
|
||||
processCount: 0,
|
||||
totalRssBytes: 0,
|
||||
totalCpuPercent: 0,
|
||||
processes: [],
|
||||
error: Option.none(),
|
||||
}),
|
||||
signal: (input) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(TraceDiagnostics.TraceDiagnostics)({
|
||||
read: () =>
|
||||
Effect.succeed({
|
||||
traceFilePath: "",
|
||||
scannedFilePaths: [],
|
||||
readAt: TEST_EPOCH,
|
||||
recordCount: 0,
|
||||
parseErrorCount: 0,
|
||||
firstSpanAt: Option.none(),
|
||||
lastSpanAt: Option.none(),
|
||||
failureCount: 0,
|
||||
interruptionCount: 0,
|
||||
slowSpanThresholdMs: 1_000,
|
||||
slowSpanCount: 0,
|
||||
logLevelCounts: {},
|
||||
topSpansByCount: [],
|
||||
slowestSpans: [],
|
||||
commonFailures: [],
|
||||
latestFailures: [],
|
||||
latestWarningAndErrorLogs: [],
|
||||
partialFailure: Option.none(),
|
||||
error: Option.none(),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provide(gitManagerLayer),
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
@@ -1922,6 +1977,42 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc server.removeKeybinding", () =>
|
||||
Effect.gen(function* () {
|
||||
const rule: KeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
key: "ctrl+k",
|
||||
};
|
||||
const resolved: ResolvedKeybindingRule = {
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
};
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
keybindings: {
|
||||
removeKeybindingRule: () => Effect.succeed([resolved]),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const response = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverRemoveKeybinding](rule)),
|
||||
);
|
||||
|
||||
assert.deepEqual(response.issues, []);
|
||||
assert.deepEqual(response.keybindings, [resolved]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -75,6 +75,8 @@ import {
|
||||
} from "./auth/http.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
@@ -283,6 +285,8 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
|
||||
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
|
||||
// Misc.
|
||||
Layer.provideMerge(ProcessDiagnostics.layer),
|
||||
Layer.provideMerge(TraceDiagnostics.layer),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(ServerLifecycleEventsLive),
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
|
||||
import { collectUint8StreamText } from "./collectUint8StreamText.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
describe("collectUint8StreamText", () => {
|
||||
it.effect("collects Uint8Array chunks into decoded text", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* collectUint8StreamText({
|
||||
stream: Stream.make(encoder.encode("hello "), encoder.encode("world")),
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
text: "hello world",
|
||||
bytes: 11,
|
||||
truncated: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("truncates by bytes and appends an optional marker once", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* collectUint8StreamText({
|
||||
stream: Stream.make(encoder.encode("abcdef"), encoder.encode("ghij")),
|
||||
maxBytes: 5,
|
||||
truncatedMarker: "[truncated]",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
text: "abcde[truncated]",
|
||||
bytes: 5,
|
||||
truncated: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Effect, Stream } from "effect";
|
||||
|
||||
export interface CollectedUint8StreamText {
|
||||
readonly text: string;
|
||||
readonly truncated: boolean;
|
||||
readonly bytes: number;
|
||||
}
|
||||
|
||||
interface CollectState {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
export const collectUint8StreamText = <E>(input: {
|
||||
readonly stream: Stream.Stream<Uint8Array, E>;
|
||||
readonly maxBytes?: number | undefined;
|
||||
readonly truncatedMarker?: string | null | undefined;
|
||||
}): Effect.Effect<CollectedUint8StreamText, E> => {
|
||||
const decoder = new TextDecoder();
|
||||
const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
|
||||
const truncatedMarker = input.truncatedMarker ?? "";
|
||||
|
||||
return input.stream.pipe(
|
||||
Stream.runFold(
|
||||
(): CollectState => ({
|
||||
text: "",
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}),
|
||||
(state, chunk): CollectState => {
|
||||
if (state.truncated) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const remainingBytes = maxBytes - state.bytes;
|
||||
if (remainingBytes <= 0) {
|
||||
return {
|
||||
...state,
|
||||
text: `${state.text}${truncatedMarker}`,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
const nextChunk =
|
||||
chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
const text = `${state.text}${decoder.decode(nextChunk, { stream: true })}`;
|
||||
const bytes = state.bytes + nextChunk.byteLength;
|
||||
const truncated = chunk.byteLength > remainingBytes;
|
||||
|
||||
return {
|
||||
text: truncated ? `${text}${truncatedMarker}` : text,
|
||||
bytes,
|
||||
truncated,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map(
|
||||
(state): CollectedUint8StreamText => ({
|
||||
text: state.truncated ? state.text : `${state.text}${decoder.decode()}`,
|
||||
bytes: state.bytes,
|
||||
truncated: state.truncated,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -243,9 +243,7 @@ const createManager = (
|
||||
...(options.subprocessPollIntervalMs !== undefined
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
: {}),
|
||||
...(options.processKillGraceMs !== undefined
|
||||
? { processKillGraceMs: options.processKillGraceMs }
|
||||
: {}),
|
||||
processKillGraceMs: options.processKillGraceMs ?? 1,
|
||||
...(options.maxRetainedInactiveSessions !== undefined
|
||||
? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions }
|
||||
: {}),
|
||||
|
||||
@@ -552,7 +552,7 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
|
||||
};
|
||||
});
|
||||
|
||||
const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
const collectOutput = Effect.fnUntraced(function* <E>(
|
||||
input: Pick<GitVcsDriver.ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
@@ -565,7 +565,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
let lineBuffer = "";
|
||||
let truncated = false;
|
||||
|
||||
const emitCompleteLines = Effect.fn("emitCompleteLines")(function* (flush: boolean) {
|
||||
const emitCompleteLines = Effect.fnUntraced(function* (flush: boolean) {
|
||||
let newlineIndex = lineBuffer.indexOf("\n");
|
||||
while (newlineIndex >= 0) {
|
||||
const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
|
||||
@@ -585,7 +585,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
}
|
||||
});
|
||||
|
||||
const processChunk = Effect.fn("processChunk")(function* (chunk: Uint8Array) {
|
||||
const processChunk = Effect.fnUntraced(function* (chunk: Uint8Array) {
|
||||
if (truncateOutputAtMaxBytes && truncated) {
|
||||
return;
|
||||
}
|
||||
@@ -626,20 +626,14 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
|
||||
};
|
||||
});
|
||||
|
||||
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (options?: {
|
||||
executeOverride?: GitVcsDriver.GitVcsDriverShape["execute"];
|
||||
}) {
|
||||
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const { worktreesDir } = yield* ServerConfig;
|
||||
|
||||
let executeRaw: GitVcsDriver.GitVcsDriverShape["execute"];
|
||||
|
||||
if (options?.executeOverride) {
|
||||
executeRaw = options.executeOverride;
|
||||
} else {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
executeRaw = Effect.fnUntraced(function* (input) {
|
||||
const executeRaw: GitVcsDriver.GitVcsDriverShape["execute"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
args: [...input.args],
|
||||
@@ -736,8 +730,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const execute: GitVcsDriver.GitVcsDriverShape["execute"] = (input) =>
|
||||
executeRaw(input).pipe(
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
export interface VcsProcessInput {
|
||||
readonly operation: string;
|
||||
@@ -86,44 +87,12 @@ export const collectText = Effect.fn("VcsProcess.collectText")(function* (input:
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) {
|
||||
const decoder = new TextDecoder();
|
||||
let text = "";
|
||||
let bytes = 0;
|
||||
let truncated = false;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false;
|
||||
|
||||
yield* Stream.runForEach(input.stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
if (truncated) return;
|
||||
|
||||
const remainingBytes = maxOutputBytes - bytes;
|
||||
if (remainingBytes <= 0) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const nextChunk = chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
|
||||
text += decoder.decode(nextChunk, { stream: true });
|
||||
bytes += nextChunk.byteLength;
|
||||
|
||||
if (chunk.byteLength > remainingBytes) {
|
||||
truncated = true;
|
||||
if (truncateOutputAtMaxBytes) {
|
||||
text += OUTPUT_TRUNCATED_MARKER;
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (!truncated) {
|
||||
text += decoder.decode();
|
||||
}
|
||||
|
||||
return { text, truncated } satisfies VcsProcessCollectedText;
|
||||
return yield* collectUint8StreamText({
|
||||
stream: input.stream,
|
||||
maxBytes: maxOutputBytes,
|
||||
truncatedMarker: input.truncateOutputAtMaxBytes ? OUTPUT_TRUNCATED_MARKER : null,
|
||||
});
|
||||
});
|
||||
|
||||
export const make = Effect.fn("makeVcsProcess")(function* () {
|
||||
|
||||
+43
-5
@@ -43,6 +43,7 @@ import {
|
||||
observeRpcStreamEffect,
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";
|
||||
import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";
|
||||
import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts";
|
||||
@@ -58,6 +59,8 @@ import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptR
|
||||
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
|
||||
import * as SourceControlDiscoveryLayer from "./sourceControl/SourceControlDiscovery.ts";
|
||||
import { SourceControlRepositoryService } from "./sourceControl/SourceControlRepositoryService.ts";
|
||||
import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
|
||||
@@ -157,6 +160,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const config = yield* ServerConfig;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
@@ -171,6 +175,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const sourceControlRepositories = yield* SourceControlRepositoryService;
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
const serverCommandId = (tag: string) =>
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
@@ -790,6 +795,14 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
).pipe(Effect.map((providers) => ({ providers }))),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverUpdateProvider]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpdateProvider,
|
||||
providerMaintenanceRunner.updateProvider(input),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverUpsertKeybinding,
|
||||
@@ -799,6 +812,15 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverRemoveKeybinding]: (rule) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverRemoveKeybinding,
|
||||
Effect.gen(function* () {
|
||||
const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
|
||||
return { keybindings: keybindingsConfig, issues: [] };
|
||||
}),
|
||||
{ "rpc.aggregate": "server" },
|
||||
),
|
||||
[WS_METHODS.serverGetSettings]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetSettings,
|
||||
@@ -823,6 +845,25 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverGetTraceDiagnostics]: (_input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.serverGetTraceDiagnostics,
|
||||
TraceDiagnostics.readTraceDiagnostics({
|
||||
traceFilePath: config.serverTracePath,
|
||||
maxFiles: config.traceMaxFiles,
|
||||
}),
|
||||
{
|
||||
"rpc.aggregate": "server",
|
||||
},
|
||||
),
|
||||
[WS_METHODS.serverGetProcessDiagnostics]: (_input) =>
|
||||
observeRpcEffect(WS_METHODS.serverGetProcessDiagnostics, processDiagnostics.read, {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.serverSignalProcess]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), {
|
||||
"rpc.aggregate": "server",
|
||||
}),
|
||||
[WS_METHODS.sourceControlLookupRepository]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.sourceControlLookupRepository,
|
||||
@@ -1174,15 +1215,12 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const session = yield* serverAuth.authenticateWebSocketUpgrade(request);
|
||||
const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {
|
||||
spanPrefix: "ws.rpc",
|
||||
spanAttributes: {
|
||||
"rpc.transport": "websocket",
|
||||
"rpc.system": "effect-rpc",
|
||||
},
|
||||
disableTracing: true,
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeWsRpcLayer(session.sessionId).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(
|
||||
SourceControlDiscoveryLayer.layer.pipe(
|
||||
Layer.provide(
|
||||
|
||||
@@ -65,7 +65,7 @@ describe("ChatMarkdown", () => {
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "PermissionRule.ts · L1" });
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}#L1`);
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}:1`);
|
||||
|
||||
await link.click();
|
||||
|
||||
@@ -87,7 +87,7 @@ describe("ChatMarkdown", () => {
|
||||
try {
|
||||
const link = page.getByRole("link", { name: "PermissionRule.ts · L1:C7" });
|
||||
await expect.element(link).toBeInTheDocument();
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}#L1C7`);
|
||||
await expect.element(link).toHaveAttribute("href", `${filePath}:1:7`);
|
||||
|
||||
await link.click();
|
||||
|
||||
|
||||
@@ -26,7 +26,11 @@ import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref } from "../markdown-links";
|
||||
import {
|
||||
normalizeMarkdownLinkDestination,
|
||||
resolveMarkdownFileLinkMeta,
|
||||
rewriteMarkdownFileUriHref,
|
||||
} from "../markdown-links";
|
||||
import { readLocalApi } from "../localApi";
|
||||
import { cn } from "../lib/utils";
|
||||
|
||||
@@ -354,7 +358,8 @@ function extractMarkdownLinkHrefs(text: string): string[] {
|
||||
}
|
||||
|
||||
function normalizeMarkdownLinkHrefKey(href: string): string {
|
||||
return rewriteMarkdownFileUriHref(href.trim()) ?? href.trim();
|
||||
const normalizedHref = normalizeMarkdownLinkDestination(href);
|
||||
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
|
||||
}
|
||||
|
||||
const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
@@ -549,7 +554,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
|
||||
return (
|
||||
<MarkdownFileLink
|
||||
href={href ?? fileLinkMeta.targetPath}
|
||||
href={fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
filePath={fileLinkMeta.filePath}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type SVGProps, useId } from "react";
|
||||
import React, { type SVGProps, useId } from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||
@@ -635,107 +635,6 @@ export const AntigravityIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const IntelliJIdeaIcon: Icon = (props) => {
|
||||
const id = useId();
|
||||
const gradientAId = `${id}-idea-a`;
|
||||
const gradientBId = `${id}-idea-b`;
|
||||
const gradientCId = `${id}-idea-c`;
|
||||
const gradientDId = `${id}-idea-d`;
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 70 70" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="0.7898"
|
||||
y1="40.0893"
|
||||
x2="33.3172"
|
||||
y2="40.0893"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset="0.2581" stopColor="#F97A12" />
|
||||
<stop offset="0.4591" stopColor="#B07B58" />
|
||||
<stop offset="0.7241" stopColor="#577BAE" />
|
||||
<stop offset="0.9105" stopColor="#1E7CE5" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="25.7674"
|
||||
y1="24.88"
|
||||
x2="79.424"
|
||||
y2="54.57"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#F97A12" />
|
||||
<stop offset="0.07179946" stopColor="#CB7A3E" />
|
||||
<stop offset="0.1541" stopColor="#9E7B6A" />
|
||||
<stop offset="0.242" stopColor="#757B91" />
|
||||
<stop offset="0.3344" stopColor="#537BB1" />
|
||||
<stop offset="0.4324" stopColor="#387CCC" />
|
||||
<stop offset="0.5381" stopColor="#237CE0" />
|
||||
<stop offset="0.6552" stopColor="#147CEF" />
|
||||
<stop offset="0.7925" stopColor="#0B7CF7" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientCId}
|
||||
x1="63.2277"
|
||||
y1="42.9153"
|
||||
x2="48.2903"
|
||||
y2="-1.7191"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#FE315D" />
|
||||
<stop offset="0.07840246" stopColor="#CB417E" />
|
||||
<stop offset="0.1601" stopColor="#9E4E9B" />
|
||||
<stop offset="0.2474" stopColor="#755BB4" />
|
||||
<stop offset="0.3392" stopColor="#5365CA" />
|
||||
<stop offset="0.4365" stopColor="#386DDB" />
|
||||
<stop offset="0.5414" stopColor="#2374E9" />
|
||||
<stop offset="0.6576" stopColor="#1478F3" />
|
||||
<stop offset="0.794" stopColor="#0B7BF8" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientDId}
|
||||
x1="10.7204"
|
||||
y1="16.473"
|
||||
x2="55.5237"
|
||||
y2="90.58"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop stopColor="#FE315D" />
|
||||
<stop offset="0.04023279" stopColor="#F63462" />
|
||||
<stop offset="0.1037" stopColor="#DF3A71" />
|
||||
<stop offset="0.1667" stopColor="#C24383" />
|
||||
<stop offset="0.2912" stopColor="#AD4A91" />
|
||||
<stop offset="0.5498" stopColor="#755BB4" />
|
||||
<stop offset="0.9175" stopColor="#1D76ED" />
|
||||
<stop offset="1" stopColor="#087CFA" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<polygon points="17.7,54.6 0.8,41.2 9.2,25.6 33.3,35" fill={`url(#${gradientAId})`} />
|
||||
<path
|
||||
d="M70 18.7 68.7 59.2 41.8 70 25.6 59.6 49.3 35 38.9 12.3 48.2 1.1Z"
|
||||
fill={`url(#${gradientBId})`}
|
||||
/>
|
||||
<polygon points="70,18.7 48.7,43.9 38.9,12.3 48.2,1.1" fill={`url(#${gradientCId})`} />
|
||||
<path
|
||||
d="M33.7 58.1 5.6 68.3 10.1 52.5 16 33.1 0 27.7 10.1 0 32.1 2.7 53.7 27.4Z"
|
||||
fill={`url(#${gradientDId})`}
|
||||
/>
|
||||
<rect x="13.7" y="13.5" width="43.2" height="43.2" fill="#000" />
|
||||
<rect x="17.7" y="48.6" width="16.2" height="2.7" fill="#fff" />
|
||||
<path d="M29.4 22.4v-3.3h-9v3.3h2.6v11.3h-2.6V37h9v-3.3h-2.5V22.4h2.5Z" fill="#fff" />
|
||||
<path
|
||||
d="M38 37.3c-1.4 0-2.6-.3-3.5-.8-.9-.5-1.7-1.2-2.3-1.9l2.5-2.8c.5.6 1 1 1.5 1.3.5.3 1.1.5 1.7.5.7 0 1.3-.2 1.8-.7.4-.5.6-1.2.6-2.3V19.1h4v11.7c0 1.1-.1 2-.4 2.8-.3.8-.7 1.4-1.3 2-.5.5-1.2 1-2 1.2-.8.3-1.6.5-2.6.5Z"
|
||||
fill="#fff"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const OpenCodeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clipPath="url(#opencode__clip0_1311_94969)">
|
||||
|
||||
@@ -0,0 +1,610 @@
|
||||
import { useId } from "react";
|
||||
import type { Icon } from "./Icons";
|
||||
|
||||
const useSvgGradientIds = (prefix: string, count: number) => {
|
||||
const id = useId();
|
||||
return Array.from(
|
||||
{ length: count },
|
||||
(_, index) => `${id}-${prefix}-${String.fromCharCode(97 + index)}`,
|
||||
);
|
||||
};
|
||||
|
||||
export const AquaIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("aqua", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="59.932"
|
||||
x2="1.336"
|
||||
y1="59.676"
|
||||
y2="1.079"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".25" stopColor="#7256FF" />
|
||||
<stop offset=".73" stopColor="#007DFE" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="7.671"
|
||||
x2="61.125"
|
||||
y1="64.392"
|
||||
y2="39.609"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".3" stopColor="#00D886" />
|
||||
<stop offset=".54" stopColor="#7256FF" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M0 4.125v34.128c0 1.658.993 3.154 2.52 3.8L39.943 57.85c.518.219 1.075.33 1.638.324l18.329-.15A4.125 4.125 0 0 0 64 53.9V36.234c0-.806-.236-1.593-.678-2.267L42.213 1.86A4.13 4.13 0 0 0 38.766 0H4.125A4.125 4.125 0 0 0 0 4.125"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M6 49.015v10.862a4.125 4.125 0 0 0 4.125 4.125h12.566q.3 0 .598-.044l37.185-5.448A4.125 4.125 0 0 0 64 54.429V39.03a4.125 4.125 0 0 0-4.127-4.125l-18.504.005c-.426 0-.849.066-1.254.195L8.871 45.085A4.13 4.13 0 0 0 6 49.015z"
|
||||
/>
|
||||
<path
|
||||
fill="#00D886"
|
||||
d="M6 47.55v12.259a4.125 4.125 0 0 0 4.19 4.124L21 64c1.181-.019 2.531-.786 3.3-1.683l32.707-38.158c.64-.748.993-1.7.993-2.685V10.125A4.125 4.125 0 0 0 53.875 6H42.872c-1.19 0-2.321.514-3.105 1.409L7.021 44.834A4.12 4.12 0 0 0 6 47.55"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM20.746 31.243a7.3 7.3 0 0 1-2.755-2.787q-1.002-1.774-1.003-3.961c0-2.187.334-2.778 1.003-3.96a7.3 7.3 0 0 1 2.755-2.787q1.752-1.013 3.917-1.014c1.443 0 2.739.338 3.907 1.013a7.3 7.3 0 0 1 2.75 2.787q.996 1.774.996 3.961c0 2.187-.332 2.778-.997 3.96a7.3 7.3 0 0 1-2.749 2.788q-1.752 1.013-3.907 1.013c-1.436 0-2.75-.338-3.917-1.013m6.308-2.23q1.06-.67 1.661-1.854.6-1.185.6-2.664t-.6-2.664a4.6 4.6 0 0 0-1.661-1.854q-1.061-.67-2.39-.67t-2.396.67a4.6 4.6 0 0 0-1.672 1.854q-.605 1.185-.605 2.664t.605 2.664 1.672 1.854q1.067.67 2.396.67 1.33 0 2.39-.67m-2.16 6.034a2.67 2.67 0 0 1-1.126-1.077q-.391-.696-.391-1.64l-.01-1.94h2.743v1.811q0 .332.129.573.128.242.37.365.24.123.574.123h1.833v2.165h-2.412q-.975 0-1.71-.38M38.233 16.992h3.173l5.563 15.006h-2.947l-1.212-3.483h-5.842l-1.136 3.483H32.82zm3.805 9.261-2.025-5.723-.225-.954-.215.954-1.908 5.723z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const CLionIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("clion", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="4.067"
|
||||
x2="62.664"
|
||||
y1="4.327"
|
||||
y2="62.923"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".29" stopColor="#009AE5" />
|
||||
<stop offset=".7" stopColor="#00D980" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="56.329"
|
||||
x2="2.874"
|
||||
y1="-.391"
|
||||
y2="24.393"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".3" stopColor="#FF2D90" />
|
||||
<stop offset=".54" stopColor="#009AE5" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M64 59.878V25.75a4.13 4.13 0 0 0-2.52-3.8L24.057 6.153a4.1 4.1 0 0 0-1.638-.325l-18.329.15A4.124 4.124 0 0 0 0 10.103v17.665c0 .806.236 1.593.678 2.267l21.109 32.109a4.12 4.12 0 0 0 3.447 1.859h34.641A4.125 4.125 0 0 0 64 59.878"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M58 14.988V4.125A4.125 4.125 0 0 0 53.875 0H41.309q-.3 0-.598.044L3.527 5.492A4.125 4.125 0 0 0 0 9.573v15.398a4.125 4.125 0 0 0 4.126 4.125l18.505-.005c.425 0 .848-.066 1.253-.195l31.246-9.98A4.13 4.13 0 0 0 58 14.988"
|
||||
/>
|
||||
<path
|
||||
fill="#FF2D90"
|
||||
d="M58 16.453V4.194A4.125 4.125 0 0 0 53.81.07L43.003.008c-1.18.019-2.535.781-3.304 1.678L6.993 39.844c-.64.748-.993 1.7-.993 2.684v11.35a4.125 4.125 0 0 0 4.125 4.125h11.003c1.19 0 2.321-.514 3.105-1.409L56.979 19.17A4.12 4.12 0 0 0 58 16.453"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM20.747 31.243a7.3 7.3 0 0 1-2.744-2.787q-.997-1.774-.997-3.961c0-2.187.332-2.778.997-3.96a7.3 7.3 0 0 1 2.744-2.787q1.747-1.013 3.901-1.014 1.823 0 3.345.675a6.86 6.86 0 0 1 2.535 1.892 6.44 6.44 0 0 1 1.355 2.793h-3.065a4.05 4.05 0 0 0-.895-1.431 4 4 0 0 0-1.431-.95 4.9 4.9 0 0 0-1.822-.332q-1.33 0-2.402.665a4.6 4.6 0 0 0-1.677 1.827q-.606 1.164-.606 2.62 0 1.459.606 2.621a4.6 4.6 0 0 0 1.677 1.828q1.072.664 2.402.664a4.9 4.9 0 0 0 1.822-.332 4.02 4.02 0 0 0 2.326-2.38h3.065a6.44 6.44 0 0 1-1.355 2.792 6.86 6.86 0 0 1-2.535 1.892q-1.522.675-3.345.675-2.154 0-3.901-1.013zM37.33 16.992v12.37h7.117v2.636H34.414V16.992z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const DataGripIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("datagrip", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="59.676"
|
||||
x2="1.08"
|
||||
y1="4.067"
|
||||
y2="62.663"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".28" stopColor="#7256FF" />
|
||||
<stop offset=".66" stopColor="#00D980" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="64.391"
|
||||
x2="39.607"
|
||||
y1="56.329"
|
||||
y2="2.874"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".3" stopColor="#FF43F2" />
|
||||
<stop offset=".54" stopColor="#7256FF" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M4.125 64h34.128a4.13 4.13 0 0 0 3.8-2.52L57.85 24.057c.219-.518.33-1.076.324-1.638l-.15-18.329A4.125 4.125 0 0 0 53.9 0H36.234c-.806 0-1.593.236-2.267.678L1.86 21.787A4.13 4.13 0 0 0 0 25.234v34.641A4.125 4.125 0 0 0 4.125 64"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M49.013 58h10.862A4.125 4.125 0 0 0 64 53.875V41.309q0-.3-.044-.598L58.508 3.527A4.125 4.125 0 0 0 54.427 0H39.029a4.125 4.125 0 0 0-4.125 4.126l.005 18.505c0 .425.066.848.195 1.253l9.979 31.246a4.13 4.13 0 0 0 3.93 2.87"
|
||||
/>
|
||||
<path
|
||||
fill="#FF43F2"
|
||||
d="M47.55 58h12.259a4.125 4.125 0 0 0 4.124-4.19L64 43c-.018-1.181-.785-2.531-1.682-3.3L24.159 6.993A4.13 4.13 0 0 0 21.474 6H10.125A4.125 4.125 0 0 0 6 10.125v11.003c0 1.19.514 2.321 1.409 3.105l37.425 32.746A4.12 4.12 0 0 0 47.55 58"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM17.012 16.992h5.713q2.133 0 3.821.965a6.9 6.9 0 0 1 2.642 2.674q.954 1.71.954 3.864t-.954 3.865a6.9 6.9 0 0 1-2.642 2.674q-1.688.964-3.821.964h-5.713zm8.028 11.876q1.008-.6 1.554-1.72.547-1.12.547-2.653 0-1.534-.547-2.653-.546-1.12-1.554-1.721-1.008-.6-2.348-.6h-2.755v9.947h2.755q1.34 0 2.348-.6M35.426 31.243a7.3 7.3 0 0 1-2.744-2.787q-.997-1.774-.997-3.961c0-2.187.333-2.778.997-3.96s1.58-2.112 2.744-2.787q1.747-1.013 3.902-1.014 1.746 0 3.221.622a6.9 6.9 0 0 1 2.487 1.747 6.36 6.36 0 0 1 1.42 2.594h-3.13a3.9 3.9 0 0 0-.927-1.228q-.585-.52-1.367-.803c-.782-.283-1.082-.284-1.683-.284q-1.329 0-2.401.664a4.6 4.6 0 0 0-1.678 1.828q-.605 1.163-.605 2.62c0 1.457.202 1.846.605 2.621a4.6 4.6 0 0 0 1.678 1.828q1.072.664 2.401.664 1.233 0 2.235-.461t1.592-1.276a3.3 3.3 0 0 0 .633-1.833l.01.31h-3.526v-2.304h6.356v1.18q0 1.982-.96 3.585a6.9 6.9 0 0 1-2.625 2.525q-1.668.921-3.736.921c-1.38 0-2.737-.337-3.902-1.013z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const DataSpellIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("dataspell", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="4.067"
|
||||
x2="62.664"
|
||||
y1="4.327"
|
||||
y2="62.923"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".28" stopColor="#007DFE" />
|
||||
<stop offset=".73" stopColor="#00D980" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="56.329"
|
||||
x2="2.875"
|
||||
y1="-.391"
|
||||
y2="24.392"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".32" stopColor="#F0EB18" />
|
||||
<stop offset=".55" stopColor="#007DFE" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M64 59.878V25.75a4.13 4.13 0 0 0-2.52-3.8L24.057 6.153a4.1 4.1 0 0 0-1.638-.325l-18.329.15A4.124 4.124 0 0 0 0 10.103v17.665c0 .806.236 1.593.678 2.267l21.109 32.109a4.12 4.12 0 0 0 3.447 1.859h34.641A4.125 4.125 0 0 0 64 59.878"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M58 14.988V4.125A4.125 4.125 0 0 0 53.875 0H41.309q-.3 0-.598.044L3.527 5.492A4.125 4.125 0 0 0 0 9.573v15.398a4.125 4.125 0 0 0 4.126 4.125l18.505-.005c.425 0 .848-.066 1.253-.195l31.246-9.98A4.13 4.13 0 0 0 58 14.988"
|
||||
/>
|
||||
<path
|
||||
fill="#F0EB18"
|
||||
d="M58 16.45V4.191A4.125 4.125 0 0 0 53.81.067L43 0c-1.181.019-2.531.786-3.3 1.683L6.993 39.84c-.64.748-.993 1.7-.993 2.685v11.349A4.125 4.125 0 0 0 10.125 58h11.003c1.19 0 2.321-.514 3.105-1.409l32.746-37.425A4.12 4.12 0 0 0 58 16.45"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM17.012 16.992h5.713q2.133 0 3.821.965a6.9 6.9 0 0 1 2.642 2.674q.954 1.71.954 3.864t-.954 3.865a6.9 6.9 0 0 1-2.642 2.674q-1.688.964-3.821.964h-5.713zm8.028 11.876q1.008-.6 1.554-1.72.547-1.12.547-2.653 0-1.534-.547-2.653-.546-1.12-1.554-1.721-1.008-.6-2.348-.6h-2.755v9.947h2.755q1.34 0 2.348-.6M34.713 31.664q-1.26-.59-1.973-1.65t-.734-2.444h2.937q0 .654.343 1.147t.954.772q.61.278 1.404.278c.53 0 .952-.083 1.334-.251q.574-.252.89-.702t.316-1.029q0-.718-.434-1.19-.435-.471-1.195-.654l-2.648-.59q-1.071-.234-1.865-.809a4 4 0 0 1-1.232-1.42q-.44-.846-.44-1.908 0-1.286.665-2.31.664-1.023 1.854-1.597 1.19-.573 2.701-.573c1.511 0 1.933.186 2.733.558s1.424.888 1.871 1.549q.67.99.68 2.277h-2.926q0-.546-.289-.98c-.289-.435-.466-.515-.82-.676a2.9 2.9 0 0 0-1.217-.24q-.686 0-1.205.23a1.9 1.9 0 0 0-.81.643q-.29.412-.29.96 0 .621.403 1.028.402.407 1.098.579l2.552.557q1.103.226 1.967.852a4.45 4.45 0 0 1 1.345 1.544q.481.917.482 1.999 0 1.329-.702 2.385-.702 1.054-1.967 1.656-1.265.6-2.894.6t-2.889-.59"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const GoLandIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("goland", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="64.391"
|
||||
x2="39.607"
|
||||
y1="56.329"
|
||||
y2="2.874"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".24" stopColor="#00D886" />
|
||||
<stop offset=".51" stopColor="#007DFE" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="59.676"
|
||||
x2="1.08"
|
||||
y1="4.067"
|
||||
y2="62.663"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".27" stopColor="#007DFE" />
|
||||
<stop offset=".7" stopColor="#D249FC" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill="#00D886"
|
||||
d="M47.55 58h12.259a4.125 4.125 0 0 0 4.124-4.19l-.176-11.044a4.13 4.13 0 0 0-1.44-3.066L24.159 6.993A4.13 4.13 0 0 0 21.474 6H10.125A4.125 4.125 0 0 0 6 10.125v11.003c0 1.19.514 2.321 1.409 3.105l37.425 32.746A4.12 4.12 0 0 0 47.55 58"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M49.013 58h10.862A4.125 4.125 0 0 0 64 53.875V41.309q0-.3-.044-.598L58.508 3.527A4.124 4.124 0 0 0 54.427 0H39.029a4.125 4.125 0 0 0-4.125 4.126l.005 18.505c0 .425.066.848.195 1.253l9.979 31.246a4.13 4.13 0 0 0 3.93 2.87"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M4.125 64h34.128a4.13 4.13 0 0 0 3.8-2.52L57.85 24.057c.219-.518.33-1.076.324-1.638l-.15-18.329A4.124 4.124 0 0 0 53.9 0H36.234c-.805 0-1.593.236-2.266.678L1.86 21.787A4.13 4.13 0 0 0 0 25.234v34.641A4.125 4.125 0 0 0 4.125 64"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M19.748 31.243a7.3 7.3 0 0 1-2.743-2.787q-.997-1.774-.997-3.961c0-2.187.332-2.778.997-3.96s1.58-2.112 2.743-2.787q1.747-1.013 3.902-1.014 1.747 0 3.222.622a6.9 6.9 0 0 1 2.486 1.747 6.4 6.4 0 0 1 1.42 2.594h-3.13a3.9 3.9 0 0 0-.926-1.228q-.584-.52-1.367-.803c-.783-.283-1.083-.284-1.683-.284q-1.33 0-2.402.664a4.6 4.6 0 0 0-1.677 1.828q-.606 1.163-.606 2.62c0 1.457.202 1.846.606 2.621a4.6 4.6 0 0 0 1.677 1.828q1.072.664 2.402.664 1.232 0 2.235-.461t1.591-1.276a3.3 3.3 0 0 0 .633-1.833l.01.31h-3.526v-2.304h6.357v1.18q0 1.982-.96 3.585a6.9 6.9 0 0 1-2.626 2.525q-1.666.921-3.736.921c-2.07 0-2.737-.337-3.902-1.013zM36.271 31.243a7.3 7.3 0 0 1-2.755-2.787q-1.002-1.774-1.002-3.961c0-2.187.333-2.778 1.002-3.96a7.3 7.3 0 0 1 2.755-2.787q1.752-1.013 3.918-1.014c1.443 0 2.738.338 3.907 1.013a7.3 7.3 0 0 1 2.749 2.787q.996 1.774.997 3.961c0 2.187-.333 2.778-.997 3.96s-1.581 2.113-2.75 2.788q-1.752 1.013-3.906 1.013c-1.437 0-2.75-.338-3.918-1.013m6.308-2.23q1.062-.67 1.662-1.854t.6-2.664-.6-2.664-1.662-1.854-2.39-.67-2.395.67a4.6 4.6 0 0 0-1.672 1.854q-.606 1.185-.606 2.664t.606 2.664 1.672 1.854 2.395.67q1.33 0 2.39-.67M33 44H17v3h16z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const IntelliJIdeaIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("intellij-idea", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="-.391"
|
||||
x2="24.392"
|
||||
y1="7.671"
|
||||
y2="61.126"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".1" stopColor="#FC801D" />
|
||||
<stop offset=".59" stopColor="#FE2857" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="4.325"
|
||||
x2="62.921"
|
||||
y1="59.932"
|
||||
y2="1.336"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".21" stopColor="#FE2857" />
|
||||
<stop offset=".7" stopColor="#007EFF" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill="#FF8100"
|
||||
d="M16.45 6H4.191a4.125 4.125 0 0 0-4.124 4.19l.176 11.044a4.13 4.13 0 0 0 1.44 3.066l38.159 32.707c.747.64 1.7.993 2.684.993h11.35A4.125 4.125 0 0 0 58 53.875V42.872c0-1.19-.514-2.321-1.41-3.105L19.167 7.021A4.12 4.12 0 0 0 16.45 6"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M14.988 6H4.125A4.125 4.125 0 0 0 0 10.125v12.566q0 .3.044.598l5.448 37.185A4.125 4.125 0 0 0 9.573 64h15.398a4.125 4.125 0 0 0 4.125-4.127L29.09 41.37c0-.426-.066-.849-.195-1.254l-9.98-31.245A4.13 4.13 0 0 0 14.988 6z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M59.876 0H25.748a4.13 4.13 0 0 0-3.8 2.52L6.151 39.943a4.1 4.1 0 0 0-.325 1.638l.15 18.329A4.125 4.125 0 0 0 10.101 64h17.666c.806 0 1.593-.236 2.266-.678l32.11-21.109A4.12 4.12 0 0 0 64 38.766V4.125A4.125 4.125 0 0 0 59.876 0"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM17 29.383h2.98v-9.775H17v-2.616h8.843v2.616h-2.98v9.775h2.98V32H17zM27.643 29.298h2.154a2.4 2.4 0 0 0 1.163-.279q.51-.279.788-.788.279-.51.279-1.163V16.992h2.926v10.28q0 1.35-.622 2.427a4.45 4.45 0 0 1-1.715 1.688q-1.092.612-2.454.611h-2.519z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const PhpStormIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("phpstorm", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="56.329"
|
||||
x2="2.874"
|
||||
y1="-.391"
|
||||
y2="24.392"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".16" stopColor="#D249FC" />
|
||||
<stop offset=".55" stopColor="#FF2D90" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="4.067"
|
||||
x2="62.664"
|
||||
y1="4.326"
|
||||
y2="62.923"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".3" stopColor="#FF2D90" />
|
||||
<stop offset=".7" stopColor="#7256FF" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill="#D249FC"
|
||||
d="M58 16.446V4.187A4.125 4.125 0 0 0 53.81.063L42.765.239A4.13 4.13 0 0 0 39.7 1.68L6.993 39.837c-.64.748-.993 1.7-.993 2.685v11.35a4.125 4.125 0 0 0 4.125 4.124h11.003c1.19 0 2.321-.514 3.105-1.409l32.746-37.425A4.12 4.12 0 0 0 58 16.446"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M58 14.988V4.125A4.125 4.125 0 0 0 53.875 0H41.309q-.3 0-.598.044L3.527 5.492A4.125 4.125 0 0 0 0 9.573v15.398a4.125 4.125 0 0 0 4.126 4.125l18.505-.005c.425 0 .848-.066 1.253-.195l31.246-9.98A4.13 4.13 0 0 0 58 14.988"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M64 59.878V25.75a4.13 4.13 0 0 0-2.52-3.8L24.057 6.153a4.1 4.1 0 0 0-1.638-.325l-18.329.15A4.124 4.124 0 0 0 0 10.103v17.665c0 .806.236 1.593.678 2.267l21.109 32.109a4.12 4.12 0 0 0 3.447 1.859h34.641A4.125 4.125 0 0 0 64 59.878"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM16.993 16.992h6.442q1.586 0 2.78.579 1.196.579 1.845 1.63.648 1.05.648 2.432c0 .922-.22 1.759-.659 2.466q-.66 1.062-1.87 1.646-1.212.584-2.83.584h-3.43V32h-2.927zm7.54 6.63q.553-.273.852-.782.3-.51.3-1.195c0-.685-.1-.842-.3-1.174q-.3-.5-.852-.772-.552-.273-1.291-.273h-3.323v4.47h3.323q.74 0 1.291-.273M32.572 31.664q-1.26-.59-1.972-1.65t-.735-2.444h2.937q0 .654.343 1.147t.954.772q.611.278 1.404.278c.53 0 .952-.083 1.335-.251q.572-.252.89-.702c.317-.45.315-.643.315-1.029q0-.718-.434-1.19-.435-.471-1.195-.654l-2.647-.59q-1.073-.234-1.866-.809a4 4 0 0 1-1.232-1.42q-.44-.846-.44-1.908 0-1.286.665-2.31.665-1.023 1.854-1.597 1.19-.573 2.702-.573c1.512 0 1.933.186 2.733.558q1.2.558 1.87 1.549t.681 2.277h-2.926q0-.546-.29-.98a1.9 1.9 0 0 0-.82-.676 2.9 2.9 0 0 0-1.216-.24q-.687 0-1.206.23a1.9 1.9 0 0 0-.81.643q-.29.412-.289.96 0 .621.402 1.028t1.099.579l2.551.557q1.104.226 1.967.852a4.45 4.45 0 0 1 1.345 1.544q.482.917.482 1.999 0 1.329-.701 2.385-.703 1.054-1.967 1.656-1.264.6-2.895.6-1.63 0-2.888-.59"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const PyCharmIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("pycharm", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="7.671"
|
||||
x2="61.126"
|
||||
y1="64.393"
|
||||
y2="39.609"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".1" stopColor="#00D886" />
|
||||
<stop offset=".59" stopColor="#F0EB18" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="59.933"
|
||||
x2="1.337"
|
||||
y1="59.676"
|
||||
y2="1.08"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".3" stopColor="#F0EB18" />
|
||||
<stop offset=".7" stopColor="#00C4F4" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill="#00D886"
|
||||
d="M6 47.55v12.259a4.125 4.125 0 0 0 4.19 4.124l11.044-.176a4.13 4.13 0 0 0 3.066-1.44l32.707-38.158c.64-.748.993-1.7.993-2.685V10.125A4.125 4.125 0 0 0 53.875 6H42.872c-1.19 0-2.321.514-3.105 1.409L7.021 44.834A4.12 4.12 0 0 0 6 47.55"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M6 49.015v10.862a4.125 4.125 0 0 0 4.125 4.125h12.566q.3 0 .598-.044l37.185-5.448A4.125 4.125 0 0 0 64 54.429V39.03a4.125 4.125 0 0 0-4.127-4.125l-18.504.005c-.426 0-.849.066-1.254.195L8.871 45.085A4.13 4.13 0 0 0 6 49.015z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M0 4.125v34.128c0 1.658.993 3.154 2.52 3.8L39.943 57.85c.518.219 1.075.33 1.638.324l18.329-.15A4.125 4.125 0 0 0 64 53.9V36.234c0-.806-.236-1.593-.678-2.267L42.213 1.86A4.13 4.13 0 0 0 38.766 0H4.125A4.125 4.125 0 0 0 0 4.125"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM16.993 16.992h6.442q1.586 0 2.78.579 1.196.579 1.845 1.63.648 1.05.648 2.432c0 .922-.22 1.759-.659 2.466q-.66 1.062-1.87 1.646-1.212.584-2.83.584h-3.43V32h-2.927zm7.54 6.63q.553-.273.852-.782.3-.51.3-1.195c0-.685-.1-.842-.3-1.174q-.3-.5-.852-.772-.552-.273-1.291-.273h-3.324v4.47h3.324q.74 0 1.291-.273M33.713 31.243a7.3 7.3 0 0 1-2.744-2.787q-.996-1.774-.996-3.961c0-2.187.332-2.778.996-3.96a7.3 7.3 0 0 1 2.744-2.787q1.748-1.013 3.902-1.014 1.823 0 3.344.675a6.86 6.86 0 0 1 2.535 1.892 6.44 6.44 0 0 1 1.356 2.793h-3.066a4.05 4.05 0 0 0-.895-1.431 4 4 0 0 0-1.43-.95 4.9 4.9 0 0 0-1.823-.332q-1.33 0-2.402.665a4.6 4.6 0 0 0-1.677 1.827q-.606 1.164-.606 2.62 0 1.459.606 2.621a4.6 4.6 0 0 0 1.677 1.828q1.072.664 2.402.664.986 0 1.822-.332a4.02 4.02 0 0 0 2.326-2.38h3.066a6.44 6.44 0 0 1-1.356 2.792 6.86 6.86 0 0 1-2.535 1.892q-1.522.675-3.344.675-2.154 0-3.902-1.013z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const RiderIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("rider", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="64.391"
|
||||
x2="39.607"
|
||||
y1="56.329"
|
||||
y2="2.874"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".21" stopColor="#007DFE" />
|
||||
<stop offset=".55" stopColor="#FFB700" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="59.676"
|
||||
x2="1.08"
|
||||
y1="4.067"
|
||||
y2="62.663"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".23" stopColor="#FFB700" />
|
||||
<stop offset=".73" stopColor="#FF0A67" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill="#007DFE"
|
||||
d="M47.55 58h12.258a4.125 4.125 0 0 0 4.124-4.19l-.176-11.044a4.12 4.12 0 0 0-1.44-3.066L24.158 6.993A4.13 4.13 0 0 0 21.474 6H10.125A4.125 4.125 0 0 0 6 10.125v11.003c0 1.19.514 2.321 1.409 3.105l37.425 32.746A4.12 4.12 0 0 0 47.55 58"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M49.013 58h10.862A4.125 4.125 0 0 0 64 53.875V41.309q0-.3-.044-.598L58.508 3.527A4.125 4.125 0 0 0 54.427 0H39.029a4.125 4.125 0 0 0-4.125 4.126l.005 18.505c0 .425.066.848.195 1.253l9.979 31.246a4.13 4.13 0 0 0 3.93 2.87"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M4.125 64h34.128a4.13 4.13 0 0 0 3.8-2.52L57.85 24.057c.219-.518.33-1.076.324-1.638l-.15-18.329A4.124 4.124 0 0 0 53.9 0H36.234c-.805 0-1.593.236-2.266.678L1.86 21.787A4.13 4.13 0 0 0 0 25.234v34.641A4.125 4.125 0 0 0 4.125 64"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM16.992 16.992h6.442q1.576 0 2.776.579t1.85 1.63.648 2.432c0 .922-.22 1.75-.66 2.46q-.66 1.068-1.875 1.651-1.217.584-2.825.584h-3.43v5.67h-2.926zm7.54 6.63q.553-.274.853-.783.3-.51.3-1.184c0-.45-.1-.852-.3-1.185q-.3-.498-.852-.772-.552-.273-1.292-.273h-3.323v4.47h3.323q.74 0 1.292-.273m-2.63 1.763h3.194L29.03 32h-3.355zM31.613 16.992h5.713q2.133 0 3.822.965a6.9 6.9 0 0 1 2.641 2.674q.954 1.71.954 3.864t-.953 3.865a6.9 6.9 0 0 1-2.642 2.674q-1.688.964-3.822.964h-5.713zm8.028 11.876q1.008-.6 1.555-1.72t.547-2.653q0-1.534-.547-2.653-.547-1.12-1.555-1.721-1.008-.6-2.347-.6h-2.755v9.947h2.755q1.34 0 2.347-.6"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const RubyMineIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("rubymine", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="4.325"
|
||||
x2="62.921"
|
||||
y1="59.932"
|
||||
y2="1.337"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".29" stopColor="#FF2358" />
|
||||
<stop offset=".75" stopColor="#7256FF" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="-.391"
|
||||
x2="24.393"
|
||||
y1="7.671"
|
||||
y2="61.125"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".29" stopColor="#FF8100" />
|
||||
<stop offset=".56" stopColor="#FF2358" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M59.875 0H25.748a4.13 4.13 0 0 0-3.8 2.52L6.151 39.942a4.1 4.1 0 0 0-.325 1.639l.15 18.328A4.125 4.125 0 0 0 10.101 64h17.666c.805 0 1.593-.235 2.266-.678l32.109-21.108A4.12 4.12 0 0 0 64 38.766V4.125A4.125 4.125 0 0 0 59.875 0"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M14.987 6H4.126A4.125 4.125 0 0 0 0 10.125v12.566q0 .3.044.598l5.448 37.184A4.125 4.125 0 0 0 9.572 64H24.97a4.125 4.125 0 0 0 4.125-4.126l-.004-18.504c0-.426-.067-.85-.196-1.254L18.917 8.87A4.13 4.13 0 0 0 14.987 6z"
|
||||
/>
|
||||
<path
|
||||
fill="#FF8100"
|
||||
d="M16.45 6H4.19a4.125 4.125 0 0 0-4.124 4.19L0 21c.019 1.181.786 2.531 1.683 3.3l38.158 32.706c.748.641 1.7.993 2.684.993h11.35A4.125 4.125 0 0 0 58 53.875V42.872c0-1.189-.514-2.32-1.41-3.104L19.167 7.021A4.12 4.12 0 0 0 16.45 6"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM17.012 16.992h6.442q1.575 0 2.776.579t1.849 1.63.648 2.432c0 .922-.22 1.75-.66 2.46q-.658 1.068-1.875 1.651-1.216.584-2.824.584h-3.43v5.67h-2.926zm7.54 6.63q.552-.274.852-.783.3-.51.3-1.184c0-.45-.1-.852-.3-1.185q-.3-.498-.852-.772-.552-.273-1.292-.273h-3.323v4.47h3.323q.74 0 1.292-.273m-2.631 1.763h3.194L29.05 32h-3.355zM31.633 16.992h4.073l3.087 9.85.257 1.287.225-1.286 2.98-9.85h4.138v15.005h-2.894V21.29l.043-.782-3.494 11.49h-2.123l-3.451-11.415.043.707v10.708h-2.883V16.992z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const RustRoverIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("rustrover", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="7.671"
|
||||
x2="61.125"
|
||||
y1="64.393"
|
||||
y2="39.609"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".08" stopColor="#00D886" />
|
||||
<stop offset=".46" stopColor="#FFAB00" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="59.932"
|
||||
x2="1.336"
|
||||
y1="59.676"
|
||||
y2="1.08"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".19" stopColor="#FFAB00" />
|
||||
<stop offset=".83" stopColor="#FF004C" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill="#00D886"
|
||||
d="M6 47.55v12.258a4.125 4.125 0 0 0 4.19 4.124l11.044-.176a4.12 4.12 0 0 0 3.066-1.44l32.707-38.158c.64-.747.993-1.7.993-2.684V10.125A4.125 4.125 0 0 0 53.875 6H42.872c-1.19 0-2.321.514-3.105 1.409L7.021 44.833A4.12 4.12 0 0 0 6 47.55"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M6 49.015v10.862a4.125 4.125 0 0 0 4.125 4.125h12.566q.3 0 .598-.044l37.185-5.448A4.125 4.125 0 0 0 64 54.429V39.03a4.125 4.125 0 0 0-4.127-4.125l-18.504.005c-.426 0-.849.066-1.254.195L8.871 45.085A4.13 4.13 0 0 0 6 49.015z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M0 4.125v34.128c0 1.658.993 3.154 2.52 3.8L39.943 57.85c.518.219 1.075.33 1.638.324l18.329-.15A4.125 4.125 0 0 0 64 53.9V36.234c0-.806-.236-1.593-.678-2.267L42.213 1.86A4.13 4.13 0 0 0 38.766 0H4.125A4.125 4.125 0 0 0 0 4.125"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM16.992 16.992h6.442q1.576 0 2.776.579t1.85 1.63.648 2.432c0 .922-.22 1.75-.66 2.46q-.66 1.068-1.875 1.651-1.217.584-2.825.584h-3.43v5.67h-2.926zm7.54 6.63q.553-.274.853-.783.3-.51.3-1.184c0-.45-.1-.852-.3-1.185q-.3-.498-.852-.772-.552-.273-1.292-.273h-3.323v4.47h3.323q.74 0 1.292-.273m-2.63 1.763h3.194L29.03 32h-3.355zM31.613 16.992h6.442q1.575 0 2.776.579t1.85 1.63.648 2.432c0 .922-.22 1.75-.66 2.46q-.659 1.068-1.875 1.651-1.217.584-2.824.584h-3.43v5.67h-2.927zm7.54 6.63q.553-.274.853-.783.3-.51.3-1.184c0-.45-.1-.852-.3-1.185q-.3-.498-.852-.772-.552-.273-1.292-.273h-3.323v4.47h3.323q.74 0 1.292-.273m-2.63 1.763h3.194L43.651 32h-3.355z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export const WebStormIcon: Icon = (props) => {
|
||||
const [gradientAId, gradientBId] = useSvgGradientIds("webstorm", 2);
|
||||
|
||||
return (
|
||||
<svg {...props} viewBox="0 0 64 64" fill="none">
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={gradientAId}
|
||||
x1="7.671"
|
||||
x2="61.126"
|
||||
y1="64.392"
|
||||
y2="39.609"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".22" stopColor="#F0EB18" />
|
||||
<stop offset=".59" stopColor="#00C4F4" />
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id={gradientBId}
|
||||
x1="59.932"
|
||||
x2="1.337"
|
||||
y1="59.676"
|
||||
y2="1.079"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
>
|
||||
<stop offset=".19" stopColor="#00C4F4" />
|
||||
<stop offset=".83" stopColor="#007DFE" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
fill="#F0EB18"
|
||||
d="M6 47.55v12.258a4.125 4.125 0 0 0 4.19 4.124l11.044-.176a4.12 4.12 0 0 0 3.066-1.44l32.707-38.158c.64-.747.993-1.7.993-2.684V10.125A4.125 4.125 0 0 0 53.875 6H42.872c-1.19 0-2.321.514-3.105 1.409L7.021 44.833A4.12 4.12 0 0 0 6 47.55"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientAId})`}
|
||||
d="M6 49.015v10.862a4.125 4.125 0 0 0 4.125 4.125h12.566q.3 0 .598-.044l37.185-5.448A4.125 4.125 0 0 0 64 54.429V39.03a4.125 4.125 0 0 0-4.127-4.125l-18.504.005c-.426 0-.849.066-1.254.195L8.871 45.085A4.13 4.13 0 0 0 6 49.015z"
|
||||
/>
|
||||
<path
|
||||
fill={`url(#${gradientBId})`}
|
||||
d="M0 4.125v34.128c0 1.658.993 3.154 2.52 3.8L39.943 57.85c.518.219 1.075.33 1.638.324l18.329-.15A4.125 4.125 0 0 0 64 53.9V36.234c0-.806-.236-1.593-.678-2.267L42.213 1.86A4.13 4.13 0 0 0 38.766 0H4.125A4.125 4.125 0 0 0 0 4.125"
|
||||
/>
|
||||
<path fill="#000" d="M52 12H12v40h40z" />
|
||||
<path
|
||||
fill="#fff"
|
||||
d="M33 44H17v3h16zM19.051 16.992l2.423 10.955 2.583-10.955h2.958l2.701 10.955 2.348-10.955h2.97l-3.645 15.006h-3.334l-2.53-10.9-2.561 10.9H19.64l-3.623-15.006zM38.662 31.664q-1.26-.59-1.972-1.65t-.735-2.444h2.937q0 .654.343 1.147t.954.772q.61.278 1.404.278c.53 0 .952-.083 1.335-.251q.573-.252.889-.702t.316-1.029q0-.718-.434-1.19-.435-.471-1.195-.654l-2.648-.59q-1.071-.234-1.865-.809a4 4 0 0 1-1.232-1.42q-.44-.846-.44-1.908 0-1.286.665-2.31.664-1.023 1.854-1.597 1.19-.573 2.701-.573c1.008 0 1.934.186 2.734.558q1.2.558 1.87 1.549t.68 2.277h-2.925q0-.546-.29-.98c-.29-.435-.466-.515-.82-.676a2.9 2.9 0 0 0-1.217-.24q-.686 0-1.205.23a1.9 1.9 0 0 0-.81.643q-.29.412-.289.96 0 .621.402 1.028t1.099.579l2.55.557q1.105.226 1.968.852a4.45 4.45 0 0 1 1.345 1.544 4.2 4.2 0 0 1 .482 1.999q0 1.329-.702 2.385-.702 1.054-1.966 1.656-1.266.6-2.894.6-1.63 0-2.889-.59"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
@@ -532,16 +532,20 @@ describe("Keybindings update toast", () => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("shows a toast for each consecutive keybinding update with no issues", async () => {
|
||||
it("coalesces rapid consecutive keybinding update toasts with no issues", async () => {
|
||||
const mounted = await mountApp();
|
||||
|
||||
try {
|
||||
sendServerConfigUpdatedPush([]);
|
||||
await waitForToast("Keybindings updated", 1);
|
||||
|
||||
// Each server push represents a distinct file change, so it should produce its own toast.
|
||||
// A single edit can produce several reload notifications as the direct update and
|
||||
// filesystem watcher settle, so avoid stacking identical success toasts.
|
||||
sendServerConfigUpdatedPush([]);
|
||||
await waitForToast("Keybindings updated", 2);
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
|
||||
const titles = queryToastTitles();
|
||||
expect(titles.filter((title) => title === "Keybindings updated")).toHaveLength(1);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
|
||||
@@ -20,13 +20,13 @@ import {
|
||||
keybindingValueForCommand,
|
||||
decodeProjectScriptKeybindingRule,
|
||||
} from "~/lib/projectScriptKeybindings";
|
||||
import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
primaryProjectScript,
|
||||
} from "~/projectScripts";
|
||||
import { shortcutLabelForCommand } from "~/keybindings";
|
||||
import { isMacPlatform } from "~/lib/utils";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
@@ -96,57 +96,6 @@ interface ProjectScriptsControlProps {
|
||||
onDeleteScript: (scriptId: string) => Promise<void> | void;
|
||||
}
|
||||
|
||||
function normalizeShortcutKeyToken(key: string): string | null {
|
||||
const normalized = key.toLowerCase();
|
||||
if (
|
||||
normalized === "meta" ||
|
||||
normalized === "control" ||
|
||||
normalized === "ctrl" ||
|
||||
normalized === "shift" ||
|
||||
normalized === "alt" ||
|
||||
normalized === "option"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (normalized === " ") return "space";
|
||||
if (normalized === "escape") return "esc";
|
||||
if (normalized === "arrowup") return "arrowup";
|
||||
if (normalized === "arrowdown") return "arrowdown";
|
||||
if (normalized === "arrowleft") return "arrowleft";
|
||||
if (normalized === "arrowright") return "arrowright";
|
||||
if (normalized.length === 1) return normalized;
|
||||
if (normalized.startsWith("f") && normalized.length <= 3) return normalized;
|
||||
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "delete" || normalized === "home" || normalized === "end") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "pageup" || normalized === "pagedown") return normalized;
|
||||
return null;
|
||||
}
|
||||
|
||||
function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {
|
||||
const keyToken = normalizeShortcutKeyToken(event.key);
|
||||
if (!keyToken) return null;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (isMacPlatform(navigator.platform)) {
|
||||
if (event.metaKey) parts.push("mod");
|
||||
if (event.ctrlKey) parts.push("ctrl");
|
||||
} else {
|
||||
if (event.ctrlKey) parts.push("mod");
|
||||
if (event.metaKey) parts.push("meta");
|
||||
}
|
||||
if (event.altKey) parts.push("alt");
|
||||
if (event.shiftKey) parts.push("shift");
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
export default function ProjectScriptsControl({
|
||||
scripts,
|
||||
keybindings,
|
||||
@@ -186,7 +135,7 @@ export default function ProjectScriptsControl({
|
||||
setKeybinding("");
|
||||
return;
|
||||
}
|
||||
const next = keybindingFromEvent(event);
|
||||
const next = keybindingFromKeyboardEvent(event, navigator.platform);
|
||||
if (!next) return;
|
||||
setKeybinding(next);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,673 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
collectUpdatedProviderSnapshots,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
getProviderUpdateInitialToastView,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateRejectedToastView,
|
||||
getProviderUpdateSidebarPillView,
|
||||
getSingleProviderUpdateProgressToastView,
|
||||
hasOneClickUpdateProviderCandidate,
|
||||
isProviderUpdateCandidate,
|
||||
providerUpdateNotificationKey,
|
||||
type ProviderUpdateCandidate,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
|
||||
const checkedAt = "2026-04-23T10:00:00.000Z";
|
||||
const sessionStartedAt = "2026-04-23T09:59:00.000Z";
|
||||
const laterCheckedAt = "2026-04-23T10:01:00.000Z";
|
||||
|
||||
const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const instanceId = (value: string) => ProviderInstanceId.make(value);
|
||||
|
||||
function provider(input: {
|
||||
readonly driver: ReturnType<typeof ProviderDriverKind.make>;
|
||||
readonly instanceId?: ReturnType<typeof ProviderInstanceId.make>;
|
||||
readonly enabled?: boolean;
|
||||
readonly version?: string | null;
|
||||
readonly latestVersion?: string | null;
|
||||
readonly canUpdate?: boolean;
|
||||
readonly updateCommand?: string | null;
|
||||
readonly updateState?: ServerProvider["updateState"];
|
||||
readonly advisoryStatus?: NonNullable<ServerProvider["versionAdvisory"]>["status"];
|
||||
}): ServerProvider {
|
||||
const result: ServerProvider = {
|
||||
instanceId: input.instanceId ?? instanceId(String(input.driver)),
|
||||
driver: input.driver,
|
||||
enabled: input.enabled ?? true,
|
||||
installed: true,
|
||||
version: input.version ?? "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
versionAdvisory: {
|
||||
status: input.advisoryStatus ?? "behind_latest",
|
||||
currentVersion: input.version ?? "1.0.0",
|
||||
latestVersion: "latestVersion" in input ? input.latestVersion : "1.1.0",
|
||||
updateCommand: "updateCommand" in input ? input.updateCommand : "npm install -g provider",
|
||||
canUpdate: input.canUpdate ?? true,
|
||||
checkedAt,
|
||||
message: "Update available.",
|
||||
},
|
||||
};
|
||||
|
||||
if (input.updateState) {
|
||||
return { ...result, updateState: input.updateState };
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function updateCandidate(input: Parameters<typeof provider>[0]): ProviderUpdateCandidate {
|
||||
return provider(input) as ProviderUpdateCandidate;
|
||||
}
|
||||
|
||||
describe("provider update launch notification logic", () => {
|
||||
it("detects enabled providers with a latest-version advisory", () => {
|
||||
expect(isProviderUpdateCandidate(provider({ driver: driver("codex") }))).toBe(true);
|
||||
expect(isProviderUpdateCandidate(provider({ driver: driver("codex"), enabled: false }))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
isProviderUpdateCandidate(
|
||||
provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isProviderUpdateCandidate(provider({ driver: driver("codex"), latestVersion: null })),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("deduplicates multi-instance provider candidates by driver", () => {
|
||||
expect(
|
||||
collectProviderUpdateCandidates([
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: instanceId("codex_personal"),
|
||||
latestVersion: "1.1.0",
|
||||
}),
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: instanceId("codex"),
|
||||
latestVersion: "1.1.0",
|
||||
}),
|
||||
provider({ driver: driver("cursor"), latestVersion: "0.3.0" }),
|
||||
]),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("disables one-click updates when provider instances disagree on the update command", () => {
|
||||
const candidate = updateCandidate({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_personal"),
|
||||
latestVersion: "2.1.123",
|
||||
});
|
||||
|
||||
expect(
|
||||
canOneClickUpdateProviderCandidate(candidate, [
|
||||
candidate,
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_work"),
|
||||
latestVersion: "2.1.123",
|
||||
canUpdate: true,
|
||||
updateCommand: "bun add -g @anthropic-ai/claude-code@latest",
|
||||
}),
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps one-click updates enabled when sibling instances are already current", () => {
|
||||
const candidate = updateCandidate({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_personal"),
|
||||
latestVersion: "2.1.123",
|
||||
updateCommand: "npm install -g @anthropic-ai/claude-code@latest",
|
||||
});
|
||||
|
||||
expect(
|
||||
hasOneClickUpdateProviderCandidate(candidate, [
|
||||
candidate,
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_work"),
|
||||
version: "2.1.123",
|
||||
latestVersion: "2.1.123",
|
||||
advisoryStatus: "current",
|
||||
canUpdate: false,
|
||||
updateCommand: null,
|
||||
}),
|
||||
]),
|
||||
).toBe(true);
|
||||
expect(
|
||||
canOneClickUpdateProviderCandidate(candidate, [
|
||||
candidate,
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
instanceId: instanceId("claude_work"),
|
||||
version: "2.1.123",
|
||||
latestVersion: "2.1.123",
|
||||
advisoryStatus: "current",
|
||||
canUpdate: false,
|
||||
updateCommand: null,
|
||||
}),
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the inline update action available while a provider update is already running", () => {
|
||||
const candidate = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(hasOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(true);
|
||||
expect(canOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(false);
|
||||
});
|
||||
|
||||
it("builds a notification key from provider latest versions", () => {
|
||||
const codex = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.0.0",
|
||||
latestVersion: "1.1.0",
|
||||
});
|
||||
const cursor = updateCandidate({
|
||||
driver: driver("cursor"),
|
||||
version: "0.2.0",
|
||||
latestVersion: "0.3.0",
|
||||
});
|
||||
|
||||
expect(providerUpdateNotificationKey([codex, cursor])).toBe("codex:1.1.0|cursor:0.3.0");
|
||||
expect(providerUpdateNotificationKey([])).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the same notification key while the published update version is unchanged", () => {
|
||||
const first = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.0.0",
|
||||
latestVersion: "1.2.0",
|
||||
});
|
||||
const second = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.2.0",
|
||||
});
|
||||
const nextPublishedVersion = updateCandidate({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.3.0",
|
||||
});
|
||||
|
||||
expect(providerUpdateNotificationKey([first])).toBe(providerUpdateNotificationKey([second]));
|
||||
expect(providerUpdateNotificationKey([nextPublishedVersion])).not.toBe(
|
||||
providerUpdateNotificationKey([first]),
|
||||
);
|
||||
});
|
||||
|
||||
it("tracks updated provider snapshots by instance instead of collapsing to a sibling driver", () => {
|
||||
const targetInstanceId = instanceId("codex_personal");
|
||||
const siblingInstanceId = instanceId("codex");
|
||||
const updatedPersonal = provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: targetInstanceId,
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
});
|
||||
const currentDefaultSibling = provider({
|
||||
driver: driver("codex"),
|
||||
instanceId: siblingInstanceId,
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: undefined,
|
||||
});
|
||||
|
||||
expect(
|
||||
collectUpdatedProviderSnapshots({
|
||||
results: [
|
||||
{
|
||||
status: "fulfilled",
|
||||
value: {
|
||||
providers: [updatedPersonal, currentDefaultSibling],
|
||||
},
|
||||
},
|
||||
],
|
||||
providerInstanceIds: new Set([targetInstanceId]),
|
||||
}),
|
||||
).toEqual([updatedPersonal]);
|
||||
});
|
||||
|
||||
it("describes a single one-click update", () => {
|
||||
const view = getProviderUpdateInitialToastView({
|
||||
updateProviders: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
oneClickProviders: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "initial",
|
||||
type: "warning",
|
||||
title: "Update Available: Codex v1.1.0",
|
||||
description: "Install the update now or review provider settings.",
|
||||
});
|
||||
});
|
||||
|
||||
it("describes settings-only updates without one-click support", () => {
|
||||
const view = getProviderUpdateInitialToastView({
|
||||
updateProviders: [
|
||||
updateCandidate({ driver: driver("codex"), canUpdate: false }),
|
||||
updateCandidate({ driver: driver("cursor"), canUpdate: false }),
|
||||
],
|
||||
oneClickProviders: [],
|
||||
});
|
||||
|
||||
expect(view.description).toBe("Codex and Cursor can be updated from provider settings.");
|
||||
});
|
||||
|
||||
it("uses server update state for running progress", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "running",
|
||||
type: "loading",
|
||||
title: "Updating provider",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses server failure state for failed progress", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "command failed",
|
||||
output: "stderr",
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: "Provider update failed",
|
||||
description: "command failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves a single-provider completion view from the returned provider snapshot", () => {
|
||||
const view = getSingleProviderUpdateProgressToastView(
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "command failed",
|
||||
output: "stderr",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: "Codex v1.1.0 update failed",
|
||||
description: "command failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unchanged providers actionable from settings", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("cursor"),
|
||||
updateState: {
|
||||
status: "unchanged",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "still old",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "unchanged",
|
||||
type: "warning",
|
||||
title: "Provider still needs an update",
|
||||
description: "Cursor still appears outdated. Check provider settings for details.",
|
||||
});
|
||||
});
|
||||
|
||||
it("marks progress succeeded once every attempted provider is no longer outdated", () => {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
providerCount: 1,
|
||||
});
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "succeeded",
|
||||
type: "success",
|
||||
title: "Provider updated",
|
||||
description: "New sessions will use the updated provider.",
|
||||
dismissAfterVisibleMs: 3_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the updated version in the single-provider success toast title", () => {
|
||||
const view = getSingleProviderUpdateProgressToastView(
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
phase: "succeeded",
|
||||
type: "success",
|
||||
title: "Codex updated: v1.1.0",
|
||||
description: "New sessions will use the updated provider.",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to a rejected RPC message for transport-level failures", () => {
|
||||
const results: PromiseSettledResult<unknown>[] = [
|
||||
{ status: "rejected", reason: new Error("WebSocket closed") },
|
||||
];
|
||||
|
||||
expect(firstRejectedProviderUpdateMessage(results)).toBe("WebSocket closed");
|
||||
expect(getProviderUpdateRejectedToastView(2, "WebSocket closed")).toMatchObject({
|
||||
phase: "failed",
|
||||
title: "Provider updates failed",
|
||||
description: "WebSocket closed",
|
||||
});
|
||||
});
|
||||
|
||||
it("collects only attempted provider snapshots from update responses", () => {
|
||||
const codex = provider({ driver: driver("codex") });
|
||||
const cursor = provider({ driver: driver("cursor") });
|
||||
const results: PromiseSettledResult<{ readonly providers: ReadonlyArray<ServerProvider> }>[] = [
|
||||
{ status: "fulfilled", value: { providers: [codex, cursor] } },
|
||||
];
|
||||
|
||||
expect(
|
||||
collectUpdatedProviderSnapshots({
|
||||
results,
|
||||
providerInstanceIds: new Set([cursor.instanceId]),
|
||||
}),
|
||||
).toEqual([cursor]);
|
||||
});
|
||||
|
||||
it("summarizes active provider updates for the sidebar pill", () => {
|
||||
const view = getProviderUpdateSidebarPillView([
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
provider({
|
||||
driver: driver("cursor"),
|
||||
updateState: {
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
message: "Waiting for another provider update to finish.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
tone: "loading",
|
||||
title: "Updating 2 providers",
|
||||
description: "Codex and Cursor updates are in progress.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the provider name for single active sidebar pill updates", () => {
|
||||
const view = getProviderUpdateSidebarPillView([
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "running",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: null,
|
||||
message: "Updating provider.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "loading:codex:running",
|
||||
tone: "loading",
|
||||
title: "Updating Codex",
|
||||
description: "Codex update in progress.",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the provider name for single failed sidebar pill updates", () => {
|
||||
const view = getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Update command exited with code 1.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: sessionStartedAt },
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",
|
||||
tone: "error",
|
||||
title: "Claude v1.1.0 update failed",
|
||||
description: "Update command exited with code 1.",
|
||||
dismissible: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a short-lived success sidebar pill after a single provider update succeeds", () => {
|
||||
const view = getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.1.0",
|
||||
latestVersion: "1.1.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: sessionStartedAt },
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "succeeded:codex:2026-04-23T10:00:00.000Z:Provider updated.",
|
||||
tone: "success",
|
||||
title: "Codex updated: v1.1.0",
|
||||
description: "New sessions will use the updated provider.",
|
||||
dismissAfterVisibleMs: 3_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps unchanged sidebar pill states dismissible", () => {
|
||||
const view = getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("cursor"),
|
||||
updateState: {
|
||||
status: "unchanged",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "still old",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: sessionStartedAt },
|
||||
);
|
||||
|
||||
expect(view).toMatchObject({
|
||||
key: "unchanged:cursor:2026-04-23T10:00:00.000Z:still old",
|
||||
tone: "warning",
|
||||
title: "Cursor still needs an update",
|
||||
dismissible: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not show sidebar terminal states from before the current app session", () => {
|
||||
expect(
|
||||
getProviderUpdateSidebarPillView(
|
||||
[
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "command failed",
|
||||
output: "stderr",
|
||||
},
|
||||
}),
|
||||
],
|
||||
{ visibleAfterIso: "2026-04-23T10:00:01.000Z" },
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a newer success before falling back to an older failure", () => {
|
||||
const providers = [
|
||||
provider({
|
||||
driver: driver("claudeAgent"),
|
||||
updateState: {
|
||||
status: "failed",
|
||||
startedAt: checkedAt,
|
||||
finishedAt: checkedAt,
|
||||
message: "Update command exited with code 1.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
provider({
|
||||
driver: driver("codex"),
|
||||
version: "1.2.0",
|
||||
latestVersion: "1.2.0",
|
||||
advisoryStatus: "current",
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: laterCheckedAt,
|
||||
finishedAt: laterCheckedAt,
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
}),
|
||||
] satisfies ReadonlyArray<ServerProvider>;
|
||||
|
||||
const successView = getProviderUpdateSidebarPillView(providers, {
|
||||
visibleAfterIso: sessionStartedAt,
|
||||
});
|
||||
expect(successView).toMatchObject({
|
||||
key: "succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated.",
|
||||
tone: "success",
|
||||
title: "Codex updated: v1.2.0",
|
||||
});
|
||||
|
||||
const failureView = getProviderUpdateSidebarPillView(providers, {
|
||||
visibleAfterIso: sessionStartedAt,
|
||||
dismissedKeys: new Set(["succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated."]),
|
||||
});
|
||||
expect(failureView).toMatchObject({
|
||||
key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",
|
||||
tone: "error",
|
||||
title: "Claude v1.1.0 update failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not show a sidebar pill for passive update availability", () => {
|
||||
expect(
|
||||
getProviderUpdateSidebarPillView([
|
||||
provider({ driver: driver("codex"), canUpdate: true }),
|
||||
provider({ driver: driver("cursor"), canUpdate: false }),
|
||||
]),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,537 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export type ProviderUpdateCandidate = ServerProvider & {
|
||||
readonly versionAdvisory: NonNullable<ServerProvider["versionAdvisory"]> & {
|
||||
readonly status: "behind_latest";
|
||||
readonly latestVersion: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type ProviderUpdateToastType = "warning" | "loading" | "error" | "success";
|
||||
export type ProviderUpdateToastPhase = "initial" | "running" | "failed" | "unchanged" | "succeeded";
|
||||
|
||||
export interface ProviderUpdateToastView {
|
||||
readonly phase: ProviderUpdateToastPhase;
|
||||
readonly type: ProviderUpdateToastType;
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly dismissAfterVisibleMs?: number;
|
||||
}
|
||||
|
||||
export type ProviderUpdateSidebarPillTone = "loading" | "warning" | "error" | "success";
|
||||
|
||||
export interface ProviderUpdateSidebarPillView {
|
||||
readonly key: string;
|
||||
readonly tone: ProviderUpdateSidebarPillTone;
|
||||
readonly title: string;
|
||||
readonly description: string;
|
||||
readonly dismissible?: boolean;
|
||||
readonly dismissAfterVisibleMs?: number;
|
||||
}
|
||||
|
||||
interface ProviderUpdateSidebarPillOptions {
|
||||
readonly visibleAfterIso?: string;
|
||||
readonly dismissedKeys?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
const PROVIDER_UPDATE_SUCCESS_VISIBLE_MS = 3_000;
|
||||
|
||||
function formatVersion(value: string): string {
|
||||
return value.startsWith("v") ? value : `v${value}`;
|
||||
}
|
||||
|
||||
function chooseRepresentativeProvider(
|
||||
current: ServerProvider | undefined,
|
||||
candidate: ServerProvider,
|
||||
): ServerProvider {
|
||||
if (!current) {
|
||||
return candidate;
|
||||
}
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(candidate.driver);
|
||||
if (candidate.instanceId === defaultInstanceId) {
|
||||
return candidate;
|
||||
}
|
||||
if (current.instanceId === defaultInstanceId) {
|
||||
return current;
|
||||
}
|
||||
return candidate.checkedAt.localeCompare(current.checkedAt) >= 0 ? candidate : current;
|
||||
}
|
||||
|
||||
function dedupeProvidersByDriver<T extends ServerProvider>(providers: ReadonlyArray<T>): T[] {
|
||||
const latestProviderByDriver = new Map<ProviderDriverKind, T>();
|
||||
|
||||
for (const provider of providers) {
|
||||
latestProviderByDriver.set(
|
||||
provider.driver,
|
||||
chooseRepresentativeProvider(latestProviderByDriver.get(provider.driver), provider) as T,
|
||||
);
|
||||
}
|
||||
|
||||
return [...latestProviderByDriver.values()];
|
||||
}
|
||||
|
||||
function dedupeProvidersByInstanceId<T extends ServerProvider>(providers: ReadonlyArray<T>): T[] {
|
||||
const latestProviderByInstanceId = new Map<ProviderInstanceId, T>();
|
||||
|
||||
for (const provider of providers) {
|
||||
const current = latestProviderByInstanceId.get(provider.instanceId);
|
||||
if (!current || provider.checkedAt.localeCompare(current.checkedAt) >= 0) {
|
||||
latestProviderByInstanceId.set(provider.instanceId, provider);
|
||||
}
|
||||
}
|
||||
|
||||
return [...latestProviderByInstanceId.values()];
|
||||
}
|
||||
|
||||
function getProviderUpdatedTitle(provider: Pick<ServerProvider, "driver" | "version">): string {
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
return provider.version
|
||||
? `${providerName} updated: ${formatVersion(provider.version)}`
|
||||
: `${providerName} updated`;
|
||||
}
|
||||
|
||||
function getProviderUpdatedDescription(providerCount: number): string {
|
||||
return providerCount === 1
|
||||
? "New sessions will use the updated provider."
|
||||
: "New sessions will use the updated providers.";
|
||||
}
|
||||
|
||||
function getProviderFailedUpdateTitle(
|
||||
provider: Pick<ServerProvider, "driver" | "versionAdvisory">,
|
||||
): string {
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
const attemptedVersion = provider.versionAdvisory?.latestVersion;
|
||||
return attemptedVersion
|
||||
? `${providerName} ${formatVersion(attemptedVersion)} update failed`
|
||||
: `${providerName} update failed`;
|
||||
}
|
||||
|
||||
export function isProviderUpdateCandidate(
|
||||
provider: ServerProvider,
|
||||
): provider is ProviderUpdateCandidate {
|
||||
return (
|
||||
provider.enabled &&
|
||||
provider.versionAdvisory?.status === "behind_latest" &&
|
||||
provider.versionAdvisory.latestVersion !== null
|
||||
);
|
||||
}
|
||||
|
||||
export function isProviderUpdateActive(provider: Pick<ServerProvider, "updateState">): boolean {
|
||||
return provider.updateState?.status === "queued" || provider.updateState?.status === "running";
|
||||
}
|
||||
|
||||
export function collectProviderUpdateCandidates(
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ProviderUpdateCandidate[] {
|
||||
return dedupeProvidersByDriver(providers.filter(isProviderUpdateCandidate));
|
||||
}
|
||||
|
||||
export function hasOneClickUpdateProviderCandidate(
|
||||
candidate: ProviderUpdateCandidate,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): boolean {
|
||||
if (
|
||||
candidate.versionAdvisory.canUpdate !== true ||
|
||||
candidate.versionAdvisory.updateCommand === null
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const driverProviders = providers.filter((provider) => provider.driver === candidate.driver);
|
||||
if (driverProviders.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const updateCommands = new Set<string>();
|
||||
for (const provider of driverProviders) {
|
||||
if (!isProviderUpdateCandidate(provider)) {
|
||||
continue;
|
||||
}
|
||||
const advisory = provider.versionAdvisory;
|
||||
if (!advisory || advisory.canUpdate !== true || advisory.updateCommand === null) {
|
||||
return false;
|
||||
}
|
||||
updateCommands.add(advisory.updateCommand);
|
||||
}
|
||||
|
||||
return updateCommands.size === 1;
|
||||
}
|
||||
|
||||
export function canOneClickUpdateProviderCandidate(
|
||||
candidate: ProviderUpdateCandidate,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): boolean {
|
||||
return (
|
||||
!isProviderUpdateActive(candidate) && hasOneClickUpdateProviderCandidate(candidate, providers)
|
||||
);
|
||||
}
|
||||
|
||||
export function providerUpdateNotificationKey(
|
||||
providers: ReadonlyArray<ProviderUpdateCandidate>,
|
||||
): string | null {
|
||||
const parts = dedupeProvidersByDriver(providers)
|
||||
.map((provider) => {
|
||||
const advisory = provider.versionAdvisory;
|
||||
return [provider.driver, advisory.latestVersion].join(":");
|
||||
})
|
||||
.toSorted();
|
||||
|
||||
return parts.length > 0 ? parts.join("|") : null;
|
||||
}
|
||||
|
||||
export function providerUpdateCandidateKey(provider: ProviderUpdateCandidate): string {
|
||||
return providerUpdateNotificationKey([provider])!;
|
||||
}
|
||||
|
||||
export function formatProviderList(providers: ReadonlyArray<Pick<ServerProvider, "driver">>) {
|
||||
const names = providers.map(
|
||||
(provider) => PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver,
|
||||
);
|
||||
if (names.length <= 2) {
|
||||
return names.join(" and ");
|
||||
}
|
||||
return `${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]}`;
|
||||
}
|
||||
|
||||
export function getProviderUpdateInitialToastView(input: {
|
||||
readonly updateProviders: ReadonlyArray<ProviderUpdateCandidate>;
|
||||
readonly oneClickProviders: ReadonlyArray<ProviderUpdateCandidate>;
|
||||
}): ProviderUpdateToastView {
|
||||
return {
|
||||
phase: "initial",
|
||||
type: "warning",
|
||||
title: getProviderUpdateInitialToastTitle(input.updateProviders),
|
||||
description:
|
||||
input.oneClickProviders.length > 0
|
||||
? "Install the update now or review provider settings."
|
||||
: `${formatProviderList(input.updateProviders)} can be updated from provider settings.`,
|
||||
};
|
||||
}
|
||||
|
||||
export function getProviderUpdateRunningToastView(providerCount: number): ProviderUpdateToastView {
|
||||
return {
|
||||
phase: "running",
|
||||
type: "loading",
|
||||
title: providerCount === 1 ? "Updating provider" : "Updating providers",
|
||||
description: "Running provider update command.",
|
||||
};
|
||||
}
|
||||
|
||||
export function getProviderUpdateRejectedToastView(
|
||||
providerCount: number,
|
||||
message: string,
|
||||
): ProviderUpdateToastView {
|
||||
return {
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: providerCount === 1 ? "Provider update failed" : "Provider updates failed",
|
||||
description: message,
|
||||
};
|
||||
}
|
||||
|
||||
export function getProviderUpdateProgressToastView(input: {
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
readonly providerCount: number;
|
||||
}): ProviderUpdateToastView {
|
||||
const providers = dedupeProvidersByDriver(input.providers);
|
||||
const failedProviders = providers.filter((provider) => provider.updateState?.status === "failed");
|
||||
if (failedProviders.length > 0) {
|
||||
return {
|
||||
phase: "failed",
|
||||
type: "error",
|
||||
title: failedProviders.length === 1 ? "Provider update failed" : "Provider updates failed",
|
||||
description: getFailedProviderUpdateDescription(failedProviders),
|
||||
};
|
||||
}
|
||||
|
||||
const unchangedProviders = providers.filter(
|
||||
(provider) => provider.updateState?.status === "unchanged",
|
||||
);
|
||||
if (unchangedProviders.length > 0) {
|
||||
return {
|
||||
phase: "unchanged",
|
||||
type: "warning",
|
||||
title:
|
||||
unchangedProviders.length === 1
|
||||
? "Provider still needs an update"
|
||||
: "Providers still need updates",
|
||||
description: `${formatProviderList(unchangedProviders)} ${
|
||||
unchangedProviders.length === 1 ? "still appears" : "still appear"
|
||||
} outdated. Check provider settings for details.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (providers.some(isProviderUpdateActive)) {
|
||||
return getProviderUpdateRunningToastView(input.providerCount);
|
||||
}
|
||||
|
||||
const hasCompleteProviderSnapshots = providers.length >= input.providerCount;
|
||||
const allProvidersUpdated =
|
||||
hasCompleteProviderSnapshots &&
|
||||
providers.every(
|
||||
(provider) =>
|
||||
provider.updateState?.status === "succeeded" || !isProviderUpdateCandidate(provider),
|
||||
);
|
||||
if (allProvidersUpdated) {
|
||||
return {
|
||||
phase: "succeeded",
|
||||
type: "success",
|
||||
title: input.providerCount === 1 ? "Provider updated" : "Provider updates finished",
|
||||
description: getProviderUpdatedDescription(input.providerCount),
|
||||
dismissAfterVisibleMs: PROVIDER_UPDATE_SUCCESS_VISIBLE_MS,
|
||||
};
|
||||
}
|
||||
|
||||
return getProviderUpdateRunningToastView(input.providerCount);
|
||||
}
|
||||
|
||||
export function getSingleProviderUpdateProgressToastView(
|
||||
provider: ServerProvider,
|
||||
): ProviderUpdateToastView {
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: [provider],
|
||||
providerCount: 1,
|
||||
});
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
|
||||
switch (view.phase) {
|
||||
case "running":
|
||||
return {
|
||||
...view,
|
||||
title: `Updating ${providerName}`,
|
||||
};
|
||||
case "failed":
|
||||
return {
|
||||
...view,
|
||||
title: getProviderFailedUpdateTitle(provider),
|
||||
};
|
||||
case "unchanged":
|
||||
return {
|
||||
...view,
|
||||
title: `${providerName} still needs an update`,
|
||||
};
|
||||
case "succeeded":
|
||||
return {
|
||||
...view,
|
||||
title: getProviderUpdatedTitle(provider),
|
||||
};
|
||||
default:
|
||||
return view;
|
||||
}
|
||||
}
|
||||
|
||||
export function collectUpdatedProviderSnapshots(input: {
|
||||
readonly results: ReadonlyArray<
|
||||
PromiseSettledResult<{ readonly providers: ReadonlyArray<ServerProvider> }>
|
||||
>;
|
||||
readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
|
||||
}): ServerProvider[] {
|
||||
const matchedProviders: ServerProvider[] = [];
|
||||
|
||||
for (const result of input.results) {
|
||||
if (result.status !== "fulfilled") {
|
||||
continue;
|
||||
}
|
||||
for (const provider of result.value.providers) {
|
||||
if (input.providerInstanceIds.has(provider.instanceId)) {
|
||||
matchedProviders.push(provider);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dedupeProvidersByInstanceId(matchedProviders);
|
||||
}
|
||||
|
||||
export function firstRejectedProviderUpdateMessage(
|
||||
results: ReadonlyArray<PromiseSettledResult<unknown>>,
|
||||
): string | null {
|
||||
const rejected = results.find((result) => result.status === "rejected");
|
||||
if (!rejected) {
|
||||
return null;
|
||||
}
|
||||
return rejected.reason instanceof Error ? rejected.reason.message : "Provider update failed.";
|
||||
}
|
||||
|
||||
function getUpdateFinishedAt(provider: ServerProvider): string | null {
|
||||
return provider.updateState?.finishedAt ?? null;
|
||||
}
|
||||
|
||||
function isRecentTerminalProvider(
|
||||
provider: ServerProvider,
|
||||
visibleAfterIso: string | undefined,
|
||||
): boolean {
|
||||
const status = provider.updateState?.status;
|
||||
if (status !== "failed" && status !== "unchanged" && status !== "succeeded") {
|
||||
return false;
|
||||
}
|
||||
if (visibleAfterIso === undefined) {
|
||||
return true;
|
||||
}
|
||||
const finishedAt = getUpdateFinishedAt(provider);
|
||||
return finishedAt !== null && finishedAt >= visibleAfterIso;
|
||||
}
|
||||
|
||||
function latestFinishedAtForProviders(providers: ReadonlyArray<ServerProvider>): string | null {
|
||||
return providers.reduce<string | null>((latest, provider) => {
|
||||
const finishedAt = getUpdateFinishedAt(provider);
|
||||
if (finishedAt === null) {
|
||||
return latest;
|
||||
}
|
||||
return latest === null || finishedAt > latest ? finishedAt : latest;
|
||||
}, null);
|
||||
}
|
||||
|
||||
export function getProviderUpdateSidebarPillView(
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
options?: ProviderUpdateSidebarPillOptions,
|
||||
): ProviderUpdateSidebarPillView | null {
|
||||
const dedupedProviders = dedupeProvidersByDriver(providers);
|
||||
const activeProviders = dedupedProviders.filter(isProviderUpdateActive);
|
||||
if (activeProviders.length > 0) {
|
||||
const activeProvider = activeProviders[0]!;
|
||||
const activeProviderName =
|
||||
PROVIDER_DISPLAY_NAMES[activeProvider.driver] ?? activeProvider.driver;
|
||||
return {
|
||||
key: `loading:${activeProviders
|
||||
.map((provider) => `${provider.driver}:${provider.updateState?.status ?? "idle"}`)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "loading",
|
||||
title:
|
||||
activeProviders.length === 1
|
||||
? `Updating ${activeProviderName}`
|
||||
: `Updating ${activeProviders.length} providers`,
|
||||
description:
|
||||
activeProviders.length === 1
|
||||
? `${formatProviderList(activeProviders)} update in progress.`
|
||||
: `${formatProviderList(activeProviders)} updates are in progress.`,
|
||||
};
|
||||
}
|
||||
|
||||
const recentTerminalProviders = dedupedProviders.filter((provider) =>
|
||||
isRecentTerminalProvider(provider, options?.visibleAfterIso),
|
||||
);
|
||||
const terminalCandidates: ProviderUpdateSidebarPillView[] = [];
|
||||
|
||||
const failedProviders = recentTerminalProviders.filter(
|
||||
(provider) => provider.updateState?.status === "failed",
|
||||
);
|
||||
if (failedProviders.length > 0) {
|
||||
const failedProvider = failedProviders[0]!;
|
||||
terminalCandidates.push({
|
||||
key: `failed:${failedProviders
|
||||
.map(
|
||||
(provider) =>
|
||||
`${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,
|
||||
)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "error",
|
||||
title:
|
||||
failedProviders.length === 1
|
||||
? getProviderFailedUpdateTitle(failedProvider)
|
||||
: `${failedProviders.length} provider updates failed`,
|
||||
description: getFailedProviderUpdateDescription(failedProviders),
|
||||
dismissible: true,
|
||||
});
|
||||
}
|
||||
|
||||
const unchangedProviders = recentTerminalProviders.filter(
|
||||
(provider) => provider.updateState?.status === "unchanged",
|
||||
);
|
||||
if (unchangedProviders.length > 0) {
|
||||
const unchangedProvider = unchangedProviders[0]!;
|
||||
const unchangedProviderName =
|
||||
PROVIDER_DISPLAY_NAMES[unchangedProvider.driver] ?? unchangedProvider.driver;
|
||||
terminalCandidates.push({
|
||||
key: `unchanged:${unchangedProviders
|
||||
.map(
|
||||
(provider) =>
|
||||
`${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,
|
||||
)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "warning",
|
||||
title:
|
||||
unchangedProviders.length === 1
|
||||
? `${unchangedProviderName} still needs an update`
|
||||
: `${unchangedProviders.length} providers still need updates`,
|
||||
description: `${formatProviderList(unchangedProviders)} ${
|
||||
unchangedProviders.length === 1 ? "still appears" : "still appear"
|
||||
} outdated. Review provider settings for details.`,
|
||||
dismissible: true,
|
||||
});
|
||||
}
|
||||
|
||||
const succeededProviders = recentTerminalProviders.filter(
|
||||
(provider) => provider.updateState?.status === "succeeded",
|
||||
);
|
||||
if (succeededProviders.length > 0) {
|
||||
const succeededProvider = succeededProviders[0]!;
|
||||
terminalCandidates.push({
|
||||
key: `succeeded:${succeededProviders
|
||||
.map(
|
||||
(provider) =>
|
||||
`${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,
|
||||
)
|
||||
.toSorted()
|
||||
.join("|")}`,
|
||||
tone: "success",
|
||||
title:
|
||||
succeededProviders.length === 1
|
||||
? getProviderUpdatedTitle(succeededProvider)
|
||||
: `${succeededProviders.length} providers updated`,
|
||||
description: getProviderUpdatedDescription(succeededProviders.length),
|
||||
dismissAfterVisibleMs: PROVIDER_UPDATE_SUCCESS_VISIBLE_MS,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
terminalCandidates
|
||||
.toSorted((left, right) => {
|
||||
const leftProviders =
|
||||
left.tone === "error"
|
||||
? failedProviders
|
||||
: left.tone === "warning"
|
||||
? unchangedProviders
|
||||
: succeededProviders;
|
||||
const rightProviders =
|
||||
right.tone === "error"
|
||||
? failedProviders
|
||||
: right.tone === "warning"
|
||||
? unchangedProviders
|
||||
: succeededProviders;
|
||||
const leftFinishedAt = latestFinishedAtForProviders(leftProviders) ?? "";
|
||||
const rightFinishedAt = latestFinishedAtForProviders(rightProviders) ?? "";
|
||||
return rightFinishedAt.localeCompare(leftFinishedAt);
|
||||
})
|
||||
.find((candidate) => !options?.dismissedKeys?.has(candidate.key)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function getProviderUpdateInitialToastTitle(
|
||||
providers: ReadonlyArray<ProviderUpdateCandidate>,
|
||||
): string {
|
||||
if (providers.length === 1) {
|
||||
const provider = providers[0]!;
|
||||
const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;
|
||||
return `Update Available: ${providerName} ${formatVersion(provider.versionAdvisory.latestVersion)}`;
|
||||
}
|
||||
return `Updates Available: ${providers.length} providers`;
|
||||
}
|
||||
|
||||
function getFailedProviderUpdateDescription(providers: ReadonlyArray<ServerProvider>): string {
|
||||
if (providers.length === 1) {
|
||||
const provider = providers[0]!;
|
||||
if (provider.updateState?.message) {
|
||||
return provider.updateState.message;
|
||||
}
|
||||
}
|
||||
return `${formatProviderList(providers)} failed to update. Check provider settings for details.`;
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { ensureLocalApi } from "../localApi";
|
||||
import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
|
||||
import { useServerProviders } from "../rpc/serverState";
|
||||
import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
collectUpdatedProviderSnapshots,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
getProviderUpdateInitialToastView,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateRejectedToastView,
|
||||
getProviderUpdateRunningToastView,
|
||||
providerUpdateNotificationKey,
|
||||
type ProviderUpdateToastView,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
|
||||
const seenProviderUpdateNotificationKeys = new Set<string>();
|
||||
type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
type ActiveProviderUpdateToast =
|
||||
| { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
|
||||
| {
|
||||
readonly kind: "update";
|
||||
readonly key: string;
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
|
||||
readonly providerCount: number;
|
||||
};
|
||||
|
||||
function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
|
||||
|
||||
if (!ProviderIcon) {
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<ProviderIcon aria-hidden="true" className="size-4" />
|
||||
<span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
|
||||
<DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function updateProviderUpdateToast(input: {
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly view: ProviderUpdateToastView;
|
||||
readonly openSettings: () => void;
|
||||
}) {
|
||||
if (input.view.type === "loading" || input.view.type === "success") {
|
||||
toastManager.update(input.toastId, {
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
...(input.view.dismissAfterVisibleMs !== undefined
|
||||
? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.update(
|
||||
input.toastId,
|
||||
stackedThreadToast({
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
actionProps: {
|
||||
children: "Settings",
|
||||
onClick: input.openSettings,
|
||||
},
|
||||
actionVariant: "outline",
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
|
||||
return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
|
||||
}
|
||||
|
||||
export function ProviderUpdateLaunchNotification() {
|
||||
const navigate = useNavigate();
|
||||
const providers = useServerProviders();
|
||||
const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
|
||||
const { dismissedNotificationKeys, dismissNotificationKey } =
|
||||
useDismissedProviderUpdateNotificationKeys();
|
||||
|
||||
const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
|
||||
const notificationKey = useMemo(
|
||||
() => providerUpdateNotificationKey(updateProviders),
|
||||
[updateProviders],
|
||||
);
|
||||
const oneClickProviders = useMemo(
|
||||
() =>
|
||||
updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
|
||||
[providers, updateProviders],
|
||||
);
|
||||
|
||||
const openProviderSettings = useCallback(
|
||||
(toastId?: ProviderUpdateToastId) => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (toastId !== undefined) {
|
||||
toastManager.close(toastId);
|
||||
} else if (activeToast) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
}
|
||||
if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
void navigate({ to: "/settings/providers" });
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind !== "update") {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeProviders = providers.filter((provider) =>
|
||||
activeToast.providerInstanceIds.has(provider.instanceId),
|
||||
);
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: activeProviders,
|
||||
providerCount: activeToast.providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId: activeToast.toastId,
|
||||
view,
|
||||
openSettings: () => openProviderSettings(activeToast.toastId),
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
}, [providers, openProviderSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
|
||||
if (
|
||||
!notificationKey ||
|
||||
dismissedNotificationKeys.has(notificationKey) ||
|
||||
seenProviderUpdateNotificationKeys.has(notificationKey) ||
|
||||
activeToastRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
seenProviderUpdateNotificationKeys.add(notificationKey);
|
||||
|
||||
const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
|
||||
|
||||
let toastId!: ProviderUpdateToastId;
|
||||
let updateStarted = false;
|
||||
const openSettings = () => openProviderSettings(toastId);
|
||||
const dismissPrompt = () => {
|
||||
dismissNotificationKey(notificationKey);
|
||||
};
|
||||
|
||||
const runUpdates = () => {
|
||||
if (updateStarted || oneClickProviders.length === 0) {
|
||||
return;
|
||||
}
|
||||
updateStarted = true;
|
||||
|
||||
const providerCount = oneClickProviders.length;
|
||||
const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
|
||||
activeToastRef.current = {
|
||||
kind: "update",
|
||||
key: notificationKey,
|
||||
toastId,
|
||||
providerInstanceIds,
|
||||
providerCount,
|
||||
};
|
||||
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRunningToastView(providerCount),
|
||||
openSettings,
|
||||
});
|
||||
|
||||
void Promise.allSettled(
|
||||
oneClickProviders.map(async (provider) =>
|
||||
ensureLocalApi().server.updateProvider({
|
||||
provider: provider.driver,
|
||||
instanceId: provider.instanceId,
|
||||
}),
|
||||
),
|
||||
).then((results) => {
|
||||
const activeUpdateToast = activeToastRef.current;
|
||||
if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rejectedMessage = firstRejectedProviderUpdateMessage(results);
|
||||
if (rejectedMessage) {
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRejectedToastView(providerCount, rejectedMessage),
|
||||
openSettings,
|
||||
});
|
||||
activeToastRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedProviderSnapshots = collectUpdatedProviderSnapshots({
|
||||
results,
|
||||
providerInstanceIds,
|
||||
});
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: updatedProviderSnapshots,
|
||||
providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view,
|
||||
openSettings,
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
toastId = toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: initialView.type,
|
||||
title: initialView.title,
|
||||
description: initialView.description,
|
||||
timeout: 0,
|
||||
actionProps:
|
||||
oneClickProviders.length > 0
|
||||
? {
|
||||
children: "Update",
|
||||
onClick: runUpdates,
|
||||
}
|
||||
: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
|
||||
data: {
|
||||
leadingIcon:
|
||||
updateProviders.length === 1 ? (
|
||||
<ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
|
||||
) : undefined,
|
||||
hideCopyButton: true,
|
||||
onClose: dismissPrompt,
|
||||
...(oneClickProviders.length > 0
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
secondaryActionVariant: "outline" as const,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
|
||||
}, [
|
||||
dismissNotificationKey,
|
||||
dismissedNotificationKeys,
|
||||
notificationKey,
|
||||
oneClickProviders,
|
||||
openProviderSettings,
|
||||
updateProviders,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -186,6 +186,7 @@ import {
|
||||
type SidebarProjectGroupMember,
|
||||
type SidebarProjectSnapshot,
|
||||
} from "../sidebarProjectGrouping";
|
||||
import { SidebarProviderUpdatePill } from "./sidebar/SidebarProviderUpdatePill";
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
|
||||
updated_at: "Last user message",
|
||||
@@ -2435,6 +2436,7 @@ const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
|
||||
return (
|
||||
<SidebarFooter className="p-2">
|
||||
<SidebarProviderUpdatePill />
|
||||
<SidebarUpdatePill />
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
|
||||
@@ -382,6 +382,60 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
expect(repeated.result).toBe(initial.result);
|
||||
});
|
||||
|
||||
it("reuses work rows when equivalent timeline derivations create new grouped arrays", () => {
|
||||
const firstWorkEntry = {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
label: "thinking",
|
||||
detail: "Inspecting repository state",
|
||||
tone: "thinking" as const,
|
||||
};
|
||||
const secondWorkEntry = {
|
||||
id: "work-2",
|
||||
createdAt: "2026-01-01T00:00:01Z",
|
||||
label: "read",
|
||||
detail: "Reading package.json",
|
||||
tone: "tool" as const,
|
||||
};
|
||||
|
||||
const createRows = () =>
|
||||
deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "entry-work-1",
|
||||
kind: "work",
|
||||
createdAt: firstWorkEntry.createdAt,
|
||||
entry: firstWorkEntry,
|
||||
},
|
||||
{
|
||||
id: "entry-work-2",
|
||||
kind: "work",
|
||||
createdAt: secondWorkEntry.createdAt,
|
||||
entry: secondWorkEntry,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const firstRows = createRows();
|
||||
const initial = computeStableMessagesTimelineRows(firstRows, {
|
||||
byId: new Map(),
|
||||
result: [],
|
||||
});
|
||||
const secondRows = createRows();
|
||||
|
||||
expect(secondRows[0]).not.toBe(firstRows[0]);
|
||||
|
||||
const repeated = computeStableMessagesTimelineRows(secondRows, initial);
|
||||
|
||||
expect(repeated).toBe(initial);
|
||||
expect(repeated.result[0]).toBe(initial.result[0]);
|
||||
});
|
||||
|
||||
it("returns a new result when row order changes without content changes", () => {
|
||||
const firstUserMessage = {
|
||||
id: "user-1" as never,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Equal from "effect/Equal";
|
||||
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
@@ -223,7 +224,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
case "work":
|
||||
return a.groupedEntries === (b as typeof a).groupedEntries;
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
case "message": {
|
||||
const bm = b as typeof a;
|
||||
|
||||
@@ -83,11 +83,6 @@ import { FileDiff } from "@pierre/diffs/react";
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface TimelineRowSharedState {
|
||||
activeTurnInProgress: boolean;
|
||||
activeTurnId: TurnId | null | undefined;
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
completionSummary: string | null;
|
||||
timestampFormat: TimestampFormat;
|
||||
routeThreadKey: string;
|
||||
markdownCwd: string | undefined;
|
||||
@@ -99,7 +94,16 @@ interface TimelineRowSharedState {
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
activeTurnInProgress: boolean;
|
||||
activeTurnId: TurnId | null;
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
completionSummary: string | null;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
|
||||
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
|
||||
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
|
||||
const REVIEW_COMMENT_DIFF_UNSAFE_CSS = `
|
||||
@@ -226,15 +230,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
};
|
||||
}, [listRef, onIsAtEndChange, rows.length]);
|
||||
|
||||
// Memoised context value — only changes on state transitions, NOT on
|
||||
// every streaming chunk. Callbacks from ChatView are useCallback-stable.
|
||||
const sharedState = useMemo<TimelineRowSharedState>(
|
||||
() => ({
|
||||
activeTurnInProgress,
|
||||
activeTurnId: activeTurnId ?? null,
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
completionSummary,
|
||||
timestampFormat,
|
||||
routeThreadKey,
|
||||
markdownCwd,
|
||||
@@ -246,11 +243,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onOpenTurnDiff,
|
||||
}),
|
||||
[
|
||||
activeTurnInProgress,
|
||||
activeTurnId,
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
completionSummary,
|
||||
timestampFormat,
|
||||
routeThreadKey,
|
||||
markdownCwd,
|
||||
@@ -262,12 +254,22 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onOpenTurnDiff,
|
||||
],
|
||||
);
|
||||
const activityState = useMemo<TimelineRowActivityState>(
|
||||
() => ({
|
||||
activeTurnInProgress,
|
||||
activeTurnId: activeTurnId ?? null,
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
completionSummary,
|
||||
}),
|
||||
[activeTurnInProgress, activeTurnId, completionSummary, isRevertingCheckpoint, isWorking],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
// from TimelineRowCtx, which propagates through LegendList's memo.
|
||||
const renderItem = useCallback(
|
||||
({ item }: { item: MessagesTimelineRow }) => (
|
||||
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden" data-timeline-root="true">
|
||||
<div className="mx-auto w-full min-w-0 max-w-3xl overflow-x-clip" data-timeline-root="true">
|
||||
<TimelineRowContent row={item} />
|
||||
</div>
|
||||
),
|
||||
@@ -286,21 +288,23 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
return (
|
||||
<TimelineRowCtx.Provider value={sharedState}>
|
||||
<LegendList<MessagesTimelineRow>
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
keyExtractor={keyExtractor}
|
||||
renderItem={renderItem}
|
||||
estimatedItemSize={90}
|
||||
initialScrollAtEnd
|
||||
maintainScrollAtEnd
|
||||
maintainScrollAtEndThreshold={0.1}
|
||||
maintainVisibleContentPosition
|
||||
onScroll={handleScroll}
|
||||
className="h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
<TimelineRowActivityCtx.Provider value={activityState}>
|
||||
<LegendList<MessagesTimelineRow>
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
keyExtractor={keyExtractor}
|
||||
renderItem={renderItem}
|
||||
estimatedItemSize={90}
|
||||
initialScrollAtEnd
|
||||
maintainScrollAtEnd
|
||||
maintainScrollAtEndThreshold={0.1}
|
||||
maintainVisibleContentPosition
|
||||
onScroll={handleScroll}
|
||||
className="h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
</TimelineRowActivityCtx.Provider>
|
||||
</TimelineRowCtx.Provider>
|
||||
);
|
||||
});
|
||||
@@ -318,9 +322,7 @@ type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
|
||||
type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
|
||||
type TimelineRow = MessagesTimelineRow;
|
||||
|
||||
function TimelineRowContent({ row }: { row: TimelineRow }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
|
||||
const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: TimelineRow }) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
@@ -332,195 +334,229 @@ function TimelineRowContent({ row }: { row: TimelineRow }) {
|
||||
data-message-id={row.kind === "message" ? row.message.id : undefined}
|
||||
data-message-role={row.kind === "message" ? row.message.role : undefined}
|
||||
>
|
||||
{row.kind === "work" && <WorkGroupSection groupedEntries={row.groupedEntries} />}
|
||||
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
|
||||
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "assistant" ? (
|
||||
<AssistantTimelineRow row={row} />
|
||||
) : null}
|
||||
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
|
||||
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
{row.kind === "message" &&
|
||||
row.message.role === "user" &&
|
||||
(() => {
|
||||
const userImages = row.message.attachments ?? [];
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
|
||||
const terminalContexts = displayedUserMessage.contexts;
|
||||
const hasReviewCommentContext =
|
||||
displayedUserMessage.visibleText.includes("<review_comment");
|
||||
const canRevertAgentWork = typeof row.revertTurnCount === "number";
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const userImages = row.message.attachments ?? [];
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
|
||||
const terminalContexts = displayedUserMessage.contexts;
|
||||
const hasReviewCommentContext = displayedUserMessage.visibleText.includes("<review_comment");
|
||||
const canRevertAgentWork = typeof row.revertTurnCount === "number";
|
||||
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
<div
|
||||
className={cn(
|
||||
"group relative rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3",
|
||||
hasReviewCommentContext ? "w-full max-w-[min(56rem,100%)]" : "max-w-[80%]",
|
||||
)}
|
||||
>
|
||||
{userImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{userImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3",
|
||||
hasReviewCommentContext ? "w-full max-w-[min(56rem,100%)]" : "max-w-[80%]",
|
||||
)}
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
>
|
||||
{userImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{userImages.map(
|
||||
(image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(userImages, image.id);
|
||||
if (!preview) return;
|
||||
ctx.onImageExpand(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="block h-auto max-h-[220px] w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(userImages, image.id);
|
||||
if (!preview) return;
|
||||
ctx.onImageExpand(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="block h-auto max-h-[220px] w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{(displayedUserMessage.visibleText.trim().length > 0 ||
|
||||
terminalContexts.length > 0) && (
|
||||
<UserMessageBody
|
||||
text={displayedUserMessage.visibleText}
|
||||
terminalContexts={terminalContexts}
|
||||
resolvedTheme={ctx.resolvedTheme}
|
||||
/>
|
||||
)}
|
||||
<div className="mt-1.5 flex items-center justify-end gap-2">
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
{displayedUserMessage.copyText && (
|
||||
<MessageCopyButton text={displayedUserMessage.copyText} />
|
||||
)}
|
||||
{canRevertAgentWork && (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={ctx.isRevertingCheckpoint || ctx.isWorking}
|
||||
onClick={() => ctx.onRevertUserMessage(row.message.id)}
|
||||
title="Revert to this message"
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-right text-xs text-muted-foreground/50">
|
||||
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "message" &&
|
||||
row.message.role === "assistant" &&
|
||||
(() => {
|
||||
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
|
||||
const assistantTurnStillInProgress =
|
||||
ctx.activeTurnInProgress &&
|
||||
ctx.activeTurnId !== null &&
|
||||
ctx.activeTurnId !== undefined &&
|
||||
row.message.turnId === ctx.activeTurnId;
|
||||
const assistantCopyState = resolveAssistantMessageCopyState({
|
||||
text: row.message.text ?? null,
|
||||
showCopyButton: row.showAssistantCopyButton,
|
||||
streaming: row.message.streaming || assistantTurnStillInProgress,
|
||||
});
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||
{ctx.completionSummary ? `Response • ${ctx.completionSummary}` : "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={ctx.markdownCwd}
|
||||
isStreaming={Boolean(row.message.streaming)}
|
||||
/>
|
||||
<AssistantChangedFilesSection
|
||||
turnSummary={row.assistantTurnDiffSummary}
|
||||
routeThreadKey={ctx.routeThreadKey}
|
||||
resolvedTheme={ctx.resolvedTheme}
|
||||
onOpenTurnDiff={ctx.onOpenTurnDiff}
|
||||
/>
|
||||
<div className="mt-1.5 flex items-center gap-2">
|
||||
<p className="text-[10px] text-muted-foreground/30">
|
||||
{row.message.streaming ? (
|
||||
<LiveMessageMeta
|
||||
createdAt={row.message.createdAt}
|
||||
durationStart={row.durationStart}
|
||||
timestampFormat={ctx.timestampFormat}
|
||||
/>
|
||||
) : (
|
||||
formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
formatElapsed(row.durationStart, row.message.completedAt),
|
||||
ctx.timestampFormat,
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
{assistantCopyState.visible ? (
|
||||
<div className="flex items-center opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
|
||||
<MessageCopyButton
|
||||
text={assistantCopyState.text ?? ""}
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "proposed-plan" && (
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ProposedPlanCard
|
||||
planMarkdown={row.proposedPlan.planMarkdown}
|
||||
environmentId={ctx.activeThreadEnvironmentId}
|
||||
cwd={ctx.markdownCwd}
|
||||
workspaceRoot={ctx.workspaceRoot}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{row.kind === "working" && (
|
||||
<div className="py-0.5 pl-1.5">
|
||||
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
<span>
|
||||
{row.createdAt ? (
|
||||
<>
|
||||
Working for <WorkingTimer createdAt={row.createdAt} />
|
||||
</>
|
||||
) : (
|
||||
"Working..."
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{(displayedUserMessage.visibleText.trim().length > 0 || terminalContexts.length > 0) && (
|
||||
<UserMessageBody
|
||||
text={displayedUserMessage.visibleText}
|
||||
terminalContexts={terminalContexts}
|
||||
resolvedTheme={ctx.resolvedTheme}
|
||||
/>
|
||||
)}
|
||||
<div className="mt-1.5 flex items-center justify-end gap-2">
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
{displayedUserMessage.copyText && (
|
||||
<MessageCopyButton text={displayedUserMessage.copyText} />
|
||||
)}
|
||||
{canRevertAgentWork && <RevertUserMessageButton messageId={row.message.id} />}
|
||||
</div>
|
||||
<p className="text-right text-xs text-muted-foreground/50">
|
||||
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={activity.isRevertingCheckpoint || activity.isWorking}
|
||||
onClick={() => ctx.onRevertUserMessage(messageId)}
|
||||
title="Revert to this message"
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
|
||||
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && <AssistantCompletionDivider />}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={ctx.markdownCwd}
|
||||
isStreaming={Boolean(row.message.streaming)}
|
||||
/>
|
||||
<AssistantChangedFilesSection
|
||||
turnSummary={row.assistantTurnDiffSummary}
|
||||
routeThreadKey={ctx.routeThreadKey}
|
||||
resolvedTheme={ctx.resolvedTheme}
|
||||
onOpenTurnDiff={ctx.onOpenTurnDiff}
|
||||
/>
|
||||
<div className="mt-1.5 flex items-center gap-2">
|
||||
<p className="text-[10px] text-muted-foreground/30">
|
||||
{row.message.streaming ? (
|
||||
<LiveMessageMeta
|
||||
createdAt={row.message.createdAt}
|
||||
durationStart={row.durationStart}
|
||||
timestampFormat={ctx.timestampFormat}
|
||||
/>
|
||||
) : (
|
||||
formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
formatElapsed(row.durationStart, row.message.completedAt),
|
||||
ctx.timestampFormat,
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
<AssistantCopyButton row={row} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantCompletionDivider() {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
|
||||
return (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||
{activity.completionSummary ? `Response • ${activity.completionSummary}` : "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantCopyButton({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const assistantTurnStillInProgress =
|
||||
activity.activeTurnInProgress &&
|
||||
activity.activeTurnId !== null &&
|
||||
row.message.turnId === activity.activeTurnId;
|
||||
const assistantCopyState = resolveAssistantMessageCopyState({
|
||||
text: row.message.text ?? null,
|
||||
showCopyButton: row.showAssistantCopyButton,
|
||||
streaming: row.message.streaming || assistantTurnStillInProgress,
|
||||
});
|
||||
|
||||
if (!assistantCopyState.visible) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
|
||||
<MessageCopyButton
|
||||
text={assistantCopyState.text ?? ""}
|
||||
size="icon-xs"
|
||||
variant="outline"
|
||||
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProposedPlanTimelineRow({
|
||||
row,
|
||||
}: {
|
||||
row: Extract<TimelineRow, { kind: "proposed-plan" }>;
|
||||
}) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
|
||||
return (
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ProposedPlanCard
|
||||
planMarkdown={row.proposedPlan.planMarkdown}
|
||||
environmentId={ctx.activeThreadEnvironmentId}
|
||||
cwd={ctx.markdownCwd}
|
||||
workspaceRoot={ctx.workspaceRoot}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
|
||||
return (
|
||||
<div className="py-0.5 pl-1.5">
|
||||
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
<span>
|
||||
{row.createdAt ? (
|
||||
<>
|
||||
Working for <WorkingTimer createdAt={row.createdAt} />
|
||||
</>
|
||||
) : (
|
||||
"Working..."
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -669,7 +705,7 @@ function AssistantChangedFilesSectionInner({
|
||||
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
<div className="sticky top-2 z-10 mb-1.5 flex items-center justify-between gap-2 bg-background before:absolute before:inset-x-0 before:-top-2 before:h-2 before:bg-background before:content-['']">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
|
||||
@@ -12,12 +12,25 @@ import {
|
||||
Icon,
|
||||
KiroIcon,
|
||||
TraeIcon,
|
||||
IntelliJIdeaIcon,
|
||||
VisualStudioCode,
|
||||
VisualStudioCodeInsiders,
|
||||
VSCodium,
|
||||
Zed,
|
||||
} from "../Icons";
|
||||
import {
|
||||
AquaIcon,
|
||||
CLionIcon,
|
||||
DataGripIcon,
|
||||
DataSpellIcon,
|
||||
GoLandIcon,
|
||||
IntelliJIdeaIcon,
|
||||
PhpStormIcon,
|
||||
PyCharmIcon,
|
||||
RiderIcon,
|
||||
RubyMineIcon,
|
||||
RustRoverIcon,
|
||||
WebStormIcon,
|
||||
} from "../JetBrainsIcons";
|
||||
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
|
||||
@@ -68,6 +81,61 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: IntelliJIdeaIcon,
|
||||
value: "idea",
|
||||
},
|
||||
{
|
||||
label: "Aqua",
|
||||
Icon: AquaIcon,
|
||||
value: "aqua",
|
||||
},
|
||||
{
|
||||
label: "CLion",
|
||||
Icon: CLionIcon,
|
||||
value: "clion",
|
||||
},
|
||||
{
|
||||
label: "DataGrip",
|
||||
Icon: DataGripIcon,
|
||||
value: "datagrip",
|
||||
},
|
||||
{
|
||||
label: "DataSpell",
|
||||
Icon: DataSpellIcon,
|
||||
value: "dataspell",
|
||||
},
|
||||
{
|
||||
label: "GoLand",
|
||||
Icon: GoLandIcon,
|
||||
value: "goland",
|
||||
},
|
||||
{
|
||||
label: "PhpStorm",
|
||||
Icon: PhpStormIcon,
|
||||
value: "phpstorm",
|
||||
},
|
||||
{
|
||||
label: "PyCharm",
|
||||
Icon: PyCharmIcon,
|
||||
value: "pycharm",
|
||||
},
|
||||
{
|
||||
label: "Rider",
|
||||
Icon: RiderIcon,
|
||||
value: "rider",
|
||||
},
|
||||
{
|
||||
label: "RubyMine",
|
||||
Icon: RubyMineIcon,
|
||||
value: "rubymine",
|
||||
},
|
||||
{
|
||||
label: "RustRover",
|
||||
Icon: RustRoverIcon,
|
||||
value: "rustrover",
|
||||
},
|
||||
{
|
||||
label: "WebStorm",
|
||||
Icon: WebStormIcon,
|
||||
value: "webstorm",
|
||||
},
|
||||
{
|
||||
label: isMacPlatform(platform)
|
||||
? "Finder"
|
||||
|
||||
@@ -0,0 +1,982 @@
|
||||
import {
|
||||
AlertTriangleIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
CopyIcon,
|
||||
FolderOpenIcon,
|
||||
InfoIcon,
|
||||
RefreshCwIcon,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import type { ServerProcessDiagnosticsEntry, ServerProcessSignal } from "@t3tools/contracts";
|
||||
import { DateTime, Option } from "effect";
|
||||
|
||||
import { ensureLocalApi } from "../../localApi";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
|
||||
import { formatRelativeTime } from "../../timestampFormat";
|
||||
import { useServerAvailableEditors, useServerObservability } from "../../rpc/serverState";
|
||||
import { useProcessDiagnostics } from "../../lib/processDiagnosticsState";
|
||||
import { useTraceDiagnostics } from "../../lib/traceDiagnosticsState";
|
||||
import { Button } from "../ui/button";
|
||||
import { ScrollArea } from "../ui/scroll-area";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
|
||||
|
||||
const NUMBER_FORMAT = new Intl.NumberFormat();
|
||||
|
||||
function formatCount(value: number): string {
|
||||
return NUMBER_FORMAT.format(value);
|
||||
}
|
||||
|
||||
function formatDuration(value: number): string {
|
||||
if (value < 1_000) return `${Math.round(value)} ms`;
|
||||
return `${(value / 1_000).toFixed(value >= 10_000 ? 1 : 2)} s`;
|
||||
}
|
||||
|
||||
function formatBytes(value: number): string {
|
||||
if (value < 1024) return `${value} B`;
|
||||
const units = ["KB", "MB", "GB"] as const;
|
||||
let unitIndex = -1;
|
||||
let next = value;
|
||||
do {
|
||||
next /= 1024;
|
||||
unitIndex += 1;
|
||||
} while (next >= 1024 && unitIndex < units.length - 1);
|
||||
return `${next.toFixed(next >= 10 ? 1 : 2)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
function formatRelative(value: DateTime.Utc | null): string {
|
||||
if (!value) return "No trace records";
|
||||
const relative = formatRelativeTime(DateTime.formatIso(value));
|
||||
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
|
||||
}
|
||||
|
||||
function formatRelativeNoWrap(value: DateTime.Utc | null): string {
|
||||
return formatRelative(value).replaceAll(" ", "\u00a0");
|
||||
}
|
||||
|
||||
function shortenTraceId(traceId: string): string {
|
||||
if (traceId.length <= 32) return traceId;
|
||||
return `${traceId.slice(0, 18)}...${traceId.slice(-10)}`;
|
||||
}
|
||||
|
||||
function isStaleProcessSignalMessage(message: string | undefined): boolean {
|
||||
return message?.includes("not a live descendant") ?? false;
|
||||
}
|
||||
|
||||
function StatBlock({
|
||||
label,
|
||||
value,
|
||||
tooltip,
|
||||
tone = "default",
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
tooltip?: ReactNode;
|
||||
tone?: "default" | "warning" | "danger";
|
||||
}) {
|
||||
return (
|
||||
<div className="min-w-0 border-border/60 px-4 py-3 sm:px-5">
|
||||
<div className="flex min-w-0 items-center gap-1.5 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
<span className="min-w-0 truncate">{label}</span>
|
||||
{tooltip ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-sm text-muted-foreground/60 hover:text-foreground"
|
||||
aria-label={`${label} details`}
|
||||
>
|
||||
<InfoIcon className="size-3" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(300px,calc(100vw-2rem))] whitespace-normal text-left text-[11px] leading-relaxed text-wrap"
|
||||
>
|
||||
{tooltip}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"mt-1 truncate font-mono text-lg font-semibold tabular-nums text-foreground",
|
||||
tone === "warning" && "text-amber-600 dark:text-amber-400",
|
||||
tone === "danger" && "text-destructive",
|
||||
)}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatsGrid({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="relative grid grid-cols-2 sm:grid-cols-4">
|
||||
<span
|
||||
className="pointer-events-none absolute inset-y-0 left-1/2 w-px bg-border/60"
|
||||
aria-hidden
|
||||
/>
|
||||
<span
|
||||
className="pointer-events-none absolute inset-x-0 top-1/2 h-px bg-border/60 sm:hidden"
|
||||
aria-hidden
|
||||
/>
|
||||
<span
|
||||
className="pointer-events-none absolute inset-y-0 left-1/4 hidden w-px bg-border/60 sm:block"
|
||||
aria-hidden
|
||||
/>
|
||||
<span
|
||||
className="pointer-events-none absolute inset-y-0 left-3/4 hidden w-px bg-border/60 sm:block"
|
||||
aria-hidden
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyRows({ label }: { label: string }) {
|
||||
return <div className="px-4 py-4 text-xs text-muted-foreground sm:px-5">{label}</div>;
|
||||
}
|
||||
|
||||
function ExpandableText({
|
||||
text,
|
||||
className,
|
||||
collapsedClassName = "line-clamp-3",
|
||||
expandLabel = "Show full error",
|
||||
}: {
|
||||
text: string;
|
||||
className?: string;
|
||||
collapsedClassName?: string;
|
||||
expandLabel?: string;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const canExpand = text.length > 180 || text.includes("\n");
|
||||
|
||||
return (
|
||||
<div className={cn("min-w-0", className)}>
|
||||
<div
|
||||
className={cn(
|
||||
"whitespace-pre-wrap break-words",
|
||||
!expanded && canExpand ? collapsedClassName : null,
|
||||
)}
|
||||
>
|
||||
{text}
|
||||
</div>
|
||||
{canExpand ? (
|
||||
<button
|
||||
type="button"
|
||||
className="mt-1 text-[11px] font-medium text-foreground/70 underline-offset-2 hover:text-foreground hover:underline"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded ? "Show less" : expandLabel}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DiagnosticsTable({
|
||||
headers,
|
||||
children,
|
||||
minTableWidth = "min-w-[640px]",
|
||||
columnWidths,
|
||||
}: {
|
||||
headers: ReadonlyArray<string>;
|
||||
children: ReactNode;
|
||||
minTableWidth?: string;
|
||||
columnWidths?: ReadonlyArray<string>;
|
||||
}) {
|
||||
return (
|
||||
<ScrollArea
|
||||
chainVerticalScroll
|
||||
scrollFade
|
||||
hideScrollbars
|
||||
className="w-full max-w-full rounded-none"
|
||||
>
|
||||
<table
|
||||
className={cn("w-full text-left text-xs", minTableWidth, columnWidths && "table-fixed")}
|
||||
>
|
||||
{columnWidths ? (
|
||||
<colgroup>
|
||||
{headers.map((header, index) => (
|
||||
<col key={header} className={columnWidths[index]} />
|
||||
))}
|
||||
</colgroup>
|
||||
) : null}
|
||||
<thead className="border-b border-border/60 text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
<tr>
|
||||
{headers.map((header, index) => (
|
||||
<th
|
||||
key={header}
|
||||
className={cn(
|
||||
"whitespace-nowrap px-4 py-2.5 font-semibold first:sm:pl-5 last:sm:pr-5",
|
||||
!columnWidths && index === headers.length - 1 && "w-px",
|
||||
)}
|
||||
>
|
||||
{header.replaceAll(" ", "\u00a0")}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/60">{children}</tbody>
|
||||
</table>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
function TraceIdCell({ traceId }: { traceId: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copyTraceId = useCallback(() => {
|
||||
void navigator.clipboard
|
||||
?.writeText(traceId)
|
||||
.then(() => {
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1_200);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [traceId]);
|
||||
|
||||
return (
|
||||
<div className="flex w-full min-w-0 max-w-full items-center gap-2">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[11px]">
|
||||
{shortenTraceId(traceId)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(520px,calc(100vw-2rem))] break-all font-mono text-[11px]"
|
||||
>
|
||||
{traceId}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label={copied ? "Copied trace ID" : "Copy trace ID"}
|
||||
onClick={copyTraceId}
|
||||
>
|
||||
<CopyIcon className="size-3" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{copied ? "Copied" : "Copy full trace ID"}</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatProcessName(command: string): string {
|
||||
const firstToken = command.trim().split(/\s+/)[0];
|
||||
if (!firstToken) return command;
|
||||
const normalized = firstToken.replace(/^['"]|['"]$/g, "");
|
||||
const segments = normalized.split(/[\\/]/).filter(Boolean);
|
||||
return segments.at(-1) ?? normalized;
|
||||
}
|
||||
|
||||
function formatProcessType(process: ServerProcessDiagnosticsEntry): string {
|
||||
if (process.depth > 0) return "Subprocess";
|
||||
if (/\b(codex|claude|opencode|cursor)\b/i.test(process.command)) return "Agent";
|
||||
return "Process";
|
||||
}
|
||||
|
||||
function ProcessNameCell({
|
||||
process,
|
||||
isExpanded,
|
||||
onToggle,
|
||||
}: {
|
||||
process: ServerProcessDiagnosticsEntry;
|
||||
isExpanded: boolean;
|
||||
onToggle: (pid: number) => void;
|
||||
}) {
|
||||
const name = formatProcessName(process.command);
|
||||
const hasChildren = process.childPids.length > 0;
|
||||
const ChevronIcon = isExpanded ? ChevronDownIcon : ChevronRightIcon;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="grid min-w-0 grid-cols-[1.25rem_0.375rem_minmax(0,1fr)] items-center gap-2"
|
||||
style={{ paddingLeft: `${Math.min(process.depth, 8) * 16}px` }}
|
||||
>
|
||||
{hasChildren ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-5 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
aria-label={isExpanded ? `Collapse ${name}` : `Expand ${name}`}
|
||||
onClick={() => onToggle(process.pid)}
|
||||
>
|
||||
<ChevronIcon className="size-3.5" />
|
||||
</button>
|
||||
) : (
|
||||
<span className="size-5 shrink-0" aria-hidden="true" />
|
||||
)}
|
||||
<span className="size-1.5 shrink-0 rounded-full bg-emerald-500/80" />
|
||||
<span className="min-w-0 truncate font-medium text-foreground">{name}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessSignalActions({
|
||||
process,
|
||||
isSignaling,
|
||||
onSignal,
|
||||
}: {
|
||||
process: ServerProcessDiagnosticsEntry;
|
||||
isSignaling: boolean;
|
||||
onSignal: (pid: number, signal: ServerProcessSignal) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
disabled={isSignaling}
|
||||
className="text-[11px] font-medium text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:pointer-events-none disabled:opacity-50"
|
||||
onClick={() => onSignal(process.pid, "SIGINT")}
|
||||
>
|
||||
INT
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Send SIGINT</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
disabled={isSignaling}
|
||||
className="text-[11px] font-medium text-destructive underline-offset-2 hover:underline disabled:pointer-events-none disabled:opacity-50"
|
||||
onClick={() => onSignal(process.pid, "SIGKILL")}
|
||||
>
|
||||
KILL
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Send SIGKILL</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessDiagnosticsTable({
|
||||
processes,
|
||||
signalingPid,
|
||||
onSignal,
|
||||
emptyLabel,
|
||||
}: {
|
||||
processes: ReadonlyArray<ServerProcessDiagnosticsEntry>;
|
||||
signalingPid: number | null;
|
||||
onSignal: (pid: number, signal: ServerProcessSignal) => void;
|
||||
emptyLabel?: string;
|
||||
}) {
|
||||
const [collapsedPids, setCollapsedPids] = useState<ReadonlySet<number>>(() => new Set());
|
||||
const visibleProcesses = useMemo(() => {
|
||||
const visible: ServerProcessDiagnosticsEntry[] = [];
|
||||
let hiddenChildDepth: number | null = null;
|
||||
|
||||
for (const process of processes) {
|
||||
if (hiddenChildDepth !== null) {
|
||||
if (process.depth > hiddenChildDepth) continue;
|
||||
hiddenChildDepth = null;
|
||||
}
|
||||
|
||||
visible.push(process);
|
||||
if (collapsedPids.has(process.pid)) {
|
||||
hiddenChildDepth = process.depth;
|
||||
}
|
||||
}
|
||||
|
||||
return visible;
|
||||
}, [collapsedPids, processes]);
|
||||
|
||||
const toggleProcess = useCallback((pid: number) => {
|
||||
setCollapsedPids((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (next.has(pid)) {
|
||||
next.delete(pid);
|
||||
} else {
|
||||
next.add(pid);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ScrollArea
|
||||
chainVerticalScroll
|
||||
scrollFade
|
||||
hideScrollbars
|
||||
className="w-full max-w-full rounded-none border-t border-border/60"
|
||||
>
|
||||
<table className="w-full min-w-[1040px] table-fixed text-left text-xs">
|
||||
<colgroup>
|
||||
<col className="w-[24%]" />
|
||||
<col className="w-[8%]" />
|
||||
<col className="w-[10%]" />
|
||||
<col className="w-[33%]" />
|
||||
<col className="w-[8%]" />
|
||||
<col className="w-[11%]" />
|
||||
<col className="w-[6%]" />
|
||||
</colgroup>
|
||||
<thead className="border-b border-border/60 bg-muted/15 text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
<tr>
|
||||
<th className="px-4 py-2 font-semibold sm:pl-5">Name</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">CPU</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">Memory</th>
|
||||
<th className="px-3 py-2 font-semibold">Command</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">PID</th>
|
||||
<th className="px-3 py-2 font-semibold">Type</th>
|
||||
<th className="px-2 py-2 text-right font-semibold sm:pr-4">Kill</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/50">
|
||||
{visibleProcesses.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="px-4 py-4 text-xs text-muted-foreground sm:px-5">
|
||||
{emptyLabel ?? "No live descendant processes found."}
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{visibleProcesses.map((process) => (
|
||||
<tr key={process.pid} className="hover:bg-muted/20">
|
||||
<td className="px-4 py-2 align-middle sm:pl-5">
|
||||
<ProcessNameCell
|
||||
process={process}
|
||||
isExpanded={!collapsedPids.has(process.pid)}
|
||||
onToggle={toggleProcess}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
|
||||
{process.cpuPercent.toFixed(1)}%
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums">
|
||||
{formatBytes(process.rssBytes)}
|
||||
</td>
|
||||
<td className="px-3 py-2 align-middle text-muted-foreground">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={<span className="block truncate">{process.command}</span>}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-[min(440px,calc(100vw-2rem))] whitespace-normal break-words text-left font-mono text-[11px] leading-relaxed text-wrap"
|
||||
>
|
||||
{process.command}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right align-middle font-mono tabular-nums text-muted-foreground">
|
||||
{process.pid}
|
||||
</td>
|
||||
<td className="truncate px-3 py-2 align-middle text-muted-foreground">
|
||||
{formatProcessType(process)}
|
||||
</td>
|
||||
<td className="px-2 py-2 align-middle sm:pr-4">
|
||||
<ProcessSignalActions
|
||||
process={process}
|
||||
isSignaling={signalingPid === process.pid}
|
||||
onSignal={onSignal}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
|
||||
useRelativeTimeTick();
|
||||
const relative = checkedAt ? formatRelativeTime(DateTime.formatIso(checkedAt)) : null;
|
||||
|
||||
if (!relative) {
|
||||
return <span className="text-[11px] text-muted-foreground/50">Checking</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
{relative.suffix ? (
|
||||
<>
|
||||
Checked <span className="font-mono tabular-nums">{relative.value}</span> {relative.suffix}
|
||||
</>
|
||||
) : (
|
||||
<>Checked {relative.value}</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function DiagnosticsRefreshButton({
|
||||
isPending,
|
||||
label,
|
||||
onClick,
|
||||
}: {
|
||||
isPending: boolean;
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
disabled={isPending}
|
||||
onClick={onClick}
|
||||
aria-label={label}
|
||||
>
|
||||
<RefreshCwIcon className={cn("size-3", isPending && "animate-spin")} />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{label}</TooltipPopup>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function DiagnosticsSettingsPanel() {
|
||||
const observability = useServerObservability();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const { data, error, isPending, refresh } = useTraceDiagnostics();
|
||||
const {
|
||||
data: processData,
|
||||
error: processError,
|
||||
isPending: isProcessPending,
|
||||
refresh: refreshProcesses,
|
||||
} = useProcessDiagnostics();
|
||||
const [isOpeningLogsDirectory, setIsOpeningLogsDirectory] = useState(false);
|
||||
const [openLogsDirectoryError, setOpenLogsDirectoryError] = useState<string | null>(null);
|
||||
const [signalingPid, setSignalingPid] = useState<number | null>(null);
|
||||
|
||||
const openLogsDirectory = useCallback(() => {
|
||||
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
|
||||
if (!logsDirectoryPath) return;
|
||||
|
||||
const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);
|
||||
if (!editor) {
|
||||
setOpenLogsDirectoryError("No available editors found.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsOpeningLogsDirectory(true);
|
||||
setOpenLogsDirectoryError(null);
|
||||
void ensureLocalApi()
|
||||
.shell.openInEditor(logsDirectoryPath, editor)
|
||||
.catch((error: unknown) => {
|
||||
setOpenLogsDirectoryError(
|
||||
error instanceof Error ? error.message : "Unable to open logs folder.",
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
setIsOpeningLogsDirectory(false);
|
||||
});
|
||||
}, [availableEditors, observability?.logsDirectoryPath]);
|
||||
|
||||
const isInitialLoading = isPending && data === null;
|
||||
const isProcessInitialLoading = isProcessPending && processData === null;
|
||||
const signalProcess = useCallback(
|
||||
(pid: number, signal: ServerProcessSignal) => {
|
||||
if (
|
||||
signal === "SIGKILL" &&
|
||||
!window.confirm(`Send SIGKILL to process ${pid}? This cannot be handled by the process.`)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSignalingPid(pid);
|
||||
void ensureLocalApi()
|
||||
.server.signalProcess({ pid, signal })
|
||||
.then((result) => {
|
||||
if (!result.signaled) {
|
||||
const message = Option.getOrUndefined(result.message);
|
||||
refreshProcesses();
|
||||
if (isStaleProcessSignalMessage(message)) {
|
||||
toastManager.add({
|
||||
type: "info",
|
||||
title: "Process already exited",
|
||||
description:
|
||||
"The process is not a child of the T3 Server. It might already have exited.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Could not send ${signal}`,
|
||||
description: message ?? `Failed to send ${signal}.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
refreshProcesses();
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Could not send ${signal}`,
|
||||
description: error instanceof Error ? error.message : `Failed to send ${signal}.`,
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
setSignalingPid(null);
|
||||
});
|
||||
},
|
||||
[refreshProcesses],
|
||||
);
|
||||
|
||||
const processDiagnosticsError = processData ? Option.getOrNull(processData.error) : null;
|
||||
const traceDiagnosticsError = data ? Option.getOrNull(data.error) : null;
|
||||
const traceDiagnosticsPartialFailure = data
|
||||
? Option.getOrElse(data.partialFailure, () => false)
|
||||
: false;
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection
|
||||
title="Live Processes"
|
||||
headerAction={
|
||||
<div className="flex items-center gap-1.5">
|
||||
<DiagnosticsLastChecked checkedAt={processData?.readAt ?? null} />
|
||||
<DiagnosticsRefreshButton
|
||||
isPending={isProcessPending}
|
||||
label="Refresh process diagnostics"
|
||||
onClick={refreshProcesses}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<StatsGrid>
|
||||
<StatBlock
|
||||
label="Child Processes"
|
||||
value={processData ? formatCount(processData.processCount) : "..."}
|
||||
/>
|
||||
<StatBlock
|
||||
label="CPU"
|
||||
value={processData ? `${processData.totalCpuPercent.toFixed(1)}%` : "..."}
|
||||
tooltip="Total CPU across live child processes of the current server process. The desktop shell and other parent processes are not included."
|
||||
/>
|
||||
<StatBlock
|
||||
label="Memory"
|
||||
value={processData ? formatBytes(processData.totalRssBytes) : "..."}
|
||||
tooltip="Total resident memory across live child processes of the current server process. The desktop shell and other parent processes are not included."
|
||||
/>
|
||||
<StatBlock
|
||||
label="Server PID"
|
||||
value={processData ? String(processData.serverPid) : "..."}
|
||||
/>
|
||||
</StatsGrid>
|
||||
{processDiagnosticsError || processError ? (
|
||||
<div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
|
||||
{processDiagnosticsError ? (
|
||||
<div className="flex items-start gap-2 text-destructive">
|
||||
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{processDiagnosticsError.message}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{processError ? (
|
||||
<div className="flex items-start gap-2 text-destructive">
|
||||
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{processError}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<ProcessDiagnosticsTable
|
||||
processes={processData?.processes ?? []}
|
||||
signalingPid={signalingPid}
|
||||
onSignal={signalProcess}
|
||||
emptyLabel={
|
||||
isProcessInitialLoading
|
||||
? "Loading live processes..."
|
||||
: "No live descendant processes found."
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="Trace Diagnostics"
|
||||
headerAction={
|
||||
<div className="flex items-center gap-1.5">
|
||||
<DiagnosticsLastChecked checkedAt={data?.readAt ?? null} />
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
disabled={!observability?.logsDirectoryPath || isOpeningLogsDirectory}
|
||||
onClick={openLogsDirectory}
|
||||
aria-label="Open logs folder"
|
||||
>
|
||||
<FolderOpenIcon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Open logs folder</TooltipPopup>
|
||||
</Tooltip>
|
||||
<DiagnosticsRefreshButton
|
||||
isPending={isPending}
|
||||
label="Refresh trace diagnostics"
|
||||
onClick={refresh}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<StatsGrid>
|
||||
<StatBlock label="Spans" value={data ? formatCount(data.recordCount) : "..."} />
|
||||
<StatBlock
|
||||
label="Failures"
|
||||
value={data ? formatCount(data.failureCount) : "..."}
|
||||
tone={data && data.failureCount > 0 ? "danger" : "default"}
|
||||
/>
|
||||
<StatBlock
|
||||
label="Slow Spans"
|
||||
value={data ? formatCount(data.slowSpanCount) : "..."}
|
||||
tooltip={
|
||||
data
|
||||
? `Spans with a duration of ${formatDuration(data.slowSpanThresholdMs)} or longer.`
|
||||
: "Spans at or above the configured slow-span threshold."
|
||||
}
|
||||
tone={data && data.slowSpanCount > 0 ? "warning" : "default"}
|
||||
/>
|
||||
<StatBlock
|
||||
label="Parse Errors"
|
||||
value={data ? formatCount(data.parseErrorCount) : "..."}
|
||||
tone={data && data.parseErrorCount > 0 ? "warning" : "default"}
|
||||
/>
|
||||
</StatsGrid>
|
||||
{openLogsDirectoryError || traceDiagnosticsError || error ? (
|
||||
<div className="space-y-2 border-t border-border/60 px-4 py-3 text-xs text-muted-foreground sm:px-5">
|
||||
{openLogsDirectoryError ? (
|
||||
<div className="flex items-start gap-2 text-destructive">
|
||||
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{openLogsDirectoryError}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{traceDiagnosticsError ? (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-start gap-2",
|
||||
traceDiagnosticsPartialFailure
|
||||
? "text-amber-600 dark:text-amber-400"
|
||||
: "text-destructive",
|
||||
)}
|
||||
>
|
||||
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>
|
||||
{traceDiagnosticsPartialFailure
|
||||
? `Some trace files could not be read, so diagnostics may be incomplete. ${traceDiagnosticsError.message}`
|
||||
: traceDiagnosticsError.message}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{error ? (
|
||||
<div className="flex items-start gap-2 text-destructive">
|
||||
<AlertTriangleIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Latest Failures">
|
||||
{data && data.latestFailures.length > 0 ? (
|
||||
<DiagnosticsTable headers={["Span", "Cause", "Duration", "Ended"]}>
|
||||
{data.latestFailures.map((failure) => (
|
||||
<tr key={`${failure.traceId}:${failure.spanId}`}>
|
||||
<td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
|
||||
{failure.name}
|
||||
</td>
|
||||
<td className="max-w-[360px] px-4 py-3 align-top text-muted-foreground">
|
||||
<ExpandableText text={failure.cause} />
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top font-mono tabular-nums">
|
||||
{formatDuration(failure.durationMs)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground last:sm:pr-5">
|
||||
{formatRelativeNoWrap(failure.endedAt)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</DiagnosticsTable>
|
||||
) : (
|
||||
<EmptyRows label={isInitialLoading ? "Loading failures..." : "No failed spans found."} />
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Most Common Failures">
|
||||
{data && data.commonFailures.length > 0 ? (
|
||||
<DiagnosticsTable
|
||||
headers={["Span", "Count", "Cause", "Last Seen"]}
|
||||
minTableWidth="min-w-[760px]"
|
||||
>
|
||||
{data.commonFailures.map((failure) => (
|
||||
<tr key={`${failure.name}:${failure.cause}`}>
|
||||
<td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
|
||||
{failure.name}
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top font-mono tabular-nums">
|
||||
{formatCount(failure.count)}
|
||||
</td>
|
||||
<td className="max-w-[360px] px-4 py-3 align-top text-muted-foreground">
|
||||
<ExpandableText text={failure.cause} />
|
||||
</td>
|
||||
<td className="w-px whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground last:sm:pr-5">
|
||||
{formatRelativeNoWrap(failure.lastSeenAt)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</DiagnosticsTable>
|
||||
) : (
|
||||
<EmptyRows
|
||||
label={isInitialLoading ? "Loading failure groups..." : "No repeated failures found."}
|
||||
/>
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Slowest Spans">
|
||||
{data && data.slowestSpans.length > 0 ? (
|
||||
<DiagnosticsTable
|
||||
headers={["Span", "Duration", "Ended", "Trace"]}
|
||||
minTableWidth="min-w-[900px]"
|
||||
columnWidths={["w-[44%]", "w-[14%]", "w-[12%]", "w-[30%]"]}
|
||||
>
|
||||
{data.slowestSpans.map((span) => (
|
||||
<tr key={`${span.traceId}:${span.spanId}`}>
|
||||
<td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
|
||||
{span.name}
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top font-mono tabular-nums">
|
||||
{formatDuration(span.durationMs)}
|
||||
</td>
|
||||
<td className="w-px whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground">
|
||||
{formatRelativeNoWrap(span.endedAt)}
|
||||
</td>
|
||||
<td className="min-w-0 whitespace-nowrap px-4 py-3 align-top text-muted-foreground last:sm:pr-5">
|
||||
<TraceIdCell traceId={span.traceId} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</DiagnosticsTable>
|
||||
) : (
|
||||
<EmptyRows label={isInitialLoading ? "Loading slow spans..." : "No spans found."} />
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Span Logs">
|
||||
{data && data.latestWarningAndErrorLogs.length > 0 ? (
|
||||
<ScrollArea
|
||||
chainVerticalScroll
|
||||
scrollFade
|
||||
hideScrollbars
|
||||
className="w-full max-w-full rounded-none"
|
||||
>
|
||||
<table className="w-full min-w-[920px] table-fixed text-left text-xs">
|
||||
<colgroup>
|
||||
<col className="w-[11%]" />
|
||||
<col className="w-[9%]" />
|
||||
<col className="w-[24%]" />
|
||||
<col className="w-[26%]" />
|
||||
<col className="w-[30%]" />
|
||||
</colgroup>
|
||||
<thead className="border-b border-border/60 text-[11px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
<tr>
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-semibold sm:pl-5">Time</th>
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-semibold">Level</th>
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-semibold">Span</th>
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-semibold">Message</th>
|
||||
<th className="whitespace-nowrap px-4 py-2.5 font-semibold sm:pr-5">Trace</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/60">
|
||||
{data.latestWarningAndErrorLogs.map((event) => (
|
||||
<tr
|
||||
key={`${event.traceId}:${event.spanId}:${DateTime.formatIso(event.seenAt)}:${event.message}`}
|
||||
className="hover:bg-muted/15"
|
||||
>
|
||||
<td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums text-muted-foreground sm:pl-5">
|
||||
{formatRelativeNoWrap(event.seenAt)}
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top">
|
||||
<span className="inline-flex rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] font-medium uppercase text-foreground/80">
|
||||
{event.level}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top">
|
||||
<div className="truncate font-medium text-foreground">{event.spanName}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top text-muted-foreground">
|
||||
<ExpandableText
|
||||
collapsedClassName="line-clamp-2"
|
||||
expandLabel="Show full message"
|
||||
text={event.message}
|
||||
/>
|
||||
</td>
|
||||
<td className="min-w-0 whitespace-nowrap px-4 py-3 align-top text-muted-foreground sm:pr-5">
|
||||
<TraceIdCell traceId={event.traceId} />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</ScrollArea>
|
||||
) : (
|
||||
<EmptyRows
|
||||
label={isInitialLoading ? "Loading recent logs..." : "No warnings or errors found."}
|
||||
/>
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Top Span Names">
|
||||
{data && data.topSpansByCount.length > 0 ? (
|
||||
<DiagnosticsTable
|
||||
headers={["Span", "Count", "Failures", "Average", "Max"]}
|
||||
minTableWidth="min-w-[760px]"
|
||||
columnWidths={["w-[48%]", "w-[13%]", "w-[13%]", "w-[13%]", "w-[13%]"]}
|
||||
>
|
||||
{data.topSpansByCount.map((span) => (
|
||||
<tr key={span.name}>
|
||||
<td className="px-4 py-3 align-top text-xs font-medium text-foreground first:sm:pl-5">
|
||||
{span.name}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
|
||||
{formatCount(span.count)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
|
||||
{formatCount(span.failureCount)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums">
|
||||
{formatDuration(span.averageDurationMs)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 align-top font-mono tabular-nums last:sm:pr-5">
|
||||
{formatDuration(span.maxDurationMs)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</DiagnosticsTable>
|
||||
) : (
|
||||
<EmptyRows label={isInitialLoading ? "Loading span names..." : "No spans found."} />
|
||||
)}
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildKeybindingRows,
|
||||
buildKeybindingCommandOptions,
|
||||
buildWhenVariableOptions,
|
||||
commandLabel,
|
||||
keybindingConflictLabels,
|
||||
keybindingFromKeyboardEvent,
|
||||
parseWhenExpressionDraft,
|
||||
shortcutToKeybindingInput,
|
||||
unknownWhenVariables,
|
||||
whenAstToExpression,
|
||||
} from "./KeybindingsSettings.logic";
|
||||
|
||||
describe("KeybindingsSettings.logic", () => {
|
||||
it("builds searchable rows with readable key and when values", () => {
|
||||
const rows = buildKeybindingRows(
|
||||
[
|
||||
{
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "j",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig,
|
||||
"terminal",
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({
|
||||
command: "terminal.toggle",
|
||||
key: "mod+j",
|
||||
when: "!terminalFocus",
|
||||
defaultKey: "mod+j",
|
||||
defaultWhen: "",
|
||||
source: "Custom",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("captures platform-specific mod shortcuts", () => {
|
||||
expect(
|
||||
keybindingFromKeyboardEvent(
|
||||
{ key: "K", metaKey: true, ctrlKey: false, altKey: false, shiftKey: true },
|
||||
"MacIntel",
|
||||
),
|
||||
).toBe("mod+shift+k");
|
||||
expect(
|
||||
keybindingFromKeyboardEvent(
|
||||
{ key: "K", metaKey: false, ctrlKey: true, altKey: false, shiftKey: true },
|
||||
"Win32",
|
||||
),
|
||||
).toBe("mod+shift+k");
|
||||
});
|
||||
|
||||
it("serializes shortcuts and when expressions for upserts", () => {
|
||||
expect(
|
||||
shortcutToKeybindingInput({
|
||||
key: " ",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: true,
|
||||
shiftKey: false,
|
||||
}),
|
||||
).toBe("mod+alt+space");
|
||||
|
||||
expect(
|
||||
whenAstToExpression({
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "editorFocus" },
|
||||
right: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
}),
|
||||
).toBe("editorFocus && !terminalFocus");
|
||||
|
||||
expect(parseWhenExpressionDraft("editorFocus && (!terminalFocus || modelPickerOpen)")).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "editorFocus" },
|
||||
right: {
|
||||
type: "or",
|
||||
left: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
right: { type: "identifier", name: "modelPickerOpen" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(parseWhenExpressionDraft("editorFocus &&")).toEqual({
|
||||
ok: false,
|
||||
message: "Use variables with !, &&, ||, and parentheses.",
|
||||
});
|
||||
|
||||
expect(parseWhenExpressionDraft("!(terminalFocus || modelPickerOpen)")).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
type: "not",
|
||||
node: {
|
||||
type: "or",
|
||||
left: { type: "identifier", name: "terminalFocus" },
|
||||
right: { type: "identifier", name: "modelPickerOpen" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("formats static and project script command labels", () => {
|
||||
expect(commandLabel("commandPalette.toggle")).toBe("Command Palette: Toggle");
|
||||
expect(commandLabel("script.setup-db.run")).toBe("Run Script: Setup Db");
|
||||
});
|
||||
|
||||
it("builds known when variable options from defaults without frontend labels", () => {
|
||||
const options = buildWhenVariableOptions();
|
||||
|
||||
expect(options).toEqual(
|
||||
expect.arrayContaining(["terminalFocus", "terminalOpen", "modelPickerOpen", "true", "false"]),
|
||||
);
|
||||
expect(options).not.toContain("customModeActive");
|
||||
});
|
||||
|
||||
it("builds command options from defaults and resolved project bindings", () => {
|
||||
const options = buildKeybindingCommandOptions([
|
||||
{
|
||||
command: "script.setup-db.run",
|
||||
shortcut: {
|
||||
key: "r",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig);
|
||||
|
||||
expect(options).toEqual(expect.arrayContaining(["chat.new", "script.setup-db.run"]));
|
||||
});
|
||||
|
||||
it("reports unknown when variables without rejecting parseable expressions", () => {
|
||||
const parsed = parseWhenExpressionDraft("!terminalFocus && terminalFoc");
|
||||
|
||||
expect(parsed.ok).toBe(true);
|
||||
expect(unknownWhenVariables(parsed.ok ? parsed.value : undefined)).toEqual(["terminalFoc"]);
|
||||
});
|
||||
|
||||
it("marks each default shortcut for multi-binding commands as default", () => {
|
||||
const rows = buildKeybindingRows(
|
||||
[
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "n",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "o",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig,
|
||||
"",
|
||||
);
|
||||
|
||||
expect(rows.map((row) => row.source)).toEqual(["Default", "Default"]);
|
||||
});
|
||||
|
||||
it("reports conflicting shortcuts that share an active when context", () => {
|
||||
const rows = buildKeybindingRows(
|
||||
[
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "n",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
{
|
||||
command: "chat.newLocal",
|
||||
shortcut: {
|
||||
key: "n",
|
||||
modKey: true,
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
] satisfies ResolvedKeybindingsConfig,
|
||||
"",
|
||||
);
|
||||
|
||||
expect(rows[0]?.conflicts).toEqual(["Chat: New Local"]);
|
||||
expect(
|
||||
keybindingConflictLabels(rows, {
|
||||
rowId: rows[0]?.id ?? "",
|
||||
key: "mod+n",
|
||||
when: "",
|
||||
}),
|
||||
).toEqual(["Chat: New Local"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
import {
|
||||
type KeybindingCommand,
|
||||
type KeybindingShortcut,
|
||||
type KeybindingWhenNode,
|
||||
type ResolvedKeybindingRule,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_RESOLVED_KEYBINDINGS,
|
||||
parseKeybindingWhenExpression,
|
||||
} from "@t3tools/shared/keybindings";
|
||||
|
||||
import { isMacPlatform } from "../../lib/utils";
|
||||
|
||||
export type KeybindingSource = "Default" | "Custom" | "Project";
|
||||
|
||||
export interface KeybindingRow {
|
||||
readonly id: string;
|
||||
readonly command: KeybindingCommand;
|
||||
readonly key: string;
|
||||
readonly when: string;
|
||||
readonly source: KeybindingSource;
|
||||
readonly defaultKey: string | null;
|
||||
readonly defaultWhen: string;
|
||||
readonly binding: ResolvedKeybindingRule;
|
||||
readonly conflicts: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export type WhenVariableOption = string;
|
||||
export type KeybindingCommandOption = KeybindingCommand;
|
||||
|
||||
const CORE_WHEN_VARIABLES = ["terminalFocus", "terminalOpen", "true", "false"] as const;
|
||||
|
||||
const DEFAULT_WHEN_VARIABLES = new Set<string>(CORE_WHEN_VARIABLES);
|
||||
for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
|
||||
collectWhenIdentifiersFromNode(binding.whenAst, DEFAULT_WHEN_VARIABLES);
|
||||
}
|
||||
|
||||
export const DEFAULT_WHEN_VARIABLE =
|
||||
[...DEFAULT_WHEN_VARIABLES].find(
|
||||
(identifier) => identifier !== "true" && identifier !== "false",
|
||||
) ?? "terminalFocus";
|
||||
const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES);
|
||||
|
||||
export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string {
|
||||
const parts: string[] = [];
|
||||
if (shortcut.modKey) parts.push("mod");
|
||||
if (shortcut.metaKey) parts.push("meta");
|
||||
if (shortcut.ctrlKey) parts.push("ctrl");
|
||||
if (shortcut.altKey) parts.push("alt");
|
||||
if (shortcut.shiftKey) parts.push("shift");
|
||||
parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key);
|
||||
return parts.join("+");
|
||||
}
|
||||
|
||||
export function whenAstToExpression(node: KeybindingWhenNode | undefined): string {
|
||||
if (!node) return "";
|
||||
switch (node.type) {
|
||||
case "identifier":
|
||||
return node.name;
|
||||
case "not":
|
||||
return `!${wrapWhenExpression(node.node)}`;
|
||||
case "and":
|
||||
return `${wrapWhenExpression(node.left)} && ${wrapWhenExpression(node.right)}`;
|
||||
case "or":
|
||||
return `${wrapWhenExpression(node.left)} || ${wrapWhenExpression(node.right)}`;
|
||||
}
|
||||
}
|
||||
|
||||
function wrapWhenExpression(node: KeybindingWhenNode): string {
|
||||
if (node.type === "identifier" || node.type === "not") return whenAstToExpression(node);
|
||||
return `(${whenAstToExpression(node)})`;
|
||||
}
|
||||
|
||||
export function parseWhenExpressionDraft(
|
||||
expression: string,
|
||||
): { ok: true; value: KeybindingWhenNode | undefined } | { ok: false; message: string } {
|
||||
const trimmed = expression.trim();
|
||||
if (trimmed.length === 0) return { ok: true, value: undefined };
|
||||
|
||||
const ast = parseKeybindingWhenExpression(trimmed);
|
||||
if (!ast) {
|
||||
return {
|
||||
ok: false,
|
||||
message: "Use variables with !, &&, ||, and parentheses.",
|
||||
};
|
||||
}
|
||||
|
||||
return { ok: true, value: ast };
|
||||
}
|
||||
|
||||
function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource {
|
||||
if (String(binding.command).startsWith("script.")) {
|
||||
return "Project";
|
||||
}
|
||||
|
||||
const bindingKey = shortcutToKeybindingInput(binding.shortcut);
|
||||
const bindingWhen = whenAstToExpression(binding.whenAst);
|
||||
const isDefault = DEFAULT_RESOLVED_KEYBINDINGS.some(
|
||||
(entry) =>
|
||||
entry.command === binding.command &&
|
||||
shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
|
||||
whenAstToExpression(entry.whenAst) === bindingWhen,
|
||||
);
|
||||
|
||||
return isDefault ? "Default" : "Custom";
|
||||
}
|
||||
|
||||
function defaultBindingForBinding(
|
||||
binding: ResolvedKeybindingRule,
|
||||
): ResolvedKeybindingRule | undefined {
|
||||
const bindingKey = shortcutToKeybindingInput(binding.shortcut);
|
||||
const bindingWhen = whenAstToExpression(binding.whenAst);
|
||||
|
||||
return (
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.find(
|
||||
(entry) =>
|
||||
entry.command === binding.command &&
|
||||
shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
|
||||
whenAstToExpression(entry.whenAst) === bindingWhen,
|
||||
) ??
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.find(
|
||||
(entry) =>
|
||||
entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen,
|
||||
) ??
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command)
|
||||
);
|
||||
}
|
||||
|
||||
function keybindingRowId(command: KeybindingCommand, key: string, when: string): string {
|
||||
return `${command}\u0000${key}\u0000${when}`;
|
||||
}
|
||||
|
||||
function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean {
|
||||
return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen;
|
||||
}
|
||||
|
||||
export function keybindingConflictLabels(
|
||||
rows: ReadonlyArray<KeybindingRow>,
|
||||
input: { readonly rowId: string; readonly key: string; readonly when: string },
|
||||
): ReadonlyArray<string> {
|
||||
if (input.key.trim().length === 0) return [];
|
||||
const conflicts = rows
|
||||
.filter(
|
||||
(candidate) =>
|
||||
candidate.id !== input.rowId &&
|
||||
candidate.key === input.key &&
|
||||
conflictsWithWhen(candidate.when, input.when),
|
||||
)
|
||||
.map((candidate) => commandLabel(candidate.command));
|
||||
return [...new Set(conflicts)].toSorted();
|
||||
}
|
||||
|
||||
export function buildKeybindingRows(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
query: string,
|
||||
): ReadonlyArray<KeybindingRow> {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const rows = keybindings.map((binding, index) => {
|
||||
const defaultBinding = defaultBindingForBinding(binding);
|
||||
const key = shortcutToKeybindingInput(binding.shortcut);
|
||||
const when = whenAstToExpression(binding.whenAst);
|
||||
return {
|
||||
id: `${keybindingRowId(binding.command, key, when)}\u0000${index}`,
|
||||
command: binding.command,
|
||||
key,
|
||||
when,
|
||||
source: sourceForBinding(binding),
|
||||
defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
|
||||
defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
|
||||
binding,
|
||||
conflicts: [],
|
||||
} satisfies KeybindingRow;
|
||||
});
|
||||
|
||||
const rowsWithConflicts = rows.map((row) => {
|
||||
const conflicts = keybindingConflictLabels(rows, {
|
||||
rowId: row.id,
|
||||
key: row.key,
|
||||
when: row.when,
|
||||
});
|
||||
return conflicts.length > 0
|
||||
? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
|
||||
: row;
|
||||
});
|
||||
|
||||
rowsWithConflicts.sort((left, right) => {
|
||||
const commandCompare = left.command.localeCompare(right.command);
|
||||
if (commandCompare !== 0) return commandCompare;
|
||||
return left.key.localeCompare(right.key);
|
||||
});
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
return rowsWithConflicts;
|
||||
}
|
||||
|
||||
return rowsWithConflicts.filter((row) => {
|
||||
return (
|
||||
row.command.toLowerCase().includes(normalizedQuery) ||
|
||||
row.key.toLowerCase().includes(normalizedQuery) ||
|
||||
row.when.toLowerCase().includes(normalizedQuery) ||
|
||||
row.source.toLowerCase().includes(normalizedQuery)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function collectWhenIdentifiersFromNode(
|
||||
node: KeybindingWhenNode | undefined,
|
||||
identifiers: Set<string>,
|
||||
): void {
|
||||
if (!node) return;
|
||||
switch (node.type) {
|
||||
case "identifier":
|
||||
identifiers.add(node.name);
|
||||
return;
|
||||
case "not":
|
||||
collectWhenIdentifiersFromNode(node.node, identifiers);
|
||||
return;
|
||||
case "and":
|
||||
case "or":
|
||||
collectWhenIdentifiersFromNode(node.left, identifiers);
|
||||
collectWhenIdentifiersFromNode(node.right, identifiers);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export function isKnownWhenVariable(identifier: string): boolean {
|
||||
return KNOWN_WHEN_VARIABLES.has(identifier);
|
||||
}
|
||||
|
||||
export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
|
||||
const identifiers = new Set<string>();
|
||||
collectWhenIdentifiersFromNode(node, identifiers);
|
||||
return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
|
||||
}
|
||||
|
||||
export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
|
||||
return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
|
||||
const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
|
||||
const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
|
||||
right as (typeof CORE_WHEN_VARIABLES)[number],
|
||||
);
|
||||
if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
|
||||
return (
|
||||
(leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
|
||||
(rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
|
||||
);
|
||||
}
|
||||
return left.localeCompare(right);
|
||||
});
|
||||
}
|
||||
|
||||
export function buildKeybindingCommandOptions(
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
): ReadonlyArray<KeybindingCommandOption> {
|
||||
const commands = new Set<KeybindingCommand>();
|
||||
for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
|
||||
commands.add(binding.command);
|
||||
}
|
||||
for (const binding of keybindings) {
|
||||
commands.add(binding.command);
|
||||
}
|
||||
return [...commands].toSorted((left, right) =>
|
||||
commandLabel(left).localeCompare(commandLabel(right)),
|
||||
);
|
||||
}
|
||||
|
||||
export function commandLabel(command: KeybindingCommand): string {
|
||||
const raw = String(command);
|
||||
if (raw.startsWith("script.") && raw.endsWith(".run")) {
|
||||
return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
|
||||
}
|
||||
return raw.split(".").map(titleCaseCommandSegment).join(": ");
|
||||
}
|
||||
|
||||
function titleCaseCommandSegment(segment: string): string {
|
||||
return segment
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.split(/[-_\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function normalizeShortcutKeyToken(key: string): string | null {
|
||||
const normalized = key.toLowerCase();
|
||||
if (
|
||||
normalized === "meta" ||
|
||||
normalized === "control" ||
|
||||
normalized === "ctrl" ||
|
||||
normalized === "shift" ||
|
||||
normalized === "alt" ||
|
||||
normalized === "option"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (normalized === " ") return "space";
|
||||
if (normalized === "escape") return "esc";
|
||||
if (normalized === "arrowup") return "arrowup";
|
||||
if (normalized === "arrowdown") return "arrowdown";
|
||||
if (normalized === "arrowleft") return "arrowleft";
|
||||
if (normalized === "arrowright") return "arrowright";
|
||||
if (normalized.length === 1) return normalized;
|
||||
if (/^f\d{1,2}$/.test(normalized)) return normalized;
|
||||
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "delete" || normalized === "home" || normalized === "end") {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "pageup" || normalized === "pagedown") return normalized;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function keybindingFromKeyboardEvent(
|
||||
event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
|
||||
platform: string,
|
||||
): string | null {
|
||||
const keyToken = normalizeShortcutKeyToken(event.key);
|
||||
if (!keyToken) return null;
|
||||
|
||||
const parts: string[] = [];
|
||||
if (isMacPlatform(platform)) {
|
||||
if (event.metaKey) parts.push("mod");
|
||||
if (event.ctrlKey) parts.push("ctrl");
|
||||
} else {
|
||||
if (event.ctrlKey) parts.push("mod");
|
||||
if (event.metaKey) parts.push("meta");
|
||||
}
|
||||
if (event.altKey) parts.push("alt");
|
||||
if (event.shiftKey) parts.push("shift");
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronDownIcon, PlusIcon, Trash2Icon, XIcon } from "lucide-react";
|
||||
import {
|
||||
ArrowUpCircleIcon,
|
||||
ChevronDownIcon,
|
||||
CopyIcon,
|
||||
DownloadIcon,
|
||||
LoaderIcon,
|
||||
PlusIcon,
|
||||
Trash2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import {
|
||||
isProviderDriverKind,
|
||||
@@ -13,12 +22,15 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
|
||||
import { normalizeProviderAccentColor } from "../../providerInstances";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Collapsible, CollapsibleContent } from "../ui/collapsible";
|
||||
import { DraftInput } from "../ui/draft-input";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import type { DriverOption } from "./providerDriverMeta";
|
||||
import { ProviderSettingsForm } from "./ProviderSettingsForm";
|
||||
@@ -26,6 +38,7 @@ import { ProviderModelsSection } from "./ProviderModelsSection";
|
||||
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import {
|
||||
getProviderVersionAdvisoryPresentation,
|
||||
PROVIDER_STATUS_STYLES,
|
||||
getProviderSummary,
|
||||
getProviderVersionLabel,
|
||||
@@ -405,6 +418,8 @@ interface ProviderInstanceCardProps {
|
||||
readonly onHiddenModelsChange: (next: ReadonlyArray<string>) => void;
|
||||
readonly onFavoriteModelsChange: (next: ReadonlyArray<string>) => void;
|
||||
readonly onModelOrderChange: (next: ReadonlyArray<string>) => void;
|
||||
readonly onRunUpdate?: (() => void) | undefined;
|
||||
readonly isUpdating?: boolean | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,6 +462,8 @@ export function ProviderInstanceCard({
|
||||
onHiddenModelsChange,
|
||||
onFavoriteModelsChange,
|
||||
onModelOrderChange,
|
||||
onRunUpdate,
|
||||
isUpdating = false,
|
||||
}: ProviderInstanceCardProps) {
|
||||
const enabled = instance.enabled ?? true;
|
||||
// The server-reported status wins when present; otherwise fall back to
|
||||
@@ -464,10 +481,30 @@ export function ProviderInstanceCard({
|
||||
: null;
|
||||
const summary = rawSummary;
|
||||
const versionLabel = getProviderVersionLabel(liveProvider?.version);
|
||||
const versionAdvisory = getProviderVersionAdvisoryPresentation(liveProvider?.versionAdvisory);
|
||||
const updateCommand = versionAdvisory?.updateCommand ?? null;
|
||||
const FallbackIconComponent = driverOption?.icon;
|
||||
const displayName =
|
||||
instance.displayName?.trim() || driverOption?.label || String(instance.driver);
|
||||
const accentColor = normalizeProviderAccentColor(instance.accentColor);
|
||||
const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
|
||||
onCopy: ({ providerName }) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: `${providerName} update command copied`,
|
||||
description: "Run it in a terminal when you are ready to update.",
|
||||
});
|
||||
},
|
||||
onError: (error, { providerName }) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Could not copy ${providerName} update command`,
|
||||
description: error.message,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// Narrow `instance.driver` for callers that key on the closed
|
||||
// `ProviderDriverKind` union (e.g. `normalizeModelSlug`'s alias table). Custom
|
||||
@@ -535,97 +572,203 @@ export function ProviderInstanceCard({
|
||||
);
|
||||
};
|
||||
|
||||
const titleIconNode = driverKind ? (
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={displayName}
|
||||
accentColor={accentColor}
|
||||
showBadge={Boolean(accentColor)}
|
||||
statusDotClassName={statusStyle.dot}
|
||||
className="size-5"
|
||||
iconClassName="size-4 text-foreground/80"
|
||||
badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"
|
||||
/>
|
||||
) : FallbackIconComponent ? (
|
||||
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
|
||||
<FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
|
||||
<span
|
||||
className={cn(
|
||||
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
|
||||
statusStyle.dot,
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className={cn("size-2 shrink-0 rounded-full", statusStyle.dot)} />
|
||||
);
|
||||
|
||||
const titleHeadNode = (
|
||||
<>
|
||||
{titleIconNode}
|
||||
<h3 className="truncate text-[13px] font-semibold tracking-[-0.01em] text-foreground">
|
||||
{displayName}
|
||||
</h3>
|
||||
{String(instanceId) !== String(instance.driver) ? (
|
||||
<code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
|
||||
{instanceId}
|
||||
</code>
|
||||
) : null}
|
||||
{driverOption?.badgeLabel ? (
|
||||
<Badge variant="warning" size="sm" className="shrink-0">
|
||||
{driverOption.badgeLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
const titleTailNode = (
|
||||
<>
|
||||
{headerAction ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
{headerAction}
|
||||
</span>
|
||||
) : null}
|
||||
{onDelete ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={onDelete}
|
||||
aria-label={`Delete provider instance ${instanceId}`}
|
||||
>
|
||||
<Trash2Icon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Delete instance</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
const authRowNode = (
|
||||
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{hasAuthenticatedEmail ? (
|
||||
<>
|
||||
<span>Authenticated as</span>
|
||||
<ProviderAuthEmail email={authEmail} />
|
||||
{authenticatedDetail ? <span>· {authenticatedDetail}</span> : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>{summary.headline}</span>
|
||||
<ProviderAuthEmail email={authEmail} separator prefix="Email" />
|
||||
</>
|
||||
)}
|
||||
{summary.detail ? <span>- {summary.detail}</span> : null}
|
||||
</p>
|
||||
);
|
||||
|
||||
const versionCodeNode = versionLabel ? (
|
||||
<code className="text-xs text-muted-foreground">{versionLabel}</code>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div className="border-t border-border first:border-t-0">
|
||||
<div className="px-4 py-4 sm:px-5">
|
||||
<div className="border-t border-border/60 first:border-t-0">
|
||||
<div className="px-4 py-3.5 sm:px-5">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex min-h-5 items-center gap-1.5">
|
||||
{driverKind ? (
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={displayName}
|
||||
accentColor={accentColor}
|
||||
showBadge={Boolean(accentColor)}
|
||||
statusDotClassName={statusStyle.dot}
|
||||
className="size-5"
|
||||
iconClassName="size-4 text-foreground/80"
|
||||
badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 text-[7px]"
|
||||
/>
|
||||
) : FallbackIconComponent ? (
|
||||
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
|
||||
<FallbackIconComponent className="size-4 text-foreground/80" aria-hidden />
|
||||
<span
|
||||
className={cn(
|
||||
"pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background",
|
||||
statusStyle.dot,
|
||||
)}
|
||||
aria-hidden
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
{titleHeadNode}
|
||||
{versionCodeNode}
|
||||
{versionAdvisory ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"size-5 rounded-sm p-0",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning hover:text-warning"
|
||||
: "text-primary hover:text-primary",
|
||||
)}
|
||||
aria-label="Update available — view details"
|
||||
>
|
||||
<ArrowUpCircleIcon className="size-3.5 [animation:bounce_2.4s_ease-in-out_infinite] motion-reduce:animate-none" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className={cn("size-2 shrink-0 rounded-full", statusStyle.dot)} />
|
||||
)}
|
||||
<h3 className="truncate text-sm font-medium text-foreground">{displayName}</h3>
|
||||
{String(instanceId) !== String(instance.driver) ? (
|
||||
// Hide the id chip on a default slot whose id === the
|
||||
// driver slug — it's redundant with the driver icon +
|
||||
// label. Custom instances (and any instance the user has
|
||||
// since renamed) keep the chip so their slug stays
|
||||
// visible for copy/paste + disambiguation.
|
||||
<code className="truncate rounded bg-muted/60 px-1 py-0.5 text-[10px] text-muted-foreground">
|
||||
{instanceId}
|
||||
</code>
|
||||
) : null}
|
||||
{driverOption?.badgeLabel ? (
|
||||
<Badge variant="warning" size="sm" className="shrink-0">
|
||||
{driverOption.badgeLabel}
|
||||
</Badge>
|
||||
) : null}
|
||||
{versionLabel ? (
|
||||
<code className="text-xs text-muted-foreground">{versionLabel}</code>
|
||||
) : null}
|
||||
{headerAction ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
{headerAction}
|
||||
</span>
|
||||
) : null}
|
||||
{onDelete ? (
|
||||
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={onDelete}
|
||||
aria-label={`Delete provider instance ${instanceId}`}
|
||||
<PopoverPopup side="bottom" align="start" className="w-84">
|
||||
<div className="grid gap-3">
|
||||
<div className="grid gap-0.5">
|
||||
<p className="text-[13px] font-semibold leading-tight text-foreground">
|
||||
Update available
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-xs leading-snug",
|
||||
versionAdvisory.emphasis === "strong"
|
||||
? "text-warning"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
<Trash2Icon className="size-3" />
|
||||
{versionAdvisory.detail}
|
||||
</p>
|
||||
</div>
|
||||
{onRunUpdate ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="default"
|
||||
className="w-full"
|
||||
disabled={isUpdating}
|
||||
onClick={onRunUpdate}
|
||||
>
|
||||
{isUpdating ? <LoaderIcon className="animate-spin" /> : <DownloadIcon />}
|
||||
{isUpdating ? "Updating" : "Update now"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Delete instance</TooltipPopup>
|
||||
</Tooltip>
|
||||
</span>
|
||||
) : null}
|
||||
{onRunUpdate && updateCommand ? (
|
||||
<div className="flex items-center gap-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
or, update manually using
|
||||
<span aria-hidden className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
) : null}
|
||||
{updateCommand ? (
|
||||
<div className="flex items-center gap-1 rounded-md border border-border/70 bg-muted/40 py-0.5 pr-0.5 pl-2">
|
||||
<code className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-[11px] text-foreground [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{updateCommand}
|
||||
</code>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-6 shrink-0 rounded-sm p-0 text-muted-foreground hover:text-foreground"
|
||||
onClick={() =>
|
||||
copyToClipboard(updateCommand, {
|
||||
providerName: displayName,
|
||||
})
|
||||
}
|
||||
aria-label="Copy update command"
|
||||
>
|
||||
<CopyIcon className="size-3" />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Copy command</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
) : null}
|
||||
{titleTailNode}
|
||||
</div>
|
||||
<p className="flex min-w-0 flex-wrap items-center gap-x-1 text-xs text-muted-foreground">
|
||||
{hasAuthenticatedEmail ? (
|
||||
<>
|
||||
<span>Authenticated as</span>
|
||||
<ProviderAuthEmail email={authEmail} />
|
||||
{authenticatedDetail ? <span>· {authenticatedDetail}</span> : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>{summary.headline}</span>
|
||||
<ProviderAuthEmail email={authEmail} separator prefix="Email" />
|
||||
</>
|
||||
)}
|
||||
{summary.detail ? <span>- {summary.detail}</span> : null}
|
||||
</p>
|
||||
{authRowNode}
|
||||
</div>
|
||||
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
|
||||
<Button
|
||||
|
||||
@@ -10,22 +10,50 @@ import {
|
||||
type DesktopUpdateChannel,
|
||||
type DesktopUpdateState,
|
||||
type LocalApi,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerConfig,
|
||||
type ServerProvider,
|
||||
type SourceControlDiscoveryResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Option } from "effect";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
import type { ReactNode } from "react";
|
||||
import {
|
||||
RouterProvider,
|
||||
createMemoryHistory,
|
||||
createRootRoute,
|
||||
createRoute,
|
||||
createRouter,
|
||||
} from "@tanstack/react-router";
|
||||
|
||||
import { __resetLocalApiForTests } from "../../localApi";
|
||||
import { AppAtomRegistryProvider, resetAppAtomRegistryForTests } from "../../rpc/atomRegistry";
|
||||
import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState";
|
||||
import { useUiStateStore } from "../../uiStateStore";
|
||||
import { ConnectionsSettings } from "./ConnectionsSettings";
|
||||
import { GeneralSettingsPanel } from "./SettingsPanels";
|
||||
import { DiagnosticsSettingsPanel } from "./DiagnosticsSettings";
|
||||
import { GeneralSettingsPanel, ProviderSettingsPanel } from "./SettingsPanels";
|
||||
import { SourceControlSettingsPanel } from "./SourceControlSettings";
|
||||
|
||||
function renderWithTestRouter(children: ReactNode) {
|
||||
const rootRoute = createRootRoute({
|
||||
component: () => children,
|
||||
});
|
||||
const indexRoute = createRoute({
|
||||
getParentRoute: () => rootRoute,
|
||||
path: "/",
|
||||
});
|
||||
const router = createRouter({
|
||||
routeTree: rootRoute.addChildren([indexRoute]),
|
||||
history: createMemoryHistory({ initialEntries: ["/"] }),
|
||||
});
|
||||
|
||||
return render(<RouterProvider router={router} />);
|
||||
}
|
||||
|
||||
const authAccessHarness = vi.hoisted(() => {
|
||||
type Snapshot = AuthAccessSnapshot;
|
||||
let snapshot: Snapshot = {
|
||||
@@ -207,6 +235,31 @@ function createBaseServerConfig(): ServerConfig {
|
||||
};
|
||||
}
|
||||
|
||||
function createOutdatedProvider(driver: string): ServerProvider {
|
||||
return {
|
||||
instanceId: ProviderInstanceId.make(driver),
|
||||
driver: ProviderDriverKind.make(driver),
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-05-04T10:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
versionAdvisory: {
|
||||
status: "behind_latest",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: "1.1.0",
|
||||
message: "Update available.",
|
||||
checkedAt: "2026-05-04T10:00:00.000Z",
|
||||
updateCommand: "npm install -g openai/codex@latest",
|
||||
canUpdate: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeUtc(value: string) {
|
||||
return DateTime.makeUnsafe(Date.parse(value));
|
||||
}
|
||||
@@ -666,25 +719,24 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
await expect.element(page.getByText("http://127.0.0.1:3773/").first()).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows diagnostics inside About with a single logs-folder action", async () => {
|
||||
it("shows diagnostics inside About with a diagnostics link", async () => {
|
||||
setServerConfigSnapshot(createBaseServerConfig());
|
||||
|
||||
mounted = await render(
|
||||
mounted = await renderWithTestRouter(
|
||||
<AppAtomRegistryProvider>
|
||||
<GeneralSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByText("About")).toBeInTheDocument();
|
||||
await expect.element(page.getByText("Diagnostics")).toBeInTheDocument();
|
||||
await expect.element(page.getByText("Open logs folder")).toBeInTheDocument();
|
||||
await expect
|
||||
.element(page.getByText("/repo/project/.t3/logs", { exact: true }))
|
||||
.element(page.getByRole("heading", { name: "Diagnostics", exact: true }))
|
||||
.toBeInTheDocument();
|
||||
await expect.element(page.getByRole("link", { name: "View diagnostics" })).toBeInTheDocument();
|
||||
await expect
|
||||
.element(
|
||||
page.getByText(
|
||||
"Local trace file. OTLP exporting traces to http://localhost:4318/v1/traces.",
|
||||
"Local trace file. Exporting OTEL traces to http://localhost:4318/v1/traces.",
|
||||
),
|
||||
)
|
||||
.toBeInTheDocument();
|
||||
@@ -992,20 +1044,56 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
it("opens the logs folder in the preferred editor", async () => {
|
||||
const openInEditor = vi.fn<LocalApi["shell"]["openInEditor"]>().mockResolvedValue(undefined);
|
||||
window.nativeApi = {
|
||||
persistence: {
|
||||
getClientSettings: vi.fn().mockResolvedValue(null),
|
||||
setClientSettings: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
shell: {
|
||||
openInEditor,
|
||||
},
|
||||
server: {
|
||||
getProcessDiagnostics: vi.fn().mockResolvedValue({
|
||||
serverPid: 1234,
|
||||
readAt: makeUtc("2036-04-07T00:00:00.000Z"),
|
||||
processCount: 0,
|
||||
totalRssBytes: 0,
|
||||
totalCpuPercent: 0,
|
||||
processes: [],
|
||||
error: Option.none(),
|
||||
}),
|
||||
getTraceDiagnostics: vi.fn().mockResolvedValue({
|
||||
traceFilePath: "/repo/project/.t3/traces.jsonl",
|
||||
scannedFilePaths: ["/repo/project/.t3/traces.jsonl"],
|
||||
readAt: makeUtc("2036-04-07T00:00:00.000Z"),
|
||||
recordCount: 0,
|
||||
parseErrorCount: 0,
|
||||
firstSpanAt: Option.none(),
|
||||
lastSpanAt: Option.none(),
|
||||
failureCount: 0,
|
||||
interruptionCount: 0,
|
||||
slowSpanThresholdMs: 5_000,
|
||||
slowSpanCount: 0,
|
||||
logLevelCounts: {},
|
||||
topSpansByCount: [],
|
||||
slowestSpans: [],
|
||||
commonFailures: [],
|
||||
latestFailures: [],
|
||||
latestWarningAndErrorLogs: [],
|
||||
partialFailure: Option.none(),
|
||||
error: Option.none(),
|
||||
}),
|
||||
},
|
||||
} as unknown as LocalApi;
|
||||
|
||||
setServerConfigSnapshot(createBaseServerConfig());
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<GeneralSettingsPanel />
|
||||
<DiagnosticsSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
const openLogsButton = page.getByText("Open logs folder");
|
||||
const openLogsButton = page.getByLabelText("Open logs folder");
|
||||
await openLogsButton.click();
|
||||
|
||||
expect(openInEditor).toHaveBeenCalledWith("/repo/project/.t3/logs", "cursor");
|
||||
@@ -1016,7 +1104,7 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<GeneralSettingsPanel />
|
||||
<ProviderSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
@@ -1031,6 +1119,41 @@ describe("GeneralSettingsPanel observability", () => {
|
||||
await expect.element(page.getByText("Server password")).toBeInTheDocument();
|
||||
await expect.element(page.getByPlaceholder("Optional")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("runs one-click provider updates from the provider card", async () => {
|
||||
const updateProvider = vi.fn<LocalApi["server"]["updateProvider"]>().mockResolvedValue({
|
||||
providers: [createOutdatedProvider("codex")],
|
||||
});
|
||||
window.nativeApi = {
|
||||
persistence: {
|
||||
getClientSettings: vi.fn().mockResolvedValue(null),
|
||||
setClientSettings: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
server: {
|
||||
updateProvider,
|
||||
},
|
||||
} as unknown as LocalApi;
|
||||
|
||||
setServerConfigSnapshot({
|
||||
...createBaseServerConfig(),
|
||||
providers: [createOutdatedProvider("codex")],
|
||||
});
|
||||
|
||||
mounted = await render(
|
||||
<AppAtomRegistryProvider>
|
||||
<ProviderSettingsPanel />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Update available — view details" }).click();
|
||||
await expect.element(page.getByRole("button", { name: "Update now" })).toBeInTheDocument();
|
||||
await page.getByRole("button", { name: "Update now" }).click();
|
||||
|
||||
expect(updateProvider).toHaveBeenCalledWith({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("SourceControlSettingsPanel discovery states", () => {
|
||||
|
||||
@@ -5,7 +5,48 @@ import {
|
||||
type ProviderInstanceConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildProviderInstanceUpdatePatch } from "./SettingsPanels.logic";
|
||||
import {
|
||||
buildProviderInstanceUpdatePatch,
|
||||
formatDiagnosticsDescription,
|
||||
} from "./SettingsPanels.logic";
|
||||
|
||||
describe("formatDiagnosticsDescription", () => {
|
||||
it("collapses trace and metric URLs that share the same OTEL base path", () => {
|
||||
expect(
|
||||
formatDiagnosticsDescription({
|
||||
localTracingEnabled: true,
|
||||
otlpTracesEnabled: true,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsEnabled: true,
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
}),
|
||||
).toBe("Local trace file. Exporting OTEL to http://localhost:4318/v1/{traces,metrics}.");
|
||||
});
|
||||
|
||||
it("keeps separate trace and metric URLs when their base paths differ", () => {
|
||||
expect(
|
||||
formatDiagnosticsDescription({
|
||||
localTracingEnabled: true,
|
||||
otlpTracesEnabled: true,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsEnabled: true,
|
||||
otlpMetricsUrl: "http://localhost:9000/v1/metrics",
|
||||
}),
|
||||
).toBe(
|
||||
"Local trace file. Exporting OTEL traces to http://localhost:4318/v1/traces and metrics to http://localhost:9000/v1/metrics.",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits OTEL text when no exporter is enabled", () => {
|
||||
expect(
|
||||
formatDiagnosticsDescription({
|
||||
localTracingEnabled: true,
|
||||
otlpTracesEnabled: false,
|
||||
otlpMetricsEnabled: false,
|
||||
}),
|
||||
).toBe("Local trace file.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildProviderInstanceUpdatePatch", () => {
|
||||
it("promotes an edited default provider into providerInstances and resets the legacy provider", () => {
|
||||
|
||||
@@ -7,6 +7,54 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
|
||||
function collapseOtelSignalsUrl(input: {
|
||||
readonly tracesUrl: string;
|
||||
readonly metricsUrl: string;
|
||||
}): string | null {
|
||||
const tracesSuffix = "/traces";
|
||||
const metricsSuffix = "/metrics";
|
||||
if (!input.tracesUrl.endsWith(tracesSuffix) || !input.metricsUrl.endsWith(metricsSuffix)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const tracesBase = input.tracesUrl.slice(0, -tracesSuffix.length);
|
||||
const metricsBase = input.metricsUrl.slice(0, -metricsSuffix.length);
|
||||
if (tracesBase !== metricsBase) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `${tracesBase}/{traces,metrics}`;
|
||||
}
|
||||
|
||||
export function formatDiagnosticsDescription(input: {
|
||||
readonly localTracingEnabled: boolean;
|
||||
readonly otlpTracesEnabled: boolean;
|
||||
readonly otlpTracesUrl?: string | undefined;
|
||||
readonly otlpMetricsEnabled: boolean;
|
||||
readonly otlpMetricsUrl?: string | undefined;
|
||||
}): string {
|
||||
const mode = input.localTracingEnabled ? "Local trace file" : "Terminal logs only";
|
||||
const tracesUrl = input.otlpTracesEnabled ? input.otlpTracesUrl : undefined;
|
||||
const metricsUrl = input.otlpMetricsEnabled ? input.otlpMetricsUrl : undefined;
|
||||
|
||||
if (tracesUrl && metricsUrl) {
|
||||
const collapsedUrl = collapseOtelSignalsUrl({ tracesUrl, metricsUrl });
|
||||
return collapsedUrl
|
||||
? `${mode}. Exporting OTEL to ${collapsedUrl}.`
|
||||
: `${mode}. Exporting OTEL traces to ${tracesUrl} and metrics to ${metricsUrl}.`;
|
||||
}
|
||||
|
||||
if (tracesUrl) {
|
||||
return `${mode}. Exporting OTEL traces to ${tracesUrl}.`;
|
||||
}
|
||||
|
||||
if (metricsUrl) {
|
||||
return `${mode}. Exporting OTEL metrics to ${metricsUrl}.`;
|
||||
}
|
||||
|
||||
return `${mode}.`;
|
||||
}
|
||||
|
||||
export function buildProviderInstanceUpdatePatch(input: {
|
||||
readonly settings: Pick<ServerSettings, "providers" | "providerInstances">;
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { ArchiveIcon, ArchiveX, LoaderIcon, PlusIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
type DesktopUpdateChannel,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
ProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceId,
|
||||
@@ -23,7 +25,6 @@ import {
|
||||
} from "../../components/desktopUpdate.logic";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { TraitsPicker } from "../chat/TraitsPicker";
|
||||
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
|
||||
import { isElectron } from "../../env";
|
||||
import { useTheme } from "../../hooks/useTheme";
|
||||
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
|
||||
@@ -56,9 +57,19 @@ import { Switch } from "../ui/switch";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
hasOneClickUpdateProviderCandidate,
|
||||
isProviderUpdateActive,
|
||||
type ProviderUpdateCandidate,
|
||||
} from "../ProviderUpdateLaunchNotification.logic";
|
||||
import { ProviderInstanceCard } from "./ProviderInstanceCard";
|
||||
import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
|
||||
import { buildProviderInstanceUpdatePatch } from "./SettingsPanels.logic";
|
||||
import {
|
||||
buildProviderInstanceUpdatePatch,
|
||||
formatDiagnosticsDescription,
|
||||
} from "./SettingsPanels.logic";
|
||||
import {
|
||||
SettingResetButton,
|
||||
SettingsPageContainer,
|
||||
@@ -67,12 +78,7 @@ import {
|
||||
useRelativeTimeTick,
|
||||
} from "./settingsLayout";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
import {
|
||||
useServerAvailableEditors,
|
||||
useServerKeybindingsConfigPath,
|
||||
useServerObservability,
|
||||
useServerProviders,
|
||||
} from "../../rpc/serverState";
|
||||
import { useServerObservability, useServerProviders } from "../../rpc/serverState";
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{
|
||||
@@ -345,37 +351,12 @@ function AboutVersionSection() {
|
||||
export function useSettingsRestore(onRestored?: () => void) {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { resetSettings } = useUpdateSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
// A provider surface is "dirty" if either the legacy per-kind
|
||||
// `settings.providers[kind]` struct differs from defaults (for users
|
||||
// on pre-migration data) or the new `settings.providerInstances` map
|
||||
// has any entries (every edit to a default slot promotes it into an
|
||||
// explicit entry, so any key in that map represents user intent to
|
||||
// diverge from factory defaults). Checking both keeps the Restore
|
||||
// Defaults chip accurate throughout the legacy→instance migration.
|
||||
const areProviderSettingsDirty =
|
||||
PROVIDER_SETTINGS.some((providerSettings) => {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const currentProviders = settings.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const defaultProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const currentSettings = currentProviders[providerSettings.provider];
|
||||
const defaultSettings = defaultProviders[providerSettings.provider];
|
||||
return !Equal.equals(currentSettings, defaultSettings);
|
||||
}) ||
|
||||
Object.keys(settings.providerInstances ?? {}).length > 0 ||
|
||||
Object.keys(settings.providerModelPreferences ?? {}).length > 0 ||
|
||||
(settings.favorites ?? []).length > 0;
|
||||
|
||||
const changedSettingLabels = useMemo(
|
||||
() => [
|
||||
@@ -408,10 +389,8 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(isGitWritingModelDirty ? ["Git writing model"] : []),
|
||||
...(areProviderSettingsDirty ? ["Providers"] : []),
|
||||
],
|
||||
[
|
||||
areProviderSettingsDirty,
|
||||
isGitWritingModelDirty,
|
||||
settings.autoOpenPlanSidebar,
|
||||
settings.confirmThreadArchive,
|
||||
@@ -437,9 +416,20 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
if (!confirmed) return;
|
||||
|
||||
setTheme("system");
|
||||
resetSettings();
|
||||
updateSettings({
|
||||
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
|
||||
diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,
|
||||
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
|
||||
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
|
||||
confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
|
||||
textGenerationModelSelection: DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
|
||||
});
|
||||
onRestored?.();
|
||||
}, [changedSettingLabels, onRestored, resetSettings, setTheme]);
|
||||
}, [changedSettingLabels, onRestored, setTheme, updateSettings]);
|
||||
|
||||
return {
|
||||
changedSettingLabels,
|
||||
@@ -451,63 +441,15 @@ export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const [openingPathByTarget, setOpeningPathByTarget] = useState({
|
||||
keybindings: false,
|
||||
logsDirectory: false,
|
||||
});
|
||||
const [openPathErrorByTarget, setOpenPathErrorByTarget] = useState<
|
||||
Partial<Record<"keybindings" | "logsDirectory", string | null>>
|
||||
>({});
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
|
||||
// Collapsible state per provider-instance card, keyed by the instance id.
|
||||
// `Record<string, boolean>` so we don't need to preseed an entry for every
|
||||
// configured instance — an absent key reads as collapsed. Default-slot
|
||||
// rows share this state: their id is the driver slug
|
||||
// (`defaultInstanceIdForDriver(driver)`), which is also `ProviderDriverKind` at
|
||||
// runtime, so a pre-existing open key for e.g. "codex" persists across
|
||||
// the legacy/unified render swap.
|
||||
const [openInstanceDetails, setOpenInstanceDetails] = useState<Record<string, boolean>>({});
|
||||
const refreshingRef = useRef(false);
|
||||
const refreshProviders = useCallback(() => {
|
||||
if (refreshingRef.current) return;
|
||||
refreshingRef.current = true;
|
||||
setIsRefreshingProviders(true);
|
||||
void ensureLocalApi()
|
||||
.server.refreshProviders()
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to refresh providers", error);
|
||||
})
|
||||
.finally(() => {
|
||||
refreshingRef.current = false;
|
||||
setIsRefreshingProviders(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const keybindingsConfigPath = useServerKeybindingsConfigPath();
|
||||
const availableEditors = useServerAvailableEditors();
|
||||
const observability = useServerObservability();
|
||||
const serverProviders = useServerProviders();
|
||||
const visibleProviderSettings = PROVIDER_SETTINGS.filter(
|
||||
(providerSettings) =>
|
||||
providerSettings.provider !== "cursor" ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
|
||||
),
|
||||
);
|
||||
const logsDirectoryPath = observability?.logsDirectoryPath ?? null;
|
||||
const diagnosticsDescription = (() => {
|
||||
const exports: string[] = [];
|
||||
if (observability?.otlpTracesEnabled && observability.otlpTracesUrl) {
|
||||
exports.push(`traces to ${observability.otlpTracesUrl}`);
|
||||
}
|
||||
if (observability?.otlpMetricsEnabled && observability.otlpMetricsUrl) {
|
||||
exports.push(`metrics to ${observability.otlpMetricsUrl}`);
|
||||
}
|
||||
const mode = observability?.localTracingEnabled ? "Local trace file" : "Terminal logs only";
|
||||
return exports.length > 0 ? `${mode}. OTLP exporting ${exports.join(" and ")}.` : `${mode}.`;
|
||||
})();
|
||||
const diagnosticsDescription = formatDiagnosticsDescription({
|
||||
localTracingEnabled: observability?.localTracingEnabled ?? false,
|
||||
otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
|
||||
otlpTracesUrl: observability?.otlpTracesUrl,
|
||||
otlpMetricsEnabled: observability?.otlpMetricsEnabled ?? false,
|
||||
otlpMetricsUrl: observability?.otlpMetricsUrl,
|
||||
});
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
@@ -532,265 +474,6 @@ export function GeneralSettingsPanel() {
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
|
||||
const openInPreferredEditor = useCallback(
|
||||
(target: "keybindings" | "logsDirectory", path: string | null, failureMessage: string) => {
|
||||
if (!path) return;
|
||||
setOpenPathErrorByTarget((existing) => ({ ...existing, [target]: null }));
|
||||
setOpeningPathByTarget((existing) => ({ ...existing, [target]: true }));
|
||||
|
||||
const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);
|
||||
if (!editor) {
|
||||
setOpenPathErrorByTarget((existing) => ({
|
||||
...existing,
|
||||
[target]: "No available editors found.",
|
||||
}));
|
||||
setOpeningPathByTarget((existing) => ({ ...existing, [target]: false }));
|
||||
return;
|
||||
}
|
||||
|
||||
void ensureLocalApi()
|
||||
.shell.openInEditor(path, editor)
|
||||
.catch((error) => {
|
||||
setOpenPathErrorByTarget((existing) => ({
|
||||
...existing,
|
||||
[target]: error instanceof Error ? error.message : failureMessage,
|
||||
}));
|
||||
})
|
||||
.finally(() => {
|
||||
setOpeningPathByTarget((existing) => ({ ...existing, [target]: false }));
|
||||
});
|
||||
},
|
||||
[availableEditors],
|
||||
);
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
openInPreferredEditor("keybindings", keybindingsConfigPath, "Unable to open keybindings file.");
|
||||
}, [keybindingsConfigPath, openInPreferredEditor]);
|
||||
|
||||
const openLogsDirectory = useCallback(() => {
|
||||
openInPreferredEditor("logsDirectory", logsDirectoryPath, "Unable to open logs folder.");
|
||||
}, [logsDirectoryPath, openInPreferredEditor]);
|
||||
|
||||
const openKeybindingsError = openPathErrorByTarget.keybindings ?? null;
|
||||
const openDiagnosticsError = openPathErrorByTarget.logsDirectory ?? null;
|
||||
const isOpeningKeybindings = openingPathByTarget.keybindings;
|
||||
const isOpeningLogsDirectory = openingPathByTarget.logsDirectory;
|
||||
|
||||
const lastCheckedAt =
|
||||
serverProviders.length > 0
|
||||
? serverProviders.reduce(
|
||||
(latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
|
||||
serverProviders[0]!.checkedAt,
|
||||
)
|
||||
: null;
|
||||
|
||||
/**
|
||||
* Build the list of rows to render, one per configured instance. Each
|
||||
* row carries enough context to drive `ProviderInstanceCard` without
|
||||
* threading storage concerns: whether it's a built-in default slot (in
|
||||
* which case `isDefault` is true, deletion is gated off, and the
|
||||
* effective envelope may have been synthesized from legacy just for
|
||||
* this render), the driver kind narrow for the in-card model-slug
|
||||
* normalization, and whether a reset-to-factory action is warranted.
|
||||
*
|
||||
* Ordering mirrors the prior split: visible built-in default slots
|
||||
* first (one per visible kind), then user-authored custom instances
|
||||
* grouped by driver after their default sibling, then orphan instances
|
||||
* whose driver isn't in the visible-defaults set.
|
||||
*/
|
||||
interface InstanceRow {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly instance: ProviderInstanceConfig;
|
||||
readonly driver: ProviderDriverKind;
|
||||
/** True for the slot whose id is `defaultInstanceIdForDriver(driver)`. */
|
||||
readonly isDefault: boolean;
|
||||
/**
|
||||
* True when this default slot differs from the factory defaults —
|
||||
* either through an explicit `providerInstances[defaultId]` entry,
|
||||
* or through a non-default legacy `settings.providers[kind]` struct
|
||||
* that we're still bridging. Used to show the reset-to-factory
|
||||
* affordance. Undefined for custom rows (they have a delete button
|
||||
* instead; "factory defaults" isn't meaningful).
|
||||
*/
|
||||
readonly isDirty?: boolean;
|
||||
}
|
||||
|
||||
const instancesByDriver = new Map<
|
||||
ProviderDriverKind,
|
||||
Array<[ProviderInstanceId, ProviderInstanceConfig]>
|
||||
>();
|
||||
for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
|
||||
const driver = instance.driver;
|
||||
const list = instancesByDriver.get(driver) ?? [];
|
||||
list.push([rawId as ProviderInstanceId, instance]);
|
||||
instancesByDriver.set(driver, list);
|
||||
}
|
||||
|
||||
const defaultSlotIdsBySource = new Set<string>(
|
||||
visibleProviderSettings.map((providerSettings) =>
|
||||
String(defaultInstanceIdForDriver(providerSettings.provider)),
|
||||
),
|
||||
);
|
||||
|
||||
const rows: InstanceRow[] = [];
|
||||
const visibleDriverKinds = new Set<ProviderDriverKind>(
|
||||
visibleProviderSettings.map((providerSettings) => providerSettings.provider),
|
||||
);
|
||||
|
||||
for (const providerSettings of visibleProviderSettings) {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings
|
||||
>;
|
||||
const driver = providerSettings.provider;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driver);
|
||||
// Prefer an explicit `providerInstances[defaultId]` entry when one
|
||||
// exists (every edit via this UI promotes the default slot into
|
||||
// that map); fall back to synthesizing one from the legacy
|
||||
// `settings.providers[kind]` struct so first-time viewers still see
|
||||
// their persisted config.
|
||||
const explicitInstance = settings.providerInstances?.[defaultInstanceId];
|
||||
const legacyConfig = legacyProviders[providerSettings.provider]!;
|
||||
const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider]!;
|
||||
const effectiveInstance: ProviderInstanceConfig =
|
||||
explicitInstance ??
|
||||
({
|
||||
driver,
|
||||
enabled: legacyConfig.enabled,
|
||||
config: legacyConfig,
|
||||
} satisfies ProviderInstanceConfig);
|
||||
const isDirty =
|
||||
explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
|
||||
rows.push({
|
||||
instanceId: defaultInstanceId,
|
||||
instance: effectiveInstance,
|
||||
driver,
|
||||
isDefault: true,
|
||||
isDirty,
|
||||
});
|
||||
// Non-default customs for this driver kind follow their default.
|
||||
for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
|
||||
if (id === defaultInstanceId) continue;
|
||||
rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
|
||||
}
|
||||
}
|
||||
// Orphan instances: drivers the visible-defaults list doesn't cover
|
||||
// (e.g. Cursor when the server hasn't reported it but the user has
|
||||
// authored a Cursor instance anyway, or fork drivers not shipped by
|
||||
// this build). Preserve insertion order within each driver.
|
||||
for (const [driver, list] of instancesByDriver) {
|
||||
if (visibleDriverKinds.has(driver)) continue;
|
||||
for (const [id, instance] of list) {
|
||||
const isDefaultSlot = defaultSlotIdsBySource.has(String(id));
|
||||
rows.push({
|
||||
instanceId: id,
|
||||
instance,
|
||||
driver: instance.driver,
|
||||
isDefault: isDefaultSlot,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const updateProviderInstance = (
|
||||
row: InstanceRow,
|
||||
next: ProviderInstanceConfig,
|
||||
options?: {
|
||||
readonly textGenerationModelSelection?: Parameters<
|
||||
typeof buildProviderInstanceUpdatePatch
|
||||
>[0]["textGenerationModelSelection"];
|
||||
},
|
||||
) => {
|
||||
updateSettings(
|
||||
buildProviderInstanceUpdatePatch({
|
||||
settings,
|
||||
instanceId: row.instanceId,
|
||||
instance: next,
|
||||
driver: row.driver,
|
||||
isDefault: row.isDefault,
|
||||
textGenerationModelSelection: options?.textGenerationModelSelection,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const deleteProviderInstance = (id: ProviderInstanceId) => {
|
||||
updateSettings({
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
|
||||
providerModelPreferences: withoutProviderInstanceKey(settings.providerModelPreferences, id),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], id),
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderModelPreferences = (
|
||||
instanceId: ProviderInstanceId,
|
||||
next: {
|
||||
readonly hiddenModels: ReadonlyArray<string>;
|
||||
readonly modelOrder: ReadonlyArray<string>;
|
||||
},
|
||||
) => {
|
||||
const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
|
||||
const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
|
||||
const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
|
||||
updateSettings({
|
||||
providerModelPreferences:
|
||||
hiddenModels.length === 0 && modelOrder.length === 0
|
||||
? rest
|
||||
: {
|
||||
...rest,
|
||||
[instanceId]: {
|
||||
hiddenModels,
|
||||
modelOrder,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderFavoriteModels = (
|
||||
instanceId: ProviderInstanceId,
|
||||
nextFavoriteModels: ReadonlyArray<string>,
|
||||
) => {
|
||||
const favoriteModels = [
|
||||
...new Set(nextFavoriteModels.map((slug) => slug.trim()).filter((slug) => slug.length > 0)),
|
||||
];
|
||||
updateSettings({
|
||||
favorites: [
|
||||
...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
|
||||
...favoriteModels.map((model) => ({ provider: instanceId, model })),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset a built-in default slot back to factory defaults. Clears both
|
||||
* the legacy `settings.providers[kind]` struct and any explicit
|
||||
* `providerInstances[defaultId]` entry that has promoted legacy into
|
||||
* the new map, so hydration re-synthesizes a clean envelope on next
|
||||
* load. Safe to call on drivers that have never been edited.
|
||||
*/
|
||||
const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
|
||||
const defaultLegacyProvider = defaultLegacyProviders[driverKind];
|
||||
if (defaultLegacyProvider === undefined) return;
|
||||
updateSettings({
|
||||
providers: {
|
||||
...settings.providers,
|
||||
[driverKind]: defaultLegacyProvider,
|
||||
} as typeof settings.providers,
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
|
||||
providerModelPreferences: withoutProviderInstanceKey(
|
||||
settings.providerModelPreferences,
|
||||
defaultInstanceId,
|
||||
),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], defaultInstanceId),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="General">
|
||||
@@ -1168,6 +851,293 @@ export function GeneralSettingsPanel() {
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="About">
|
||||
{isElectron ? (
|
||||
<AboutVersionSection />
|
||||
) : (
|
||||
<SettingsRow
|
||||
title={<AboutVersionTitle />}
|
||||
description="Current version of the application."
|
||||
/>
|
||||
)}
|
||||
<SettingsRow
|
||||
title="Diagnostics"
|
||||
description={diagnosticsDescription}
|
||||
control={
|
||||
<Button render={<Link to="/settings/diagnostics" />} size="xs" variant="outline">
|
||||
View diagnostics
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProviderSettingsPanel() {
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const serverProviders = useServerProviders();
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const [isAddInstanceDialogOpen, setIsAddInstanceDialogOpen] = useState(false);
|
||||
const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
|
||||
ReadonlySet<ProviderDriverKind>
|
||||
>(() => new Set());
|
||||
const [openInstanceDetails, setOpenInstanceDetails] = useState<Record<string, boolean>>({});
|
||||
const refreshingRef = useRef(false);
|
||||
|
||||
const providerUpdateCandidates = useMemo(
|
||||
() => collectProviderUpdateCandidates(serverProviders),
|
||||
[serverProviders],
|
||||
);
|
||||
const providerUpdateCandidateByInstanceId = useMemo(
|
||||
() => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),
|
||||
[providerUpdateCandidates],
|
||||
);
|
||||
const visibleProviderSettings = PROVIDER_SETTINGS.filter(
|
||||
(providerSettings) =>
|
||||
providerSettings.provider !== "cursor" ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.instanceId === defaultInstanceIdForDriver(ProviderDriverKind.make("cursor")),
|
||||
),
|
||||
);
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const lastCheckedAt =
|
||||
serverProviders.length > 0
|
||||
? serverProviders.reduce(
|
||||
(latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),
|
||||
serverProviders[0]!.checkedAt,
|
||||
)
|
||||
: null;
|
||||
|
||||
const refreshProviders = useCallback(() => {
|
||||
if (refreshingRef.current) return;
|
||||
refreshingRef.current = true;
|
||||
setIsRefreshingProviders(true);
|
||||
void ensureLocalApi()
|
||||
.server.refreshProviders()
|
||||
.catch((error: unknown) => {
|
||||
console.warn("Failed to refresh providers", error);
|
||||
})
|
||||
.finally(() => {
|
||||
refreshingRef.current = false;
|
||||
setIsRefreshingProviders(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const runProviderUpdate = useCallback(async (candidate: ProviderUpdateCandidate) => {
|
||||
let started = false;
|
||||
setUpdatingProviderDrivers((previous) => {
|
||||
if (previous.has(candidate.driver)) {
|
||||
return previous;
|
||||
}
|
||||
started = true;
|
||||
const next = new Set(previous);
|
||||
next.add(candidate.driver);
|
||||
return next;
|
||||
});
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureLocalApi().server.updateProvider({
|
||||
provider: candidate.driver,
|
||||
instanceId: candidate.instanceId,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: `Could not update ${PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver}`,
|
||||
description:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The provider update command could not be started.",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setUpdatingProviderDrivers((previous) => {
|
||||
if (!previous.has(candidate.driver)) {
|
||||
return previous;
|
||||
}
|
||||
const next = new Set(previous);
|
||||
next.delete(candidate.driver);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
interface InstanceRow {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly instance: ProviderInstanceConfig;
|
||||
readonly driver: ProviderDriverKind;
|
||||
readonly isDefault: boolean;
|
||||
readonly isDirty?: boolean;
|
||||
}
|
||||
|
||||
const instancesByDriver = new Map<
|
||||
ProviderDriverKind,
|
||||
Array<[ProviderInstanceId, ProviderInstanceConfig]>
|
||||
>();
|
||||
for (const [rawId, instance] of Object.entries(settings.providerInstances ?? {})) {
|
||||
const driver = instance.driver;
|
||||
const list = instancesByDriver.get(driver) ?? [];
|
||||
list.push([rawId as ProviderInstanceId, instance]);
|
||||
instancesByDriver.set(driver, list);
|
||||
}
|
||||
|
||||
const defaultSlotIdsBySource = new Set<string>(
|
||||
visibleProviderSettings.map((providerSettings) =>
|
||||
String(defaultInstanceIdForDriver(providerSettings.provider)),
|
||||
),
|
||||
);
|
||||
|
||||
const rows: InstanceRow[] = [];
|
||||
const visibleDriverKinds = new Set<ProviderDriverKind>(
|
||||
visibleProviderSettings.map((providerSettings) => providerSettings.provider),
|
||||
);
|
||||
|
||||
for (const providerSettings of visibleProviderSettings) {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const legacyProviders = settings.providers as Record<string, LegacyProviderSettings>;
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings
|
||||
>;
|
||||
const driver = providerSettings.provider;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driver);
|
||||
const explicitInstance = settings.providerInstances?.[defaultInstanceId];
|
||||
const legacyConfig = legacyProviders[providerSettings.provider]!;
|
||||
const defaultLegacyConfig = defaultLegacyProviders[providerSettings.provider]!;
|
||||
const effectiveInstance: ProviderInstanceConfig =
|
||||
explicitInstance ??
|
||||
({
|
||||
driver,
|
||||
enabled: legacyConfig.enabled,
|
||||
config: legacyConfig,
|
||||
} satisfies ProviderInstanceConfig);
|
||||
const isDirty =
|
||||
explicitInstance !== undefined || !Equal.equals(legacyConfig, defaultLegacyConfig);
|
||||
rows.push({
|
||||
instanceId: defaultInstanceId,
|
||||
instance: effectiveInstance,
|
||||
driver,
|
||||
isDefault: true,
|
||||
isDirty,
|
||||
});
|
||||
for (const [id, instance] of instancesByDriver.get(providerSettings.provider) ?? []) {
|
||||
if (id === defaultInstanceId) continue;
|
||||
rows.push({ instanceId: id, instance, driver: instance.driver, isDefault: false });
|
||||
}
|
||||
}
|
||||
for (const [driver, list] of instancesByDriver) {
|
||||
if (visibleDriverKinds.has(driver)) continue;
|
||||
for (const [id, instance] of list) {
|
||||
rows.push({
|
||||
instanceId: id,
|
||||
instance,
|
||||
driver: instance.driver,
|
||||
isDefault: defaultSlotIdsBySource.has(String(id)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const updateProviderInstance = (
|
||||
row: InstanceRow,
|
||||
next: ProviderInstanceConfig,
|
||||
options?: {
|
||||
readonly textGenerationModelSelection?: Parameters<
|
||||
typeof buildProviderInstanceUpdatePatch
|
||||
>[0]["textGenerationModelSelection"];
|
||||
},
|
||||
) => {
|
||||
updateSettings(
|
||||
buildProviderInstanceUpdatePatch({
|
||||
settings,
|
||||
instanceId: row.instanceId,
|
||||
instance: next,
|
||||
driver: row.driver,
|
||||
isDefault: row.isDefault,
|
||||
textGenerationModelSelection: options?.textGenerationModelSelection,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const deleteProviderInstance = (id: ProviderInstanceId) => {
|
||||
updateSettings({
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, id),
|
||||
providerModelPreferences: withoutProviderInstanceKey(settings.providerModelPreferences, id),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], id),
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderModelPreferences = (
|
||||
instanceId: ProviderInstanceId,
|
||||
next: {
|
||||
readonly hiddenModels: ReadonlyArray<string>;
|
||||
readonly modelOrder: ReadonlyArray<string>;
|
||||
},
|
||||
) => {
|
||||
const hiddenModels = [...new Set(next.hiddenModels.filter((slug) => slug.trim().length > 0))];
|
||||
const modelOrder = [...new Set(next.modelOrder.filter((slug) => slug.trim().length > 0))];
|
||||
const rest = withoutProviderInstanceKey(settings.providerModelPreferences, instanceId);
|
||||
updateSettings({
|
||||
providerModelPreferences:
|
||||
hiddenModels.length === 0 && modelOrder.length === 0
|
||||
? rest
|
||||
: {
|
||||
...rest,
|
||||
[instanceId]: {
|
||||
hiddenModels,
|
||||
modelOrder,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const updateProviderFavoriteModels = (
|
||||
instanceId: ProviderInstanceId,
|
||||
nextFavoriteModels: ReadonlyArray<string>,
|
||||
) => {
|
||||
const favoriteModels = [
|
||||
...new Set(nextFavoriteModels.map((slug) => slug.trim()).filter((slug) => slug.length > 0)),
|
||||
];
|
||||
updateSettings({
|
||||
favorites: [
|
||||
...withoutProviderInstanceFavorites(settings.favorites ?? [], instanceId),
|
||||
...favoriteModels.map((model) => ({ provider: instanceId, model })),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const resetDefaultInstance = (driverKind: ProviderDriverKind) => {
|
||||
type LegacyProviderSettings = (typeof settings.providers)[keyof typeof settings.providers];
|
||||
const defaultLegacyProviders = DEFAULT_UNIFIED_SETTINGS.providers as Record<
|
||||
string,
|
||||
LegacyProviderSettings | undefined
|
||||
>;
|
||||
const defaultInstanceId = defaultInstanceIdForDriver(driverKind);
|
||||
const defaultLegacyProvider = defaultLegacyProviders[driverKind];
|
||||
if (defaultLegacyProvider === undefined) return;
|
||||
updateSettings({
|
||||
providers: {
|
||||
...settings.providers,
|
||||
[driverKind]: defaultLegacyProvider,
|
||||
} as typeof settings.providers,
|
||||
providerInstances: withoutProviderInstanceKey(settings.providerInstances, defaultInstanceId),
|
||||
providerModelPreferences: withoutProviderInstanceKey(
|
||||
settings.providerModelPreferences,
|
||||
defaultInstanceId,
|
||||
),
|
||||
favorites: withoutProviderInstanceFavorites(settings.favorites ?? [], defaultInstanceId),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection
|
||||
title="Providers"
|
||||
headerAction={
|
||||
@@ -1218,6 +1188,23 @@ export function GeneralSettingsPanel() {
|
||||
const liveProvider = serverProviders.find(
|
||||
(candidate) => candidate.instanceId === row.instanceId,
|
||||
);
|
||||
const updateCandidate = liveProvider
|
||||
? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
|
||||
: undefined;
|
||||
const isDriverUpdateRunning =
|
||||
updateCandidate !== undefined &&
|
||||
(updatingProviderDrivers.has(updateCandidate.driver) ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
|
||||
));
|
||||
const showInlineUpdateButton =
|
||||
updateCandidate !== undefined &&
|
||||
hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
|
||||
const canRunInlineUpdate =
|
||||
updateCandidate !== undefined &&
|
||||
canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
|
||||
!updatingProviderDrivers.has(updateCandidate.driver);
|
||||
const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
|
||||
hiddenModels: [],
|
||||
modelOrder: [],
|
||||
@@ -1248,13 +1235,6 @@ export function GeneralSettingsPanel() {
|
||||
}))
|
||||
}
|
||||
onUpdate={(next) => {
|
||||
// When the user disables the exact instance the text-gen
|
||||
// selection points at, fall back to the global default so we
|
||||
// don't leave the selection dangling on a disabled instance.
|
||||
// Prior kind-level behavior cleared on any kind-matching
|
||||
// disable; instance-level addressing makes this narrower and
|
||||
// more accurate (other instances of the same kind stay
|
||||
// untouched).
|
||||
const wasEnabled = row.instance.enabled ?? true;
|
||||
const isDisabling = next.enabled === false && wasEnabled;
|
||||
const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;
|
||||
@@ -1287,6 +1267,17 @@ export function GeneralSettingsPanel() {
|
||||
modelOrder,
|
||||
})
|
||||
}
|
||||
onRunUpdate={
|
||||
showInlineUpdateButton && updateCandidate
|
||||
? () => {
|
||||
if (!canRunInlineUpdate) {
|
||||
return;
|
||||
}
|
||||
void runProviderUpdate(updateCandidate);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
isUpdating={showInlineUpdateButton ? isDriverUpdateRunning : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -1296,70 +1287,6 @@ export function GeneralSettingsPanel() {
|
||||
open={isAddInstanceDialogOpen}
|
||||
onOpenChange={setIsAddInstanceDialogOpen}
|
||||
/>
|
||||
|
||||
<SettingsSection title="Advanced">
|
||||
<SettingsRow
|
||||
title="Keybindings"
|
||||
description="Open the persisted `keybindings.json` file to edit advanced bindings directly."
|
||||
status={
|
||||
<>
|
||||
<span className="block break-all font-mono text-[11px] text-foreground">
|
||||
{keybindingsConfigPath ?? "Resolving keybindings path..."}
|
||||
</span>
|
||||
{openKeybindingsError ? (
|
||||
<span className="mt-1 block text-destructive">{openKeybindingsError}</span>
|
||||
) : (
|
||||
<span className="mt-1 block">Opens in your preferred editor.</span>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
control={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!keybindingsConfigPath || isOpeningKeybindings}
|
||||
onClick={openKeybindingsFile}
|
||||
>
|
||||
{isOpeningKeybindings ? "Opening..." : "Open file"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="About">
|
||||
{isElectron ? (
|
||||
<AboutVersionSection />
|
||||
) : (
|
||||
<SettingsRow
|
||||
title={<AboutVersionTitle />}
|
||||
description="Current version of the application."
|
||||
/>
|
||||
)}
|
||||
<SettingsRow
|
||||
title="Diagnostics"
|
||||
description={diagnosticsDescription}
|
||||
status={
|
||||
<>
|
||||
<span className="block break-all font-mono text-[11px] text-foreground">
|
||||
{logsDirectoryPath ?? "Resolving logs directory..."}
|
||||
</span>
|
||||
{openDiagnosticsError ? (
|
||||
<span className="mt-1 block text-destructive">{openDiagnosticsError}</span>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
control={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!logsDirectoryPath || isOpeningLogsDirectory}
|
||||
onClick={openLogsDirectory}
|
||||
>
|
||||
{isOpeningLogsDirectory ? "Opening..." : "Open logs folder"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { useCallback, type ComponentType } from "react";
|
||||
import { ArchiveIcon, ArrowLeftIcon, GitBranchIcon, Link2Icon, Settings2Icon } from "lucide-react";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArrowLeftIcon,
|
||||
BotIcon,
|
||||
GitBranchIcon,
|
||||
KeyboardIcon,
|
||||
Link2Icon,
|
||||
Settings2Icon,
|
||||
} from "lucide-react";
|
||||
import { useCanGoBack, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import {
|
||||
@@ -15,6 +23,8 @@ import {
|
||||
|
||||
export type SettingsSectionPath =
|
||||
| "/settings/general"
|
||||
| "/settings/keybindings"
|
||||
| "/settings/providers"
|
||||
| "/settings/source-control"
|
||||
| "/settings/connections"
|
||||
| "/settings/archived";
|
||||
@@ -25,6 +35,8 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
}> = [
|
||||
{ label: "General", to: "/settings/general", icon: Settings2Icon },
|
||||
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
|
||||
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
|
||||
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
|
||||
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
|
||||
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import type { ServerProvider, ServerProviderVersionAdvisory } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* Visual treatment for each server-reported provider status. Centralized so
|
||||
@@ -89,3 +89,29 @@ export function getProviderVersionLabel(version: string | null | undefined) {
|
||||
if (!version) return null;
|
||||
return version.startsWith("v") ? version : `v${version}`;
|
||||
}
|
||||
|
||||
export function getProviderVersionAdvisoryPresentation(
|
||||
advisory: ServerProviderVersionAdvisory | undefined,
|
||||
): {
|
||||
readonly detail: string;
|
||||
readonly updateCommand: string | null;
|
||||
readonly emphasis: "normal" | "strong";
|
||||
} | null {
|
||||
if (!advisory || advisory.status === "current" || advisory.status === "unknown") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const label = "Update available";
|
||||
const version = advisory.latestVersion;
|
||||
const versionLabel = getProviderVersionLabel(version);
|
||||
|
||||
return {
|
||||
detail:
|
||||
advisory.message ??
|
||||
(versionLabel
|
||||
? `${label}: install ${versionLabel}.`
|
||||
: `${label}: install the latest provider version.`),
|
||||
updateCommand: advisory.updateCommand,
|
||||
emphasis: "normal" as const,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Undo2Icon } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useState } from "react";
|
||||
import { type ComponentPropsWithoutRef, type ReactNode, useEffect, useState } from "react";
|
||||
|
||||
import { cn } from "../../lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
@@ -20,15 +20,17 @@ export function SettingsSection({
|
||||
icon,
|
||||
headerAction,
|
||||
children,
|
||||
}: {
|
||||
className,
|
||||
...sectionProps
|
||||
}: ComponentPropsWithoutRef<"section"> & {
|
||||
title: string;
|
||||
icon?: ReactNode;
|
||||
headerAction?: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="space-y-2.5">
|
||||
<div className="flex h-5 items-center justify-between px-1">
|
||||
<section {...sectionProps} className={cn("space-y-2.5", className)}>
|
||||
<div className="flex items-center justify-between px-1">
|
||||
<h2 className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-foreground/50">
|
||||
<span className="inline-block h-px w-3 bg-border" aria-hidden />
|
||||
{icon}
|
||||
@@ -62,7 +64,7 @@ export function SettingsRow({
|
||||
<div
|
||||
className={cn(
|
||||
"border-t border-border/60 px-4 first:border-t-0 sm:px-5",
|
||||
children ? "pt-4 pb-0" : "py-4",
|
||||
children ? "pt-3.5 pb-0" : "py-3.5",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
@@ -75,7 +77,7 @@ export function SettingsRow({
|
||||
{resetAction}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground/80">{description}</p>
|
||||
<p className="text-xs text-muted-foreground/80">{description}</p>
|
||||
{status ? <div className="pt-0.5 text-[11px] text-muted-foreground">{status}</div> : null}
|
||||
</div>
|
||||
{control ? (
|
||||
@@ -113,10 +115,18 @@ export function SettingResetButton({ label, onClick }: { label: string; onClick:
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsPageContainer({ children }: { children: ReactNode }) {
|
||||
export function SettingsPageContainer({
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto p-6 sm:p-8">
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-8">{children}</div>
|
||||
<div className={cn("mx-auto flex w-full max-w-3xl flex-col gap-8", className)}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { CircleCheckIcon, DownloadIcon, LoaderIcon, TriangleAlertIcon, XIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useState, type CSSProperties } from "react";
|
||||
|
||||
import { useServerProviders } from "../../rpc/serverState";
|
||||
import {
|
||||
getProviderUpdateSidebarPillView,
|
||||
type ProviderUpdateSidebarPillView,
|
||||
} from "../ProviderUpdateLaunchNotification.logic";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
|
||||
const PROVIDER_UPDATE_PILL_STYLES = {
|
||||
loading:
|
||||
"bg-primary/15 text-primary group-has-[button.provider-update-main:hover]/provider-update:bg-primary/22",
|
||||
success:
|
||||
"bg-success/12 text-success group-has-[button.provider-update-main:hover]/provider-update:bg-success/18",
|
||||
warning:
|
||||
"bg-warning/12 text-warning group-has-[button.provider-update-main:hover]/provider-update:bg-warning/18",
|
||||
error:
|
||||
"bg-destructive/12 text-destructive group-has-[button.provider-update-main:hover]/provider-update:bg-destructive/18",
|
||||
} as const;
|
||||
|
||||
const PROVIDER_UPDATE_PILL_PROGRESS_STYLES = {
|
||||
success: "bg-success/18",
|
||||
warning: "bg-warning/14",
|
||||
error: "bg-destructive/14",
|
||||
} as const;
|
||||
|
||||
function latestProviderCheckedAt(
|
||||
providers: ReadonlyArray<Pick<ServerProvider, "checkedAt">>,
|
||||
): string | undefined {
|
||||
return providers.reduce<string | undefined>(
|
||||
(latest, provider) =>
|
||||
latest === undefined || provider.checkedAt > latest ? provider.checkedAt : latest,
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
|
||||
export function SidebarProviderUpdatePill() {
|
||||
const navigate = useNavigate();
|
||||
const providers = useServerProviders();
|
||||
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;
|
||||
const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;
|
||||
const viewKey = displayedView?.key ?? null;
|
||||
const showDismissProgress =
|
||||
dismissAfterVisibleMs !== undefined &&
|
||||
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],
|
||||
);
|
||||
|
||||
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]);
|
||||
|
||||
if (!displayedView) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group/provider-update relative flex h-7 w-full items-center overflow-hidden rounded-lg text-xs font-medium transform-gpu transition-all duration-180 ease-[cubic-bezier(0.22,1,0.36,1)] will-change-transform ${
|
||||
PROVIDER_UPDATE_PILL_STYLES[displayedView.tone]
|
||||
} ${
|
||||
exitingKey === displayedView.key
|
||||
? "pointer-events-none translate-y-1.5 opacity-0"
|
||||
: "translate-y-0 opacity-100"
|
||||
}`}
|
||||
onTransitionEnd={(event) => {
|
||||
if (event.target !== event.currentTarget) {
|
||||
return;
|
||||
}
|
||||
if (!displayedView || exitingKey !== displayedView.key) {
|
||||
return;
|
||||
}
|
||||
if (dismissAfterExitKey === displayedView.key) {
|
||||
setDismissedKeys((previous) => new Set(previous).add(displayedView.key));
|
||||
}
|
||||
setRenderedView(pendingView);
|
||||
setPendingView(null);
|
||||
setExitingKey(null);
|
||||
setDismissAfterExitKey(null);
|
||||
}}
|
||||
>
|
||||
{showDismissProgress ? (
|
||||
<div
|
||||
key={displayedView.key}
|
||||
aria-hidden="true"
|
||||
className={`provider-update-pill-progress pointer-events-none absolute inset-y-0 left-0 w-full origin-left border-r border-current/15 shadow-[inset_0_1px_0_rgb(255_255_255_/_0.08)] ${
|
||||
PROVIDER_UPDATE_PILL_PROGRESS_STYLES[displayedView.tone]
|
||||
}`}
|
||||
style={
|
||||
{
|
||||
"--provider-update-pill-dismiss-ms": `${dismissAfterVisibleMs}ms`,
|
||||
} as CSSProperties
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<div className="pointer-events-none absolute inset-0 rounded-lg transition-colors" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
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}
|
||||
>
|
||||
{displayedView.tone === "loading" ? (
|
||||
<LoaderIcon className="size-3.5 animate-spin" />
|
||||
) : displayedView.tone === "success" ? (
|
||||
<CircleCheckIcon className="size-3.5" />
|
||||
) : displayedView.tone === "error" ? (
|
||||
<TriangleAlertIcon className="size-3.5" />
|
||||
) : (
|
||||
<DownloadIcon className="size-3.5" />
|
||||
)}
|
||||
<span>{displayedView.title}</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{displayedView.description}</TooltipPopup>
|
||||
</Tooltip>
|
||||
{displayedView.dismissible && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
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)}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Dismiss until provider status changes</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,11 +10,13 @@ function ScrollArea({
|
||||
scrollFade = false,
|
||||
scrollbarGutter = false,
|
||||
hideScrollbars = false,
|
||||
chainVerticalScroll = false,
|
||||
...props
|
||||
}: ScrollAreaPrimitive.Root.Props & {
|
||||
scrollFade?: boolean;
|
||||
scrollbarGutter?: boolean;
|
||||
hideScrollbars?: boolean;
|
||||
chainVerticalScroll?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
@@ -23,7 +25,8 @@ function ScrollArea({
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
className={cn(
|
||||
"h-full max-h-[inherit] overflow-y-auto overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
|
||||
"h-full max-h-[inherit] overflow-auto overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
|
||||
chainVerticalScroll && "overscroll-y-auto",
|
||||
scrollFade &&
|
||||
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",
|
||||
scrollbarGutter && "[scrollbar-gutter:stable]",
|
||||
|
||||
@@ -105,20 +105,24 @@ function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
|
||||
|
||||
function SelectPopup({
|
||||
className,
|
||||
popupClassName,
|
||||
children,
|
||||
side = "bottom",
|
||||
sideOffset = 4,
|
||||
align = "start",
|
||||
alignOffset = 0,
|
||||
alignItemWithTrigger = true,
|
||||
matchTriggerWidth = true,
|
||||
anchor,
|
||||
...props
|
||||
}: SelectPrimitive.Popup.Props & {
|
||||
popupClassName?: string;
|
||||
side?: SelectPrimitive.Positioner.Props["side"];
|
||||
sideOffset?: SelectPrimitive.Positioner.Props["sideOffset"];
|
||||
align?: SelectPrimitive.Positioner.Props["align"];
|
||||
alignOffset?: SelectPrimitive.Positioner.Props["alignOffset"];
|
||||
alignItemWithTrigger?: SelectPrimitive.Positioner.Props["alignItemWithTrigger"];
|
||||
matchTriggerWidth?: boolean;
|
||||
anchor?: SelectPrimitive.Positioner.Props["anchor"];
|
||||
}) {
|
||||
return (
|
||||
@@ -144,7 +148,13 @@ function SelectPopup({
|
||||
>
|
||||
<ChevronUpIcon className="relative size-4.5 sm:size-4" />
|
||||
</SelectPrimitive.ScrollUpArrow>
|
||||
<div className="relative h-full min-w-(--anchor-width) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">
|
||||
<div
|
||||
className={cn(
|
||||
"relative h-full rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
matchTriggerWidth && "min-w-(--anchor-width)",
|
||||
popupClassName,
|
||||
)}
|
||||
>
|
||||
<SelectPrimitive.List
|
||||
className={cn("max-h-(--available-height) overflow-y-auto p-1", className)}
|
||||
data-slot="select-list"
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
useMemo,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
type ComponentPropsWithoutRef,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
@@ -38,9 +39,20 @@ import {
|
||||
export type ThreadToastData = {
|
||||
threadRef?: ScopedThreadRef | null;
|
||||
threadId?: ThreadId | null;
|
||||
leadingIcon?: ReactNode;
|
||||
tooltipStyle?: boolean;
|
||||
onClose?: (() => void) | undefined;
|
||||
dismissAfterVisibleMs?: number;
|
||||
hideCopyButton?: boolean;
|
||||
secondaryActionProps?: ComponentPropsWithoutRef<"button">;
|
||||
secondaryActionVariant?:
|
||||
| "default"
|
||||
| "destructive"
|
||||
| "destructive-outline"
|
||||
| "ghost"
|
||||
| "link"
|
||||
| "outline"
|
||||
| "secondary";
|
||||
/** Optional extra body shown after toggling “Show details” (e.g. a list of pending RPCs). */
|
||||
expandableContent?: ReactNode;
|
||||
expandableLabels?: { expand?: string; collapse?: string };
|
||||
@@ -90,6 +102,15 @@ const toastCornerOrbClass = cn(
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
|
||||
);
|
||||
|
||||
function handleToastDismissClick(
|
||||
manager: typeof toastManager | typeof anchoredToastManager,
|
||||
toastId: ToastId,
|
||||
onClose: (() => void) | undefined,
|
||||
) {
|
||||
onClose?.();
|
||||
manager.close(toastId);
|
||||
}
|
||||
|
||||
function CopyErrorButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
|
||||
@@ -232,6 +253,7 @@ interface ToastBodyDescriptor {
|
||||
readonly Icon: ToastIconComponent | null | undefined;
|
||||
readonly stackedActionLayout: boolean;
|
||||
readonly actionVariant: NonNullable<ThreadToastData["actionVariant"]>;
|
||||
readonly secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]>;
|
||||
readonly copyErrorText: string | null;
|
||||
readonly hasTrailingControls: boolean;
|
||||
readonly inlineContentEndPad: string;
|
||||
@@ -248,16 +270,21 @@ function deriveToastBodyDescriptor(toast: {
|
||||
toast.actionProps !== undefined && toast.data?.actionLayout === "stacked-end";
|
||||
const actionVariant: NonNullable<ThreadToastData["actionVariant"]> =
|
||||
toast.data?.actionVariant ?? "default";
|
||||
const secondaryActionVariant: NonNullable<ThreadToastData["secondaryActionVariant"]> =
|
||||
toast.data?.secondaryActionVariant ?? "outline";
|
||||
const copyErrorText =
|
||||
toast.type === "error" && typeof toast.description === "string" && !toast.data?.hideCopyButton
|
||||
? toast.description
|
||||
: null;
|
||||
const hasTrailingControls = copyErrorText !== null || toast.actionProps !== undefined;
|
||||
const hasSecondaryAction = toast.data?.secondaryActionProps !== undefined;
|
||||
const hasTrailingControls =
|
||||
copyErrorText !== null || toast.actionProps !== undefined || hasSecondaryAction;
|
||||
const inlineContentEndPad = hasTrailingControls ? "pr-6" : "pr-10";
|
||||
return {
|
||||
Icon,
|
||||
stackedActionLayout,
|
||||
actionVariant,
|
||||
secondaryActionVariant,
|
||||
copyErrorText,
|
||||
hasTrailingControls,
|
||||
inlineContentEndPad,
|
||||
@@ -277,22 +304,35 @@ function ToastBodyContent({
|
||||
copyErrorText,
|
||||
actionProps,
|
||||
actionVariant,
|
||||
secondaryActionVariant,
|
||||
hasTrailingControls,
|
||||
toastData,
|
||||
toastDescription,
|
||||
toastType,
|
||||
}: ToastBodyContentProps) {
|
||||
const secondaryActionProps = toastData?.secondaryActionProps;
|
||||
const leadingIcon = toastData?.leadingIcon;
|
||||
const { className: secondaryActionClassName, ...secondaryActionRest } =
|
||||
secondaryActionProps ?? {};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={cn("flex min-w-0 gap-2", !stackedActionLayout && "flex-1")}>
|
||||
{Icon && (
|
||||
{leadingIcon ? (
|
||||
<div
|
||||
className="flex h-lh w-4 shrink-0 items-center justify-center"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
{leadingIcon}
|
||||
</div>
|
||||
) : Icon ? (
|
||||
<div
|
||||
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
|
||||
data-slot="toast-icon"
|
||||
>
|
||||
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 min-w-0 flex-1 flex-col gap-0.5",
|
||||
@@ -315,6 +355,16 @@ function ToastBodyContent({
|
||||
)}
|
||||
>
|
||||
{copyErrorText !== null ? <CopyErrorButton text={copyErrorText} /> : null}
|
||||
{secondaryActionProps ? (
|
||||
<button
|
||||
{...secondaryActionRest}
|
||||
className={cn(
|
||||
buttonVariants({ size: "xs", variant: secondaryActionVariant }),
|
||||
secondaryActionClassName,
|
||||
)}
|
||||
type="button"
|
||||
/>
|
||||
) : null}
|
||||
{actionProps ? (
|
||||
<Toast.Action
|
||||
className={cn(buttonVariants({ size: "xs", variant: actionVariant }), "shrink-0")}
|
||||
@@ -579,7 +629,9 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
aria-label="Dismiss notification"
|
||||
className={toastCornerOrbClass}
|
||||
data-slot="toast-close"
|
||||
onClick={() => toastManager.close(toast.id)}
|
||||
onClick={() =>
|
||||
handleToastDismissClick(toastManager, toast.id, toast.data?.onClose)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
<XIcon className="size-3" strokeWidth={2.25} />
|
||||
@@ -670,7 +722,13 @@ function AnchoredToasts() {
|
||||
aria-label="Dismiss notification"
|
||||
className={toastCornerOrbClass}
|
||||
data-slot="toast-close"
|
||||
onClick={() => anchoredToastManager.close(toast.id)}
|
||||
onClick={() =>
|
||||
handleToastDismissClick(
|
||||
anchoredToastManager,
|
||||
toast.id,
|
||||
toast.data?.onClose,
|
||||
)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
<XIcon className="size-3" strokeWidth={2.25} />
|
||||
|
||||
@@ -134,9 +134,14 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => {
|
||||
server: {
|
||||
getConfig: vi.fn(),
|
||||
refreshProviders: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
upsertKeybinding: vi.fn(),
|
||||
removeKeybinding: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
getTraceDiagnostics: vi.fn(),
|
||||
getProcessDiagnostics: vi.fn(),
|
||||
signalProcess: vi.fn(),
|
||||
discoverSourceControl: vi.fn(),
|
||||
subscribeConfig: vi.fn(() => () => undefined),
|
||||
subscribeLifecycle: vi.fn(() => () => undefined),
|
||||
|
||||
@@ -26,6 +26,7 @@ import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
const clientSettingsListeners = new Set<() => void>();
|
||||
const clientSettingsHydrationListeners = new Set<() => void>();
|
||||
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
let clientSettingsHydrated = false;
|
||||
let clientSettingsHydrationPromise: Promise<void> | null = null;
|
||||
@@ -36,6 +37,12 @@ function emitClientSettingsChange() {
|
||||
}
|
||||
}
|
||||
|
||||
function emitClientSettingsHydrationChange() {
|
||||
for (const listener of clientSettingsHydrationListeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function getClientSettingsSnapshot(): ClientSettings {
|
||||
return clientSettingsSnapshot;
|
||||
}
|
||||
@@ -45,6 +52,14 @@ function replaceClientSettingsSnapshot(settings: ClientSettings): void {
|
||||
emitClientSettingsChange();
|
||||
}
|
||||
|
||||
function setClientSettingsHydrated(nextHydrated: boolean): void {
|
||||
if (clientSettingsHydrated === nextHydrated) {
|
||||
return;
|
||||
}
|
||||
clientSettingsHydrated = nextHydrated;
|
||||
emitClientSettingsHydrationChange();
|
||||
}
|
||||
|
||||
function subscribeClientSettings(listener: () => void): () => void {
|
||||
clientSettingsListeners.add(listener);
|
||||
void hydrateClientSettings();
|
||||
@@ -53,6 +68,18 @@ function subscribeClientSettings(listener: () => void): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
function getClientSettingsHydratedSnapshot(): boolean {
|
||||
return clientSettingsHydrated;
|
||||
}
|
||||
|
||||
function subscribeClientSettingsHydration(listener: () => void): () => void {
|
||||
clientSettingsHydrationListeners.add(listener);
|
||||
void hydrateClientSettings();
|
||||
return () => {
|
||||
clientSettingsHydrationListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
async function hydrateClientSettings(): Promise<void> {
|
||||
if (clientSettingsHydrated) {
|
||||
return;
|
||||
@@ -70,7 +97,7 @@ async function hydrateClientSettings(): Promise<void> {
|
||||
} catch (error) {
|
||||
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
|
||||
} finally {
|
||||
clientSettingsHydrated = true;
|
||||
setClientSettingsHydrated(true);
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -132,6 +159,14 @@ export function getClientSettings(): ClientSettings {
|
||||
return getClientSettingsSnapshot();
|
||||
}
|
||||
|
||||
export function useClientSettingsHydrated(): boolean {
|
||||
return useSyncExternalStore(
|
||||
subscribeClientSettingsHydration,
|
||||
getClientSettingsHydratedSnapshot,
|
||||
() => false,
|
||||
);
|
||||
}
|
||||
|
||||
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
|
||||
const serverSettings = useServerSettings();
|
||||
const clientSettings = useSyncExternalStore(
|
||||
@@ -193,4 +228,5 @@ export function __resetClientSettingsPersistenceForTests(): void {
|
||||
clientSettingsHydrated = false;
|
||||
clientSettingsHydrationPromise = null;
|
||||
clientSettingsListeners.clear();
|
||||
clientSettingsHydrationListeners.clear();
|
||||
}
|
||||
@@ -485,6 +485,19 @@ label:has(> select#reasoning-effort) select {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
@keyframes provider-update-pill-countdown {
|
||||
from {
|
||||
transform: scaleX(1);
|
||||
}
|
||||
to {
|
||||
transform: scaleX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.provider-update-pill-progress {
|
||||
animation: provider-update-pill-countdown var(--provider-update-pill-dismiss-ms) linear forwards;
|
||||
}
|
||||
|
||||
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||
.diff-panel-viewport {
|
||||
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { ServerProcessDiagnosticsResult } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Option } from "effect";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { ensureLocalApi } from "../localApi";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
|
||||
const PROCESS_DIAGNOSTICS_STALE_TIME_MS = 2_000;
|
||||
const PROCESS_DIAGNOSTICS_IDLE_TTL_MS = 5 * 60_000;
|
||||
|
||||
const processDiagnosticsAtom = Atom.make(
|
||||
Effect.promise(() => ensureLocalApi().server.getProcessDiagnostics()),
|
||||
).pipe(
|
||||
Atom.swr({
|
||||
staleTime: PROCESS_DIAGNOSTICS_STALE_TIME_MS,
|
||||
revalidateOnMount: true,
|
||||
}),
|
||||
Atom.setIdleTTL(PROCESS_DIAGNOSTICS_IDLE_TTL_MS),
|
||||
Atom.withLabel("process-diagnostics"),
|
||||
);
|
||||
|
||||
export interface ProcessDiagnosticsState {
|
||||
readonly data: ServerProcessDiagnosticsResult | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
function formatProcessDiagnosticsError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "Failed to load process diagnostics.";
|
||||
}
|
||||
|
||||
function readProcessDiagnosticsError(
|
||||
result: AsyncResult.AsyncResult<ServerProcessDiagnosticsResult, unknown>,
|
||||
): string | null {
|
||||
if (result._tag !== "Failure") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const squashed = Cause.squash(result.cause);
|
||||
return formatProcessDiagnosticsError(squashed);
|
||||
}
|
||||
|
||||
export function refreshProcessDiagnostics(): void {
|
||||
appAtomRegistry.refresh(processDiagnosticsAtom);
|
||||
}
|
||||
|
||||
export function useProcessDiagnostics(): ProcessDiagnosticsState {
|
||||
const result = useAtomValue(processDiagnosticsAtom);
|
||||
const data = Option.getOrNull(AsyncResult.value(result));
|
||||
const refresh = useCallback(() => {
|
||||
refreshProcessDiagnostics();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
data,
|
||||
error: readProcessDiagnosticsError(result),
|
||||
isPending: result.waiting,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { ServerTraceDiagnosticsResult } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Option } from "effect";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { ensureLocalApi } from "../localApi";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
|
||||
const TRACE_DIAGNOSTICS_STALE_TIME_MS = 5_000;
|
||||
const TRACE_DIAGNOSTICS_IDLE_TTL_MS = 5 * 60_000;
|
||||
|
||||
const traceDiagnosticsAtom = Atom.make(
|
||||
Effect.promise(() => ensureLocalApi().server.getTraceDiagnostics()),
|
||||
).pipe(
|
||||
Atom.swr({
|
||||
staleTime: TRACE_DIAGNOSTICS_STALE_TIME_MS,
|
||||
revalidateOnMount: true,
|
||||
}),
|
||||
Atom.setIdleTTL(TRACE_DIAGNOSTICS_IDLE_TTL_MS),
|
||||
Atom.withLabel("trace-diagnostics"),
|
||||
);
|
||||
|
||||
export interface TraceDiagnosticsState {
|
||||
readonly data: ServerTraceDiagnosticsResult | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly refresh: () => void;
|
||||
}
|
||||
|
||||
function formatTraceDiagnosticsError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "Failed to load trace diagnostics.";
|
||||
}
|
||||
|
||||
function readTraceDiagnosticsError(
|
||||
result: AsyncResult.AsyncResult<ServerTraceDiagnosticsResult, unknown>,
|
||||
): string | null {
|
||||
if (result._tag !== "Failure") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const squashed = Cause.squash(result.cause);
|
||||
return formatTraceDiagnosticsError(squashed);
|
||||
}
|
||||
|
||||
export function refreshTraceDiagnostics(): void {
|
||||
appAtomRegistry.refresh(traceDiagnosticsAtom);
|
||||
}
|
||||
|
||||
export function useTraceDiagnostics(): TraceDiagnosticsState {
|
||||
const result = useAtomValue(traceDiagnosticsAtom);
|
||||
const data = Option.getOrNull(AsyncResult.value(result));
|
||||
const refresh = useCallback(() => {
|
||||
refreshTraceDiagnostics();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
data,
|
||||
error: readTraceDiagnosticsError(result),
|
||||
isPending: result.waiting,
|
||||
refresh,
|
||||
};
|
||||
}
|
||||
@@ -93,6 +93,7 @@ const rpcClientMock = {
|
||||
server: {
|
||||
getConfig: vi.fn(),
|
||||
refreshProviders: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
upsertKeybinding: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
@@ -545,6 +546,34 @@ describe("wsApi", () => {
|
||||
expect(rpcClientMock.server.refreshProviders).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it("forwards provider updates directly to the RPC client", async () => {
|
||||
const nextProviders: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
...defaultProviders[0]!,
|
||||
updateState: {
|
||||
status: "succeeded",
|
||||
startedAt: "2026-01-03T00:00:00.000Z",
|
||||
finishedAt: "2026-01-03T00:00:01.000Z",
|
||||
message: "Provider updated.",
|
||||
output: null,
|
||||
},
|
||||
},
|
||||
];
|
||||
rpcClientMock.server.updateProvider.mockResolvedValue({ providers: nextProviders });
|
||||
const { createLocalApi } = await import("./localApi");
|
||||
|
||||
const api = createLocalApi(rpcClientMock as never);
|
||||
|
||||
await expect(
|
||||
api.server.updateProvider({ provider: ProviderDriverKind.make("codex") }),
|
||||
).resolves.toEqual({
|
||||
providers: nextProviders,
|
||||
});
|
||||
expect(rpcClientMock.server.updateProvider).toHaveBeenCalledWith({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards server settings updates directly to the RPC client", async () => {
|
||||
const nextSettings = {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
@@ -604,6 +633,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
@@ -665,6 +695,7 @@ describe("wsApi", () => {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
|
||||
@@ -125,10 +125,18 @@ function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi {
|
||||
rpcClient
|
||||
? rpcClient.server.refreshProviders()
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
updateProvider: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.updateProvider(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
upsertKeybinding: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.upsertKeybinding(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
removeKeybinding: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.removeKeybinding(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
getSettings: () =>
|
||||
rpcClient ? rpcClient.server.getSettings() : Promise.reject(unavailableLocalBackendError()),
|
||||
updateSettings: (patch) =>
|
||||
@@ -139,6 +147,18 @@ function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi {
|
||||
rpcClient
|
||||
? rpcClient.server.discoverSourceControl()
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
getTraceDiagnostics: () =>
|
||||
rpcClient
|
||||
? rpcClient.server.getTraceDiagnostics()
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
getProcessDiagnostics: () =>
|
||||
rpcClient
|
||||
? rpcClient.server.getProcessDiagnostics()
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
signalProcess: (input) =>
|
||||
rpcClient
|
||||
? rpcClient.server.signalProcess(input)
|
||||
: Promise.reject(unavailableLocalBackendError()),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -18,6 +18,20 @@ describe("rewriteMarkdownFileUriHref", () => {
|
||||
"/Users/julius/project/file%2520name.md",
|
||||
);
|
||||
});
|
||||
|
||||
it("normalizes file uri hrefs for windows drive paths", () => {
|
||||
expect(
|
||||
rewriteMarkdownFileUriHref(
|
||||
"file:///D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69",
|
||||
),
|
||||
).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69");
|
||||
});
|
||||
|
||||
it("unwraps angle-bracketed file uri hrefs", () => {
|
||||
expect(
|
||||
rewriteMarkdownFileUriHref(" <file:///D:/Programme/t3code/apps/web/src/markdown-links.ts> "),
|
||||
).toBe("D:/Programme/t3code/apps/web/src/markdown-links.ts");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveMarkdownFileLinkTarget", () => {
|
||||
@@ -84,6 +98,22 @@ describe("resolveMarkdownFileLinkTarget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes slash-prefixed windows drive paths before resolving", () => {
|
||||
expect(
|
||||
resolveMarkdownFileLinkTarget(
|
||||
"/D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69",
|
||||
),
|
||||
).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx:69");
|
||||
});
|
||||
|
||||
it("resolves angle-bracketed windows drive paths", () => {
|
||||
expect(
|
||||
resolveMarkdownFileLinkTarget(
|
||||
"</D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1>",
|
||||
),
|
||||
).toBe("D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1");
|
||||
});
|
||||
|
||||
it("does not treat app routes as file links", () => {
|
||||
expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -39,6 +39,14 @@ function safeDecode(value: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function unwrapMarkdownLinkDestination(value: string): string {
|
||||
return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
|
||||
}
|
||||
|
||||
export function normalizeMarkdownLinkDestination(value: string): string {
|
||||
return unwrapMarkdownLinkDestination(value.trim());
|
||||
}
|
||||
|
||||
function stripSearchAndHash(value: string): { path: string; hash: string } {
|
||||
const hashIndex = value.indexOf("#");
|
||||
const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
|
||||
@@ -48,6 +56,10 @@ function stripSearchAndHash(value: string): { path: string; hash: string } {
|
||||
return { path, hash: rawHash };
|
||||
}
|
||||
|
||||
function normalizeWindowsDrivePath(path: string): string {
|
||||
return /^\/[A-Za-z]:[\\/]/.test(path) ? path.slice(1) : path;
|
||||
}
|
||||
|
||||
function parseFileUrlHref(
|
||||
href: string,
|
||||
options?: { readonly decodePath?: boolean },
|
||||
@@ -60,7 +72,7 @@ function parseFileUrlHref(
|
||||
if (rawPath.length === 0) return null;
|
||||
|
||||
// Browser URL parser encodes "C:/foo" as "/C:/foo" for file URLs.
|
||||
const normalizedPath = /^\/[A-Za-z]:[\\/]/.test(rawPath) ? rawPath.slice(1) : rawPath;
|
||||
const normalizedPath = normalizeWindowsDrivePath(rawPath);
|
||||
|
||||
return {
|
||||
path: options?.decodePath === false ? normalizedPath : safeDecode(normalizedPath),
|
||||
@@ -73,7 +85,8 @@ function parseFileUrlHref(
|
||||
|
||||
export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {
|
||||
if (!href) return null;
|
||||
const target = parseFileUrlHref(href.trim(), { decodePath: false });
|
||||
const normalizedHref = normalizeMarkdownLinkDestination(href);
|
||||
const target = parseFileUrlHref(normalizedHref, { decodePath: false });
|
||||
if (!target) return null;
|
||||
return `${target.path}${target.hash}`;
|
||||
}
|
||||
@@ -124,14 +137,16 @@ export function resolveMarkdownFileLinkTarget(
|
||||
cwd?: string,
|
||||
): string | null {
|
||||
if (!href) return null;
|
||||
const rawHref = href.trim();
|
||||
const rawHref = normalizeMarkdownLinkDestination(href);
|
||||
if (rawHref.length === 0 || rawHref.startsWith("#")) return null;
|
||||
|
||||
const fileUrlTarget = rawHref.toLowerCase().startsWith("file:")
|
||||
? parseFileUrlHref(rawHref)
|
||||
: null;
|
||||
const source = fileUrlTarget ?? stripSearchAndHash(rawHref);
|
||||
const decodedPath = fileUrlTarget ? source.path.trim() : safeDecode(source.path.trim());
|
||||
const decodedPath = normalizeWindowsDrivePath(
|
||||
fileUrlTarget ? source.path.trim() : safeDecode(source.path.trim()),
|
||||
);
|
||||
const decodedHash = safeDecode(source.hash.trim());
|
||||
|
||||
if (decodedPath.length === 0) return null;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { removeLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import {
|
||||
dismissProviderUpdateNotification,
|
||||
isProviderUpdateNotificationDismissed,
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
} from "./providerUpdateDismissal";
|
||||
|
||||
describe("providerUpdateDismissal", () => {
|
||||
beforeEach(() => {
|
||||
removeLocalStorageItem(PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY);
|
||||
});
|
||||
|
||||
it("persists provider update dismissals by notification key", () => {
|
||||
expect(isProviderUpdateNotificationDismissed("opencode:1.14.33")).toBe(false);
|
||||
|
||||
dismissProviderUpdateNotification("opencode:1.14.33");
|
||||
|
||||
expect(isProviderUpdateNotificationDismissed("opencode:1.14.33")).toBe(true);
|
||||
expect(isProviderUpdateNotificationDismissed("opencode:1.14.34")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
|
||||
|
||||
export const PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY = "t3code:provider-update-dismissals:v1";
|
||||
|
||||
const ProviderUpdateDismissalsSchema = Schema.Struct({
|
||||
keys: Schema.Array(Schema.String),
|
||||
});
|
||||
|
||||
type ProviderUpdateDismissals = typeof ProviderUpdateDismissalsSchema.Type;
|
||||
|
||||
function readProviderUpdateDismissals(): ProviderUpdateDismissals {
|
||||
try {
|
||||
return (
|
||||
getLocalStorageItem(
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
ProviderUpdateDismissalsSchema,
|
||||
) ?? {
|
||||
keys: [],
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
return { keys: [] };
|
||||
}
|
||||
}
|
||||
|
||||
function writeProviderUpdateDismissals(document: ProviderUpdateDismissals): void {
|
||||
try {
|
||||
setLocalStorageItem(
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
document,
|
||||
ProviderUpdateDismissalsSchema,
|
||||
);
|
||||
} catch {
|
||||
// Dismissal state is best-effort UI state; a storage failure should not block the toast.
|
||||
}
|
||||
}
|
||||
|
||||
export function isProviderUpdateNotificationDismissed(
|
||||
dismissalKey: string | null | undefined,
|
||||
): boolean {
|
||||
if (!dismissalKey) {
|
||||
return false;
|
||||
}
|
||||
return readProviderUpdateDismissals().keys.includes(dismissalKey);
|
||||
}
|
||||
|
||||
export function dismissProviderUpdateNotification(dismissalKey: string | null | undefined): void {
|
||||
const trimmedKey = dismissalKey?.trim();
|
||||
if (!trimmedKey) {
|
||||
return;
|
||||
}
|
||||
const document = readProviderUpdateDismissals();
|
||||
if (document.keys.includes(trimmedKey)) {
|
||||
return;
|
||||
}
|
||||
writeProviderUpdateDismissals({
|
||||
keys: [...document.keys, trimmedKey],
|
||||
});
|
||||
}
|
||||
|
||||
export function useDismissedProviderUpdateNotificationKeys() {
|
||||
const [dismissals, setDismissals] = useLocalStorage(
|
||||
PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,
|
||||
{ keys: [] },
|
||||
ProviderUpdateDismissalsSchema,
|
||||
);
|
||||
const dismissedKeys = dismissals.keys;
|
||||
|
||||
const dismissedKeySet = useMemo(() => new Set(dismissedKeys), [dismissedKeys]);
|
||||
|
||||
const dismissNotificationKey = useCallback(
|
||||
(key: string) => {
|
||||
const trimmedKey = key.trim();
|
||||
if (trimmedKey.length === 0 || dismissedKeySet.has(trimmedKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDismissals({
|
||||
keys: [...dismissedKeys, trimmedKey],
|
||||
});
|
||||
},
|
||||
[dismissedKeySet, dismissedKeys, setDismissals],
|
||||
);
|
||||
|
||||
return {
|
||||
dismissedNotificationKeys: dismissedKeySet,
|
||||
dismissNotificationKey,
|
||||
};
|
||||
}
|
||||
@@ -14,7 +14,10 @@ import { Route as PairRouteImport } from './routes/pair'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
|
||||
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
|
||||
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
|
||||
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
|
||||
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
|
||||
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
|
||||
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
|
||||
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
|
||||
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
|
||||
@@ -44,11 +47,26 @@ const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
|
||||
path: '/source-control',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsProvidersRoute = SettingsProvidersRouteImport.update({
|
||||
id: '/providers',
|
||||
path: '/providers',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsKeybindingsRoute = SettingsKeybindingsRouteImport.update({
|
||||
id: '/keybindings',
|
||||
path: '/keybindings',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
|
||||
id: '/general',
|
||||
path: '/general',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsDiagnosticsRoute = SettingsDiagnosticsRouteImport.update({
|
||||
id: '/diagnostics',
|
||||
path: '/diagnostics',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
|
||||
id: '/connections',
|
||||
path: '/connections',
|
||||
@@ -77,7 +95,10 @@ export interface FileRoutesByFullPath {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
'/draft/$draftId': typeof ChatDraftDraftIdRoute
|
||||
@@ -87,7 +108,10 @@ export interface FileRoutesByTo {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/': typeof ChatIndexRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
@@ -100,7 +124,10 @@ export interface FileRoutesById {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/connections': typeof SettingsConnectionsRoute
|
||||
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/_chat/': typeof ChatIndexRoute
|
||||
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
@@ -114,7 +141,10 @@ export interface FileRouteTypes {
|
||||
| '/settings'
|
||||
| '/settings/archived'
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/$environmentId/$threadId'
|
||||
| '/draft/$draftId'
|
||||
@@ -124,7 +154,10 @@ export interface FileRouteTypes {
|
||||
| '/settings'
|
||||
| '/settings/archived'
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/'
|
||||
| '/$environmentId/$threadId'
|
||||
@@ -136,7 +169,10 @@ export interface FileRouteTypes {
|
||||
| '/settings'
|
||||
| '/settings/archived'
|
||||
| '/settings/connections'
|
||||
| '/settings/diagnostics'
|
||||
| '/settings/general'
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/_chat/'
|
||||
| '/_chat/$environmentId/$threadId'
|
||||
@@ -186,6 +222,20 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsSourceControlRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/providers': {
|
||||
id: '/settings/providers'
|
||||
path: '/providers'
|
||||
fullPath: '/settings/providers'
|
||||
preLoaderRoute: typeof SettingsProvidersRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/keybindings': {
|
||||
id: '/settings/keybindings'
|
||||
path: '/keybindings'
|
||||
fullPath: '/settings/keybindings'
|
||||
preLoaderRoute: typeof SettingsKeybindingsRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/general': {
|
||||
id: '/settings/general'
|
||||
path: '/general'
|
||||
@@ -193,6 +243,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsGeneralRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/diagnostics': {
|
||||
id: '/settings/diagnostics'
|
||||
path: '/diagnostics'
|
||||
fullPath: '/settings/diagnostics'
|
||||
preLoaderRoute: typeof SettingsDiagnosticsRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/connections': {
|
||||
id: '/settings/connections'
|
||||
path: '/connections'
|
||||
@@ -241,14 +298,20 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
|
||||
interface SettingsRouteChildren {
|
||||
SettingsArchivedRoute: typeof SettingsArchivedRoute
|
||||
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
|
||||
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
|
||||
SettingsGeneralRoute: typeof SettingsGeneralRoute
|
||||
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
|
||||
SettingsProvidersRoute: typeof SettingsProvidersRoute
|
||||
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
|
||||
}
|
||||
|
||||
const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsArchivedRoute: SettingsArchivedRoute,
|
||||
SettingsConnectionsRoute: SettingsConnectionsRoute,
|
||||
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
|
||||
SettingsGeneralRoute: SettingsGeneralRoute,
|
||||
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
|
||||
SettingsProvidersRoute: SettingsProvidersRoute,
|
||||
SettingsSourceControlRoute: SettingsSourceControlRoute,
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { APP_DISPLAY_NAME } from "../branding";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import { CommandPalette } from "../components/CommandPalette";
|
||||
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
|
||||
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
|
||||
import {
|
||||
SlowRpcAckToastCoordinator,
|
||||
WebSocketConnectionCoordinator,
|
||||
@@ -136,6 +137,7 @@ function RootRouteView() {
|
||||
<SshPasswordPromptDialog />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <WebSocketConnectionCoordinator /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <SlowRpcAckToastCoordinator /> : null}
|
||||
{primaryEnvironmentAuthenticated ? (
|
||||
@@ -286,6 +288,7 @@ function EventRouter() {
|
||||
const readPathname = useEffectEvent(() => pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
|
||||
const lastKeybindingsSuccessToastAtRef = useRef(0);
|
||||
const disposedRef = useRef(false);
|
||||
const serverConfig = useServerConfig();
|
||||
|
||||
@@ -352,6 +355,11 @@ function EventRouter() {
|
||||
|
||||
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
|
||||
if (!issue) {
|
||||
const now = Date.now();
|
||||
if (now - lastKeybindingsSuccessToastAtRef.current < 2_000) {
|
||||
return;
|
||||
}
|
||||
lastKeybindingsSuccessToastAtRef.current = now;
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Keybindings updated",
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { DiagnosticsSettingsPanel } from "../components/settings/DiagnosticsSettings";
|
||||
|
||||
export const Route = createFileRoute("/settings/diagnostics")({
|
||||
component: DiagnosticsSettingsPanel,
|
||||
});
|
||||
@@ -2,6 +2,10 @@ import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { GeneralSettingsPanel } from "../components/settings/SettingsPanels";
|
||||
|
||||
function SettingsGeneralRoute() {
|
||||
return <GeneralSettingsPanel />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/settings/general")({
|
||||
component: GeneralSettingsPanel,
|
||||
component: SettingsGeneralRoute,
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { KeybindingsSettingsPanel } from "../components/settings/KeybindingsSettings";
|
||||
|
||||
export const Route = createFileRoute("/settings/keybindings")({
|
||||
component: KeybindingsSettingsPanel,
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { ProviderSettingsPanel } from "../components/settings/SettingsPanels";
|
||||
|
||||
function SettingsProvidersRoute() {
|
||||
return <ProviderSettingsPanel />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/settings/providers")({
|
||||
component: SettingsProvidersRoute,
|
||||
});
|
||||
@@ -122,7 +122,9 @@ export interface WsRpcClient {
|
||||
readonly refreshProviders: (
|
||||
input?: RpcInput<typeof WS_METHODS.serverRefreshProviders>,
|
||||
) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverRefreshProviders>>;
|
||||
readonly updateProvider: RpcUnaryMethod<typeof WS_METHODS.serverUpdateProvider>;
|
||||
readonly upsertKeybinding: RpcUnaryMethod<typeof WS_METHODS.serverUpsertKeybinding>;
|
||||
readonly removeKeybinding: RpcUnaryMethod<typeof WS_METHODS.serverRemoveKeybinding>;
|
||||
readonly getSettings: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetSettings>;
|
||||
readonly updateSettings: (
|
||||
patch: ServerSettingsPatch,
|
||||
@@ -130,6 +132,11 @@ export interface WsRpcClient {
|
||||
readonly discoverSourceControl: RpcUnaryNoArgMethod<
|
||||
typeof WS_METHODS.serverDiscoverSourceControl
|
||||
>;
|
||||
readonly getTraceDiagnostics: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetTraceDiagnostics>;
|
||||
readonly getProcessDiagnostics: RpcUnaryNoArgMethod<
|
||||
typeof WS_METHODS.serverGetProcessDiagnostics
|
||||
>;
|
||||
readonly signalProcess: RpcUnaryMethod<typeof WS_METHODS.serverSignalProcess>;
|
||||
readonly subscribeConfig: RpcStreamMethod<typeof WS_METHODS.subscribeServerConfig>;
|
||||
readonly subscribeLifecycle: RpcStreamMethod<typeof WS_METHODS.subscribeServerLifecycle>;
|
||||
readonly subscribeAuthAccess: RpcStreamMethod<typeof WS_METHODS.subscribeAuthAccess>;
|
||||
@@ -256,13 +263,29 @@ export function createWsRpcClient(
|
||||
getConfig: () => transport.request((client) => client[WS_METHODS.serverGetConfig]({})),
|
||||
refreshProviders: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverRefreshProviders](input ?? {})),
|
||||
updateProvider: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverUpdateProvider](input)),
|
||||
upsertKeybinding: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverUpsertKeybinding](input)),
|
||||
removeKeybinding: (input) =>
|
||||
transport.request((client) => client[WS_METHODS.serverRemoveKeybinding](input)),
|
||||
getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})),
|
||||
updateSettings: (patch) =>
|
||||
transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })),
|
||||
discoverSourceControl: () =>
|
||||
transport.request((client) => client[WS_METHODS.serverDiscoverSourceControl]({})),
|
||||
getTraceDiagnostics: () =>
|
||||
transport.request((client) =>
|
||||
client[WS_METHODS.serverGetTraceDiagnostics]({}).pipe(Effect.withTracerEnabled(false)),
|
||||
),
|
||||
getProcessDiagnostics: () =>
|
||||
transport.request((client) =>
|
||||
client[WS_METHODS.serverGetProcessDiagnostics]({}).pipe(Effect.withTracerEnabled(false)),
|
||||
),
|
||||
signalProcess: (input) =>
|
||||
transport.request((client) =>
|
||||
client[WS_METHODS.serverSignalProcess](input).pipe(Effect.withTracerEnabled(false)),
|
||||
),
|
||||
subscribeConfig: (listener, options) =>
|
||||
transport.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeServerConfig]({}),
|
||||
|
||||
@@ -27,6 +27,17 @@ export const EDITORS = [
|
||||
{ id: "zed", label: "Zed", commands: ["zed", "zeditor"], launchStyle: "direct-path" },
|
||||
{ id: "antigravity", label: "Antigravity", commands: ["agy"], launchStyle: "goto" },
|
||||
{ id: "idea", label: "IntelliJ IDEA", commands: ["idea"], launchStyle: "line-column" },
|
||||
{ id: "aqua", label: "Aqua", commands: ["aqua"], launchStyle: "line-column" },
|
||||
{ id: "clion", label: "CLion", commands: ["clion"], launchStyle: "line-column" },
|
||||
{ id: "datagrip", label: "DataGrip", commands: ["datagrip"], launchStyle: "line-column" },
|
||||
{ id: "dataspell", label: "DataSpell", commands: ["dataspell"], launchStyle: "line-column" },
|
||||
{ id: "goland", label: "GoLand", commands: ["goland"], launchStyle: "line-column" },
|
||||
{ id: "phpstorm", label: "PhpStorm", commands: ["phpstorm"], launchStyle: "line-column" },
|
||||
{ id: "pycharm", label: "PyCharm", commands: ["pycharm"], launchStyle: "line-column" },
|
||||
{ id: "rider", label: "Rider", commands: ["rider"], launchStyle: "line-column" },
|
||||
{ id: "rubymine", label: "RubyMine", commands: ["rubymine"], launchStyle: "line-column" },
|
||||
{ id: "rustrover", label: "RustRover", commands: ["rustrover"], launchStyle: "line-column" },
|
||||
{ id: "webstorm", label: "WebStorm", commands: ["webstorm"], launchStyle: "line-column" },
|
||||
{ id: "file-manager", label: "File Manager", commands: null, launchStyle: "direct-path" },
|
||||
] as const satisfies ReadonlyArray<EditorDefinition>;
|
||||
|
||||
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user