diff --git a/CLAUDE.md b/CLAUDE.md index 47dc3e3d86..c317064255 120000 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1 +1 @@ -AGENTS.md \ No newline at end of file +AGENTS.md diff --git a/README.md b/README.md index d7b2fccb8f..d3a54a1b90 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ We are very very early in this project. Expect bugs. We are not accepting contributions yet. +Observability guide: [docs/observability.md](./docs/observability.md) + ## If you REALLY want to contribute still.... read this first Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR. diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 34391a5995..3d61571df9 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -28,6 +28,7 @@ import { autoUpdater } from "electron-updater"; import type { ContextMenuItem } from "@t3tools/contracts"; import { NetService } from "@t3tools/shared/Net"; import { RotatingFileSink } from "@t3tools/shared/logging"; +import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; import { showDesktopConfirmDialog } from "./confirmDialog"; import { syncShellEnvironment } from "./syncShellEnvironment"; import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState"; @@ -76,6 +77,7 @@ const LOG_DIR = Path.join(STATE_DIR, "logs"); const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024; const LOG_FILE_MAX_FILES = 10; const APP_RUN_ID = Crypto.randomBytes(6).toString("hex"); +const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json"); const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000; const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000; const DESKTOP_UPDATE_CHANNEL = "latest"; @@ -99,8 +101,10 @@ let aboutCommitHashCache: string | null | undefined; let desktopLogSink: RotatingFileSink | null = null; let backendLogSink: RotatingFileSink | null = null; let restoreStdIoCapture: (() => void) | null = null; +let backendObservabilitySettings = readPersistedBackendObservabilitySettings(); let destructiveMenuIconCache: Electron.NativeImage | null | undefined; +const expectedBackendExitChildren = new WeakSet(); const desktopRuntimeInfo = resolveDesktopRuntimeInfo({ platform: process.platform, processArch: process.arch, @@ -121,6 +125,21 @@ function sanitizeLogValue(value: string): string { return value.replace(/\s+/g, " ").trim(); } +function readPersistedBackendObservabilitySettings(): { + readonly otlpTracesUrl: string | undefined; + readonly otlpMetricsUrl: string | undefined; +} { + try { + if (!FS.existsSync(SERVER_SETTINGS_PATH)) { + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } + return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8")); + } catch (error) { + console.warn("[desktop] failed to read persisted backend observability settings", error); + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } +} + function backendChildEnv(): NodeJS.ProcessEnv { const env = { ...process.env }; delete env.T3CODE_PORT; @@ -988,6 +1007,7 @@ function scheduleBackendRestart(reason: string): void { function startBackend(): void { if (isQuitting || backendProcess) return; + backendObservabilitySettings = readPersistedBackendObservabilitySettings(); const backendEntry = resolveBackendEntry(); if (!FS.existsSync(backendEntry)) { scheduleBackendRestart(`missing server entry at ${backendEntry}`); @@ -1016,6 +1036,12 @@ function startBackend(): void { port: backendPort, t3Home: BASE_DIR, authToken: backendAuthToken, + ...(backendObservabilitySettings.otlpTracesUrl + ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl } + : {}), + ...(backendObservabilitySettings.otlpMetricsUrl + ? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl } + : {}), })}\n`, ); bootstrapStream.end(); @@ -1042,21 +1068,26 @@ function startBackend(): void { }); child.on("error", (error) => { + const wasExpected = expectedBackendExitChildren.has(child); if (backendProcess === child) { backendProcess = null; } closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`); + if (wasExpected) { + return; + } scheduleBackendRestart(error.message); }); child.on("exit", (code, signal) => { + const wasExpected = expectedBackendExitChildren.has(child); if (backendProcess === child) { backendProcess = null; } closeBackendSession( `pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`, ); - if (isQuitting) return; + if (isQuitting || wasExpected) return; const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`; scheduleBackendRestart(reason); }); @@ -1073,6 +1104,7 @@ function stopBackend(): void { if (!child) return; if (child.exitCode === null && child.signalCode === null) { + expectedBackendExitChildren.add(child); child.kill("SIGTERM"); setTimeout(() => { if (child.exitCode === null && child.signalCode === null) { @@ -1093,6 +1125,7 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise { if (!child) return; const backendChild = child; if (backendChild.exitCode !== null || backendChild.signalCode !== null) return; + expectedBackendExitChildren.add(backendChild); await new Promise((resolve) => { let settled = false; diff --git a/apps/marketing/src/pages/download.astro b/apps/marketing/src/pages/download.astro index 0cf31a82e4..54454d4026 100644 --- a/apps/marketing/src/pages/download.astro +++ b/apps/marketing/src/pages/download.astro @@ -1,5 +1,6 @@ --- import Layout from "../layouts/Layout.astro"; +import { RELEASES_URL } from "../lib/releases"; --- @@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro";

macOS

- + Apple Silicon (arm64) .dmg - + Intel (x64) .dmg @@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";

Windows

- + Windows 10, 11 .exe @@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";

Linux

- + x86_64 AppImage diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 152ed1d608..87c81f08c8 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -48,7 +48,7 @@ import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointRea import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts"; import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts"; import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts"; -import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts"; +import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts"; import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts"; import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts"; import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts"; @@ -297,7 +297,7 @@ export const makeOrchestrationIntegrationHarness = ( ProjectionPendingApprovalRepositoryLive, checkpointStoreLayer, providerLayer, - RuntimeReceiptBusLive, + RuntimeReceiptBusTest, ); const serverSettingsLayer = ServerSettingsService.layerTest(); const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( @@ -376,7 +376,7 @@ export const makeOrchestrationIntegrationHarness = ( runtime.runPromise(reactor.start().pipe(Scope.provide(scope))), ).pipe(Effect.orDie); const receiptHistory = yield* Ref.make>([]); - yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) => + yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) => Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid), ).pipe(Effect.forkIn(scope)); yield* Effect.sleep(10); diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts index ef03a1ab5c..1ca6fa1b83 100644 --- a/apps/server/integration/providerService.integration.test.ts +++ b/apps/server/integration/providerService.integration.test.ts @@ -86,6 +86,7 @@ const collectEventsDuring = ( Effect.forkScoped, ); + yield* Effect.sleep("50 millis"); yield* action; return yield* Effect.forEach( @@ -104,7 +105,6 @@ const runTurn = (input: { }) => Effect.gen(function* () { yield* input.harness.queueTurnResponse(input.threadId, input.response); - return yield* collectEventsDuring( input.provider.streamEvents, input.response.events.length, @@ -116,7 +116,7 @@ const runTurn = (input: { ); }); -it.effect("replays typed runtime fixture events", () => +it.live("replays typed runtime fixture events", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; @@ -149,7 +149,7 @@ it.effect("replays typed runtime fixture events", () => }).pipe(Effect.provide(NodeServices.layer)), ); -it.effect("replays file-changing fixture turn events", () => +it.live("replays file-changing fixture turn events", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; const { join } = yield* Path.Path; @@ -188,7 +188,7 @@ it.effect("replays file-changing fixture turn events", () => }).pipe(Effect.provide(NodeServices.layer)), ); -it.effect("runs multi-turn tool/approval flow", () => +it.live("runs multi-turn tool/approval flow", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; const { join } = yield* Path.Path; @@ -242,7 +242,7 @@ it.effect("runs multi-turn tool/approval flow", () => }).pipe(Effect.provide(NodeServices.layer)), ); -it.effect("rolls back provider conversation state only", () => +it.live("rolls back provider conversation state only", () => Effect.gen(function* () { const fixture = yield* makeIntegrationFixture; const { join } = yield* Path.Path; diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts index 7df1c71c23..6e7b18277c 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts @@ -80,7 +80,7 @@ function initRepoWithCommit( }); } -function buildLargeText(lineCount = 20_000): string { +function buildLargeText(lineCount = 5_000): string { return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) .join("\n") .concat("\n"); @@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => { expect(diff).toContain("diff --git"); expect(diff).not.toContain("[truncated]"); - expect(diff).toContain("+line 19999"); + expect(diff).toContain("+line 04999"); }), ); }); diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.ts index 27bc60b1be..ef2f9f55d8 100644 --- a/apps/server/src/cli-config.test.ts +++ b/apps/server/src/cli-config.test.ts @@ -9,6 +9,18 @@ import { deriveServerPaths } from "./config"; import { resolveServerConfig } from "./cli"; it.layer(NodeServices.layer)("cli config resolution", (it) => { + const defaultObservabilityConfig = { + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", + } as const; + const openBootstrapFd = Effect.fn(function* (payload: Record) { const fs = yield* FileSystem.FileSystem; const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); @@ -28,6 +40,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { port: Option.none(), host: Option.none(), baseDir: Option.none(), + cwd: Option.none(), devUrl: Option.none(), noBrowser: Option.none(), authToken: Option.none(), @@ -62,6 +75,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { expect(resolved).toEqual({ logLevel: "Warn", + ...defaultObservabilityConfig, mode: "desktop", port: 4001, cwd: process.cwd(), @@ -89,6 +103,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { port: Option.some(8788), host: Option.some("127.0.0.1"), baseDir: Option.some(baseDir), + cwd: Option.none(), devUrl: Option.some(new URL("http://127.0.0.1:4173")), noBrowser: Option.some(true), authToken: Option.some("flag-token"), @@ -123,6 +138,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { expect(resolved).toEqual({ logLevel: "Debug", + ...defaultObservabilityConfig, mode: "web", port: 8788, cwd: process.cwd(), @@ -153,6 +169,8 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { authToken: "bootstrap-token", autoBootstrapProjectFromCwd: false, logWebSocketEvents: true, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", }); const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173")); @@ -162,6 +180,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { port: Option.none(), host: Option.none(), baseDir: Option.none(), + cwd: Option.none(), devUrl: Option.none(), noBrowser: Option.none(), authToken: Option.none(), @@ -187,6 +206,9 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { expect(resolved).toEqual({ logLevel: "Info", + ...defaultObservabilityConfig, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", mode: "desktop", port: 4888, cwd: process.cwd(), @@ -209,6 +231,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" }); + const customCwd = path.join(baseDir, "nested", "project"); const resolved = yield* resolveServerConfig( { @@ -216,6 +239,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { port: Option.some(4888), host: Option.none(), baseDir: Option.some(baseDir), + cwd: Option.some(customCwd), devUrl: Option.some(new URL("http://127.0.0.1:5173")), noBrowser: Option.none(), authToken: Option.none(), @@ -234,6 +258,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { ); for (const directory of [ + customCwd, resolved.stateDir, resolved.logsDir, resolved.providerLogsDir, @@ -241,9 +266,11 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { resolved.attachmentsDir, resolved.worktreesDir, path.dirname(resolved.serverLogPath), + path.dirname(resolved.serverTracePath), ]) { expect(yield* fs.exists(directory)).toBe(true); } + expect(resolved.cwd).toBe(path.resolve(customCwd)); }), ); @@ -270,6 +297,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { port: Option.some(8788), host: Option.some("127.0.0.1"), baseDir: Option.none(), + cwd: Option.none(), devUrl: Option.some(new URL("http://127.0.0.1:4173")), noBrowser: Option.none(), authToken: Option.some("flag-token"), @@ -300,6 +328,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { expect(resolved).toEqual({ logLevel: "Debug", + ...defaultObservabilityConfig, mode: "web", port: 8788, cwd: process.cwd(), @@ -315,4 +344,68 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { }); }), ); + + it.effect("falls back to persisted observability settings when env vars are absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" }); + const derivedPaths = yield* deriveServerPaths(baseDir, undefined); + yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }); + yield* fs.writeFileString( + derivedPaths.settingsPath, + `${JSON.stringify({ + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + })}\n`, + ); + + const resolved = yield* resolveServerConfig( + { + mode: Option.some("desktop"), + port: Option.some(4888), + host: Option.none(), + baseDir: Option.some(baseDir), + cwd: Option.none(), + devUrl: Option.none(), + noBrowser: Option.none(), + authToken: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + NetService.layer, + ), + ), + ); + + expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces"); + expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics"); + expect(resolved).toEqual({ + logLevel: "Info", + ...defaultObservabilityConfig, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + mode: "desktop", + port: 4888, + cwd: process.cwd(), + baseDir, + ...derivedPaths, + host: "127.0.0.1", + staticDir: resolved.staticDir, + devUrl: undefined, + noBrowser: true, + authToken: undefined, + autoBootstrapProjectFromCwd: false, + logWebSocketEvents: false, + }); + }), + ); }); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index 2f76d25b7b..9ece02a0d3 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -1,6 +1,7 @@ import { NetService } from "@t3tools/shared/Net"; -import { Config, Effect, LogLevel, Option, Schema } from "effect"; -import { Command, Flag, GlobalFlag } from "effect/unstable/cli"; +import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; +import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect"; +import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli"; import { DEFAULT_PORT, @@ -12,7 +13,7 @@ import { type ServerConfigShape, } from "./config"; import { readBootstrapEnvelope } from "./bootstrap"; -import { resolveBaseDir } from "./os-jank"; +import { expandHomePath, resolveBaseDir } from "./os-jank"; import { runServer } from "./server"; const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); @@ -27,6 +28,8 @@ const BootstrapEnvelopeSchema = Schema.Struct({ authToken: Schema.optional(Schema.String), autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean), logWebSocketEvents: Schema.optional(Schema.Boolean), + otlpTracesUrl: Schema.optional(Schema.String), + otlpMetricsUrl: Schema.optional(Schema.String), }); const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe( @@ -81,6 +84,27 @@ const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe( 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), @@ -116,6 +140,7 @@ interface CliServerFlags { readonly port: Option.Option; readonly host: Option.Option; readonly baseDir: Option.Option; + readonly cwd: Option.Option; readonly devUrl: Option.Option; readonly noBrowser: Option.Option; readonly authToken: Option.Option; @@ -131,12 +156,25 @@ const resolveOptionPrecedence = ( ...values: ReadonlyArray> ): Option.Option => 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, ) => Effect.gen(function* () { const { findAvailablePort } = yield* NetService; + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; const env = yield* EnvServerConfig; const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd; const bootstrapEnvelope = @@ -188,8 +226,16 @@ export const resolveServerConfig = ( ), ), ); + const rawCwd = Option.getOrElse(flags.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 noBrowser = resolveBooleanFlag( flags.noBrowser, Option.getOrElse( @@ -248,11 +294,35 @@ export const resolveServerConfig = ( const config: ServerConfigShape = { logLevel, + traceMinLevel: env.traceMinLevel, + traceTimingEnabled: env.traceTimingEnabled, + traceBatchWindowMs: env.traceBatchWindowMs, + traceMaxBytes: env.traceMaxBytes, + traceMaxFiles: env.traceMaxFiles, + otlpTracesUrl: + env.otlpTracesUrl ?? + Option.getOrUndefined( + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.otlpTracesUrl), + ), + ) ?? + persistedObservabilitySettings.otlpTracesUrl, + otlpMetricsUrl: + env.otlpMetricsUrl ?? + Option.getOrUndefined( + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.otlpMetricsUrl), + ), + ) ?? + persistedObservabilitySettings.otlpMetricsUrl, + otlpExportIntervalMs: env.otlpExportIntervalMs, + otlpServiceName: env.otlpServiceName, mode, port, - cwd: process.cwd(), + cwd, baseDir, ...derivedPaths, + serverTracePath, host, staticDir, devUrl, @@ -270,6 +340,12 @@ const commandFlags = { 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, authToken: authTokenFlag, diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 21cd6f3150..9ceea4c13c 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -25,6 +25,7 @@ export interface ServerDerivedPaths { readonly attachmentsDir: string; readonly logsDir: string; readonly serverLogPath: string; + readonly serverTracePath: string; readonly providerLogsDir: string; readonly providerEventLogPath: string; readonly terminalLogsDir: string; @@ -36,6 +37,15 @@ export interface ServerDerivedPaths { */ export interface ServerConfigShape extends ServerDerivedPaths { readonly logLevel: LogLevel.LogLevel; + readonly traceMinLevel: LogLevel.LogLevel; + readonly traceTimingEnabled: boolean; + readonly traceBatchWindowMs: number; + readonly traceMaxBytes: number; + readonly traceMaxFiles: number; + readonly otlpTracesUrl: string | undefined; + readonly otlpMetricsUrl: string | undefined; + readonly otlpExportIntervalMs: number; + readonly otlpServiceName: string; readonly mode: RuntimeMode; readonly port: number; readonly host: string | undefined; @@ -68,6 +78,7 @@ export const deriveServerPaths = Effect.fn(function* ( attachmentsDir, logsDir, serverLogPath: join(logsDir, "server.log"), + serverTracePath: join(logsDir, "server.trace.ndjson"), providerLogsDir, providerEventLogPath: join(providerLogsDir, "events.log"), terminalLogsDir: join(logsDir, "terminals"), @@ -117,6 +128,15 @@ export class ServerConfig extends ServiceMap.Service; } +const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n; + +const addCurrentSpanEvent = (name: string, attributes: Record) => + Effect.currentSpan.pipe( + Effect.tap((span) => + Effect.sync(() => { + span.event(name, nowUnixNano(), compactTraceAttributes(attributes)); + }), + ), + Effect.catch(() => Effect.void), + ); + function trace2ChildKey(record: Record): string | null { const childId = record.child_id; if (typeof childId === "number" || typeof childId === "string") { @@ -444,6 +458,9 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( if (event === "child_start") { hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); + yield* addCurrentSpanEvent("git.hook.started", { + hookName, + }); if (progress.onHookStarted) { yield* progress.onHookStarted(hookName); } @@ -452,12 +469,19 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( if (event === "child_exit") { hookStartByChildKey.delete(childKey); + const code = traceRecord.success.code; + const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null; + const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null; + yield* addCurrentSpanEvent("git.hook.finished", { + hookName: started?.hookName ?? hookName, + exitCode, + durationMs, + }); if (progress.onHookFinished) { - const code = traceRecord.success.code; yield* progress.onHookFinished({ hookName: started?.hookName ?? hookName, - exitCode: typeof code === "number" && Number.isInteger(code) ? code : null, - durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null, + exitCode, + durationMs, }); } } @@ -609,13 +633,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const path = yield* Path.Path; const { worktreesDir } = yield* ServerConfig; - let execute: GitCoreShape["execute"]; + let executeRaw: GitCoreShape["execute"]; if (options?.executeOverride) { - execute = options.executeOverride; + executeRaw = options.executeOverride; } else { const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - execute = Effect.fnUntraced(function* (input) { + executeRaw = Effect.fnUntraced(function* (input) { const commandInput = { ...input, args: [...input.args], @@ -716,6 +740,25 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }); } + const execute: GitCoreShape["execute"] = (input) => + executeRaw(input).pipe( + withMetrics({ + counter: gitCommandsTotal, + timer: gitCommandDuration, + attributes: { + operation: input.operation, + }, + }), + Effect.withSpan(input.operation, { + kind: "client", + attributes: { + "git.operation": input.operation, + "git.cwd": input.cwd, + "git.args_count": input.args.length, + }, + }), + ); + const executeGit = ( operation: string, cwd: string, diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index 8fcac582ff..005bdb5bc6 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -6,7 +6,12 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; import { expect } from "vitest"; -import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts"; +import type { + GitActionProgressEvent, + GitPreparePullRequestThreadInput, + ModelSelection, + ThreadId, +} from "@t3tools/contracts"; import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts"; import { type GitManagerShape } from "../Services/GitManager.ts"; @@ -21,6 +26,11 @@ import { GitCore } from "../Services/GitCore.ts"; import { makeGitManager } from "./GitManager.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { + ProjectSetupScriptRunner, + type ProjectSetupScriptRunnerInput, + type ProjectSetupScriptRunnerShape, +} from "../../project/Services/ProjectSetupScriptRunner.ts"; interface FakeGhScenario { prListSequence?: string[]; @@ -593,7 +603,7 @@ function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; refe function preparePullRequestThread( manager: GitManagerShape, - input: { cwd: string; reference: string; mode: "local" | "worktree" }, + input: GitPreparePullRequestThreadInput, ) { return manager.preparePullRequestThread(input); } @@ -601,6 +611,7 @@ function preparePullRequestThread( function makeManager(input?: { ghScenario?: FakeGhScenario; textGeneration?: Partial; + setupScriptRunner?: ProjectSetupScriptRunnerShape; }) { const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario); const textGeneration = createTextGeneration(input?.textGeneration); @@ -618,6 +629,12 @@ function makeManager(input?: { const managerLayer = Layer.mergeAll( Layer.succeed(GitHubCli, gitHubCli), Layer.succeed(TextGeneration, textGeneration), + Layer.succeed( + ProjectSetupScriptRunner, + input?.setupScriptRunner ?? { + runForThread: () => Effect.succeed({ status: "no-script" as const }), + }, + ), gitCoreLayer, serverSettingsLayer, ).pipe(Layer.provideMerge(NodeServices.layer)); @@ -628,6 +645,8 @@ function makeManager(input?: { ); } +const asThreadId = (threadId: string) => threadId as ThreadId; + const GitManagerTestLayer = GitCoreLive.pipe( Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })), Layer.provideMerge(NodeServices.layer), @@ -2176,6 +2195,59 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("launches setup only when creating a new PR worktree", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-worktree-setup"]); + fs.writeFileSync(path.join(repoDir, "setup.txt"), "setup\n"); + yield* runGit(repoDir, ["add", "setup.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR worktree setup branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-worktree-setup"]); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/177/head"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const setupCalls: ProjectSetupScriptRunnerInput[] = []; + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 177, + title: "Worktree setup PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/177", + baseRefName: "main", + headRefName: "feature/pr-worktree-setup", + state: "open", + }, + }, + setupScriptRunner: { + runForThread: (setupInput) => + Effect.sync(() => { + setupCalls.push(setupInput); + return { status: "no-script" as const }; + }), + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "177", + mode: "worktree", + threadId: asThreadId("thread-pr-setup"), + }); + + expect(result.worktreePath).not.toBeNull(); + expect(setupCalls).toHaveLength(1); + expect(setupCalls[0]).toEqual({ + threadId: "thread-pr-setup", + projectCwd: repoDir, + worktreePath: result.worktreePath as string, + }); + }), + ); + it.effect("preserves fork upstream tracking when preparing a worktree PR thread", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -2360,6 +2432,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`); yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]); + const setupCalls: ProjectSetupScriptRunnerInput[] = []; const { manager } = yield* makeManager({ ghScenario: { pullRequest: { @@ -2371,18 +2444,27 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { state: "open", }, }, + setupScriptRunner: { + runForThread: (setupInput) => + Effect.sync(() => { + setupCalls.push(setupInput); + return { status: "no-script" as const }; + }), + }, }); const result = yield* preparePullRequestThread(manager, { cwd: repoDir, reference: "78", mode: "worktree", + threadId: asThreadId("thread-pr-existing-worktree"), }); expect(result.worktreePath && fs.realpathSync.native(result.worktreePath)).toBe( fs.realpathSync.native(worktreePath), ); expect(result.branch).toBe("feature/pr-existing-worktree"); + expect(setupCalls).toHaveLength(0); }), ); @@ -2562,6 +2644,50 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("does not fail PR worktree prep when setup terminal startup fails", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-setup-failure"]); + fs.writeFileSync(path.join(repoDir, "setup-failure.txt"), "setup failure\n"); + yield* runGit(repoDir, ["add", "setup-failure.txt"]); + yield* runGit(repoDir, ["commit", "-m", "PR setup failure branch"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-setup-failure"]); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/184/head"]); + yield* runGit(repoDir, ["checkout", "main"]); + + const { manager } = yield* makeManager({ + ghScenario: { + pullRequest: { + number: 184, + title: "Setup failure PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/184", + baseRefName: "main", + headRefName: "feature/pr-setup-failure", + state: "open", + }, + }, + setupScriptRunner: { + runForThread: () => Effect.fail(new Error("terminal start failed")), + }, + }); + + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "184", + mode: "worktree", + threadId: asThreadId("thread-pr-setup-failure"), + }); + + expect(result.branch).toBe("feature/pr-setup-failure"); + expect(result.worktreePath).not.toBeNull(); + expect(fs.existsSync(result.worktreePath as string)).toBe(true); + }), + ); + it.effect("rejects worktree prep when the PR head branch is checked out in the main repo", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index abc4985abd..7fedb15714 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -26,6 +26,7 @@ import { import { GitCore, GitStatusDetails } from "../Services/GitCore.ts"; import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; +import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts"; import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import type { GitManagerServiceError } from "@t3tools/contracts"; @@ -552,6 +553,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { const gitCore = yield* GitCore; const gitHubCli = yield* GitHubCli; const textGeneration = yield* TextGeneration; + const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; const serverSettingsService = yield* ServerSettingsService; const createProgressEmitter = ( @@ -1329,6 +1331,24 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn( "preparePullRequestThread", )(function* (input) { + const maybeRunSetupScript = (worktreePath: string) => { + if (!input.threadId) { + return Effect.void; + } + return projectSetupScriptRunner + .runForThread({ + threadId: input.threadId, + projectCwd: input.cwd, + worktreePath, + }) + .pipe( + Effect.catch((error) => + Effect.logWarning( + `GitManager.preparePullRequestThread: failed to launch worktree setup script for thread ${input.threadId} in ${worktreePath}: ${error.message}`, + ).pipe(Effect.asVoid), + ), + ); + }; return yield* Effect.gen(function* () { const normalizedReference = normalizePullRequestReference(input.reference); const rootWorktreePath = canonicalizeExistingPath(input.cwd); @@ -1461,6 +1481,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { path: null, }); yield* ensureExistingWorktreeUpstream(worktree.worktree.path); + yield* maybeRunSetupScript(worktree.worktree.path); return { pullRequest, diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index cee08b4f98..ca4a2c22ef 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -1,6 +1,15 @@ import Mime from "@effect/platform-node/Mime"; -import { Effect, FileSystem, Option, Path } from "effect"; -import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; +import { Data, Effect, FileSystem, Layer, Option, Path } from "effect"; +import { cast } from "effect/Function"; +import { + HttpBody, + HttpClient, + HttpClientResponse, + HttpRouter, + HttpServerResponse, + HttpServerRequest, +} from "effect/unstable/http"; +import { OtlpTracer } from "effect/unstable/observability"; import { ATTACHMENTS_ROUTE_PREFIX, @@ -9,10 +18,74 @@ import { } from "./attachmentPaths"; import { resolveAttachmentPathById } from "./attachmentStore"; import { ServerConfig } from "./config"; +import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts"; +import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts"; import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver"; const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600"; const FALLBACK_PROJECT_FAVICON_SVG = ``; +const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces"; + +class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{ + readonly cause: unknown; + readonly bodyJson: OtlpTracer.TraceData; +}> {} + +export const otlpTracesProxyRouteLayer = HttpRouter.add( + "POST", + OTLP_TRACES_PROXY_PATH, + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const config = yield* ServerConfig; + const otlpTracesUrl = config.otlpTracesUrl; + const browserTraceCollector = yield* BrowserTraceCollector; + const httpClient = yield* HttpClient.HttpClient; + const bodyJson = cast(yield* request.json); + + yield* Effect.try({ + try: () => decodeOtlpTraceRecords(bodyJson), + catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }), + }).pipe( + Effect.flatMap((records) => browserTraceCollector.record(records)), + Effect.catch((cause) => + Effect.logWarning("Failed to decode browser OTLP traces", { + cause, + bodyJson, + }), + ), + ); + + if (otlpTracesUrl === undefined) { + return HttpServerResponse.empty({ status: 204 }); + } + + return yield* httpClient + .post(otlpTracesUrl, { + body: HttpBody.jsonUnsafe(bodyJson), + }) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.as(HttpServerResponse.empty({ status: 204 })), + Effect.tapError((cause) => + Effect.logWarning("Failed to export browser OTLP traces", { + cause, + otlpTracesUrl, + }), + ), + Effect.catch(() => + Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })), + ), + ); + }), +).pipe( + Layer.provide( + HttpRouter.cors({ + allowedMethods: ["POST", "OPTIONS"], + allowedHeaders: ["content-type"], + maxAge: 600, + }), + ), +); export const attachmentsRouteLayer = HttpRouter.add( "GET", diff --git a/apps/server/src/observability/Attributes.test.ts b/apps/server/src/observability/Attributes.test.ts new file mode 100644 index 0000000000..4b495598ea --- /dev/null +++ b/apps/server/src/observability/Attributes.test.ts @@ -0,0 +1,46 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts"; + +describe("Attributes", () => { + it("normalizes circular arrays, maps, and sets without recursing forever", () => { + const array: Array = ["alpha"]; + array.push(array); + + const map = new Map(); + map.set("self", map); + + const set = new Set(); + set.add(set); + + assert.deepStrictEqual( + compactTraceAttributes({ + array, + map, + set, + }), + { + array: ["alpha", "[Circular]"], + map: { self: "[Circular]" }, + set: ["[Circular]"], + }, + ); + }); + + it("normalizes invalid dates without throwing", () => { + assert.deepStrictEqual( + compactTraceAttributes({ + invalidDate: new Date("not-a-real-date"), + }), + { + invalidDate: "Invalid Date", + }, + ); + }); + + it("groups GPT-family models under a shared metric label", () => { + assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt"); + assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude"); + }); +}); diff --git a/apps/server/src/observability/Attributes.ts b/apps/server/src/observability/Attributes.ts new file mode 100644 index 0000000000..2251fcfea6 --- /dev/null +++ b/apps/server/src/observability/Attributes.ts @@ -0,0 +1,128 @@ +import { Cause, Exit } from "effect"; + +export type MetricAttributeValue = string; +export type MetricAttributes = Readonly>; +export type TraceAttributes = Readonly>; +export type ObservabilityOutcome = "success" | "failure" | "interrupt"; + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function markSeen(value: object, seen: WeakSet): boolean { + if (seen.has(value)) { + return true; + } + seen.add(value); + return false; +} + +function normalizeJsonValue(value: unknown, seen: WeakSet = new WeakSet()): unknown { + if ( + value === null || + value === undefined || + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + return value ?? null; + } + if (typeof value === "bigint") { + return value.toString(); + } + if (value instanceof Date) { + return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString(); + } + if (value instanceof Error) { + return { + name: value.name, + message: value.message, + ...(value.stack ? { stack: value.stack } : {}), + }; + } + if (Array.isArray(value)) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return value.map((entry) => normalizeJsonValue(entry, seen)); + } + if (value instanceof Map) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Object.fromEntries( + Array.from(value.entries(), ([key, entryValue]) => [ + String(key), + normalizeJsonValue(entryValue, seen), + ]), + ); + } + if (value instanceof Set) { + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen)); + } + if (!isPlainObject(value)) { + return String(value); + } + if (markSeen(value, seen)) { + return "[Circular]"; + } + return Object.fromEntries( + Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]), + ); +} + +export function compactTraceAttributes( + attributes: Readonly>, +): TraceAttributes { + return Object.fromEntries( + Object.entries(attributes) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => [key, normalizeJsonValue(value)]), + ); +} + +export function compactMetricAttributes( + attributes: Readonly>, +): MetricAttributes { + return Object.fromEntries( + Object.entries(attributes).flatMap(([key, value]) => { + if (value === undefined || value === null) { + return []; + } + if (typeof value === "string") { + return [[key, value]]; + } + if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") { + return [[key, String(value)]]; + } + return []; + }), + ); +} + +export function outcomeFromExit(exit: Exit.Exit): ObservabilityOutcome { + if (Exit.isSuccess(exit)) { + return "success"; + } + return Cause.hasInterruptsOnly(exit.cause) ? "interrupt" : "failure"; +} + +export function normalizeModelMetricLabel(model: string | null | undefined): string | undefined { + const normalized = model?.trim().toLowerCase(); + if (!normalized) { + return undefined; + } + if (normalized.includes("gpt")) { + return "gpt"; + } + if (normalized.includes("claude")) { + return "claude"; + } + if (normalized.includes("gemini")) { + return "gemini"; + } + return "other"; +} diff --git a/apps/server/src/observability/Layers/Observability.ts b/apps/server/src/observability/Layers/Observability.ts new file mode 100644 index 0000000000..7c6a28005f --- /dev/null +++ b/apps/server/src/observability/Layers/Observability.ts @@ -0,0 +1,84 @@ +import { Effect, Layer, References, Tracer } from "effect"; +import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; + +import { ServerConfig } from "../../config.ts"; +import { ServerLoggerLive } from "../../serverLogger.ts"; +import { makeLocalFileTracer } from "../LocalFileTracer.ts"; +import { BrowserTraceCollector } from "../Services/BrowserTraceCollector.ts"; +import { makeTraceSink } from "../TraceSink.ts"; + +const otlpSerializationLayer = OtlpSerialization.layerJson; + +export const ObservabilityLive = Layer.unwrap( + Effect.gen(function* () { + const config = yield* ServerConfig; + + const traceReferencesLayer = Layer.mergeAll( + Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel), + Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled), + ); + + const tracerLayer = Layer.unwrap( + Effect.gen(function* () { + const sink = yield* makeTraceSink({ + filePath: config.serverTracePath, + maxBytes: config.traceMaxBytes, + maxFiles: config.traceMaxFiles, + batchWindowMs: config.traceBatchWindowMs, + }); + const delegate = + config.otlpTracesUrl === undefined + ? undefined + : yield* OtlpTracer.make({ + url: config.otlpTracesUrl, + exportInterval: `${config.otlpExportIntervalMs} millis`, + resource: { + serviceName: config.otlpServiceName, + attributes: { + "service.runtime": "t3-server", + "service.mode": config.mode, + }, + }, + }); + + const tracer = yield* makeLocalFileTracer({ + filePath: config.serverTracePath, + maxBytes: config.traceMaxBytes, + maxFiles: config.traceMaxFiles, + batchWindowMs: config.traceBatchWindowMs, + sink, + ...(delegate ? { delegate } : {}), + }); + + return Layer.mergeAll( + Layer.succeed(Tracer.Tracer, tracer), + Layer.succeed(BrowserTraceCollector, { + record: (records) => + Effect.sync(() => { + for (const record of records) { + sink.push(record); + } + }), + }), + ); + }), + ).pipe(Layer.provideMerge(otlpSerializationLayer)); + + const metricsLayer = + config.otlpMetricsUrl === undefined + ? Layer.empty + : OtlpMetrics.layer({ + url: config.otlpMetricsUrl, + exportInterval: `${config.otlpExportIntervalMs} millis`, + resource: { + serviceName: config.otlpServiceName, + attributes: { + "service.runtime": "t3-server", + "service.mode": config.mode, + }, + }, + }).pipe(Layer.provideMerge(otlpSerializationLayer)); + + return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer); + }), +); diff --git a/apps/server/src/observability/LocalFileTracer.test.ts b/apps/server/src/observability/LocalFileTracer.test.ts new file mode 100644 index 0000000000..19efffaf10 --- /dev/null +++ b/apps/server/src/observability/LocalFileTracer.test.ts @@ -0,0 +1,117 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Layer, Logger, References, Tracer } from "effect"; + +import type { EffectTraceRecord } from "./TraceRecord.ts"; +import { makeLocalFileTracer } from "./LocalFileTracer.ts"; + +const makeTestLayer = (tracePath: string) => + Layer.mergeAll( + Layer.effect( + Tracer.Tracer, + makeLocalFileTracer({ + filePath: tracePath, + maxBytes: 1024 * 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }), + ), + Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }), + Layer.succeed(References.MinimumLogLevel, "Info"), + ); + +const readTraceRecords = (tracePath: string): Array => + fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as EffectTraceRecord); + +describe("LocalFileTracer", () => { + it.effect("writes nested spans to disk and captures log messages as span events", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + yield* Effect.scoped( + Effect.gen(function* () { + const program = Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "demo.parent": true, + }); + yield* Effect.logInfo("parent event"); + yield* Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "demo.child": true, + }); + yield* Effect.logInfo("child event"); + }).pipe(Effect.withSpan("child-span")); + }).pipe(Effect.withSpan("parent-span")); + + yield* program.pipe(Effect.provide(makeTestLayer(tracePath))); + }), + ); + + const records = readTraceRecords(tracePath); + assert.equal(records.length, 2); + + const parent = records.find((record) => record.name === "parent-span"); + const child = records.find((record) => record.name === "child-span"); + + assert.notEqual(parent, undefined); + assert.notEqual(child, undefined); + if (!parent || !child) { + return; + } + + assert.equal(child.parentSpanId, parent.spanId); + assert.equal(parent.attributes["demo.parent"], true); + assert.equal(child.attributes["demo.child"], true); + assert.equal( + parent.events.some((event) => event.name === "parent event"), + true, + ); + assert.equal( + child.events.some((event) => event.name === "child event"), + true, + ); + assert.equal( + child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"), + true, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + + it.effect("serializes interrupted spans with an interrupted exit status", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + yield* Effect.scoped( + Effect.exit( + Effect.interrupt.pipe( + Effect.withSpan("interrupt-span"), + Effect.provide(makeTestLayer(tracePath)), + ), + ), + ); + + const records = readTraceRecords(tracePath); + assert.equal(records.length, 1); + assert.equal(records[0]?.name, "interrupt-span"); + assert.equal(records[0]?.exit._tag, "Interrupted"); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); +}); diff --git a/apps/server/src/observability/LocalFileTracer.ts b/apps/server/src/observability/LocalFileTracer.ts new file mode 100644 index 0000000000..cde5a176e8 --- /dev/null +++ b/apps/server/src/observability/LocalFileTracer.ts @@ -0,0 +1,107 @@ +import type * as Exit from "effect/Exit"; +import { Effect, Option, Tracer } from "effect"; + +import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts"; +import { makeTraceSink, type TraceSink } from "./TraceSink.ts"; + +export interface LocalFileTracerOptions { + readonly filePath: string; + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; + readonly delegate?: Tracer.Tracer; + readonly sink?: TraceSink; +} + +class LocalFileSpan implements Tracer.Span { + readonly _tag = "Span"; + readonly name: string; + readonly spanId: string; + readonly traceId: string; + readonly parent: Option.Option; + readonly annotations: Tracer.Span["annotations"]; + readonly links: Array; + readonly sampled: boolean; + readonly kind: Tracer.SpanKind; + + status: Tracer.SpanStatus; + attributes: Map; + events: Array<[name: string, startTime: bigint, attributes: Record]>; + + constructor( + options: Parameters[0], + private readonly delegate: Tracer.Span, + private readonly push: (record: EffectTraceRecord) => void, + ) { + this.name = delegate.name; + this.spanId = delegate.spanId; + this.traceId = delegate.traceId; + this.parent = options.parent; + this.annotations = options.annotations; + this.links = [...options.links]; + this.sampled = delegate.sampled; + this.kind = delegate.kind; + this.status = { + _tag: "Started", + startTime: options.startTime, + }; + this.attributes = new Map(); + this.events = []; + } + + end(endTime: bigint, exit: Exit.Exit): void { + this.status = { + _tag: "Ended", + startTime: this.status.startTime, + endTime, + exit, + }; + this.delegate.end(endTime, exit); + + if (this.sampled) { + this.push(spanToTraceRecord(this)); + } + } + + attribute(key: string, value: unknown): void { + this.attributes.set(key, value); + this.delegate.attribute(key, value); + } + + event(name: string, startTime: bigint, attributes?: Record): void { + const nextAttributes = attributes ?? {}; + this.events.push([name, startTime, nextAttributes]); + this.delegate.event(name, startTime, nextAttributes); + } + + addLinks(links: ReadonlyArray): void { + this.links.push(...links); + this.delegate.addLinks(links); + } +} + +export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* ( + options: LocalFileTracerOptions, +) { + const sink = + options.sink ?? + (yield* makeTraceSink({ + filePath: options.filePath, + maxBytes: options.maxBytes, + maxFiles: options.maxFiles, + batchWindowMs: options.batchWindowMs, + })); + + const delegate = + options.delegate ?? + Tracer.make({ + span: (spanOptions) => new Tracer.NativeSpan(spanOptions), + }); + + return Tracer.make({ + span(spanOptions) { + return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push); + }, + ...(delegate.context ? { context: delegate.context } : {}), + }); +}); diff --git a/apps/server/src/observability/Metrics.test.ts b/apps/server/src/observability/Metrics.test.ts new file mode 100644 index 0000000000..4604f43b63 --- /dev/null +++ b/apps/server/src/observability/Metrics.test.ts @@ -0,0 +1,111 @@ +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Metric } from "effect"; + +import { withMetrics } from "./Metrics.ts"; + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +describe("withMetrics", () => { + it.effect("supports pipe-style usage", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_pipe_total"); + const timer = Metric.timer("with_metrics_pipe_duration"); + + const result = yield* Effect.succeed("ok").pipe( + withMetrics({ + counter, + timer, + attributes: { + operation: "pipe", + }, + }), + ); + + assert.equal(result, "ok"); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_pipe_total", { + operation: "pipe", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", { + operation: "pipe", + }), + true, + ); + }), + ); + + it.effect("supports direct invocation", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_direct_total"); + + yield* withMetrics(Effect.fail("boom"), { + counter, + attributes: { + operation: "direct", + }, + }).pipe(Effect.exit); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_direct_total", { + operation: "direct", + outcome: "failure", + }), + true, + ); + }), + ); + + it.effect("evaluates attributes lazily after the wrapped effect runs", () => + Effect.gen(function* () { + const counter = Metric.counter("with_metrics_lazy_total"); + const timer = Metric.timer("with_metrics_lazy_duration"); + let provider = "unknown"; + + yield* Effect.sync(() => { + provider = "codex"; + }).pipe( + withMetrics({ + counter, + timer, + attributes: () => ({ + provider, + operation: "lazy", + }), + }), + ); + + const snapshots = yield* Metric.snapshot; + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_lazy_total", { + provider: "codex", + operation: "lazy", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", { + provider: "codex", + operation: "lazy", + }), + true, + ); + }), + ); +}); diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts new file mode 100644 index 0000000000..3e527c7cb4 --- /dev/null +++ b/apps/server/src/observability/Metrics.ts @@ -0,0 +1,160 @@ +import { Duration, Effect, Exit, Metric } from "effect"; +import { dual } from "effect/Function"; + +import { + compactMetricAttributes, + normalizeModelMetricLabel, + outcomeFromExit, +} from "./Attributes.ts"; + +export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", { + description: "Total RPC requests handled by the websocket RPC server.", +}); + +export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", { + description: "RPC request handling duration.", +}); + +export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", { + description: "Total orchestration commands dispatched.", +}); + +export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", { + description: "Orchestration command dispatch duration.", +}); + +export const orchestrationCommandAckDuration = Metric.timer( + "t3_orchestration_command_ack_duration", + { + description: + "Time from orchestration command dispatch to the first committed domain event emitted for that command.", + }, +); + +export const orchestrationEventsProcessedTotal = Metric.counter( + "t3_orchestration_events_processed_total", + { + description: "Total orchestration intent events processed by runtime reactors.", + }, +); + +export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", { + description: "Total provider session lifecycle operations.", +}); + +export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", { + description: "Total provider turn lifecycle operations.", +}); + +export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", { + description: "Provider turn request duration.", +}); + +export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", { + description: "Total canonical provider runtime events processed.", +}); + +export const gitCommandsTotal = Metric.counter("t3_git_commands_total", { + description: "Total git commands executed by the server runtime.", +}); + +export const gitCommandDuration = Metric.timer("t3_git_command_duration", { + description: "Git command execution duration.", +}); + +export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", { + description: "Total terminal sessions started.", +}); + +export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", { + description: "Total terminal restart requests handled.", +}); + +export const metricAttributes = ( + attributes: Readonly>, +): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes)); + +export const increment = ( + metric: Metric.Metric, + attributes: Readonly>, + amount = 1, +) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount); + +export interface WithMetricsOptions { + readonly counter?: Metric.Metric; + readonly timer?: Metric.Metric; + readonly attributes?: + | Readonly> + | (() => Readonly>); + readonly outcomeAttributes?: ( + outcome: ReturnType, + ) => Readonly>; +} + +const withMetricsImpl = ( + effect: Effect.Effect, + options: WithMetricsOptions, +): Effect.Effect => + Effect.gen(function* () { + const startedAt = Date.now(); + const exit = yield* Effect.exit(effect); + const duration = Duration.millis(Math.max(0, Date.now() - startedAt)); + const baseAttributes = + typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {}); + + if (options.timer) { + yield* Metric.update( + Metric.withAttributes(options.timer, metricAttributes(baseAttributes)), + duration, + ); + } + + if (options.counter) { + const outcome = outcomeFromExit(exit); + yield* Metric.update( + Metric.withAttributes( + options.counter, + metricAttributes({ + ...baseAttributes, + outcome, + ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}), + }), + ), + 1, + ); + } + + if (Exit.isSuccess(exit)) { + return exit.value; + } + return yield* Effect.failCause(exit.cause); + }); + +export const withMetrics: { + ( + options: WithMetricsOptions, + ): (effect: Effect.Effect) => Effect.Effect; + (effect: Effect.Effect, options: WithMetricsOptions): Effect.Effect; +} = dual(2, withMetricsImpl); + +export const providerMetricAttributes = ( + provider: string, + extra?: Readonly>, +) => + compactMetricAttributes({ + provider, + ...extra, + }); + +export const providerTurnMetricAttributes = (input: { + readonly provider: string; + readonly model: string | null | undefined; + readonly extra?: Readonly>; +}) => { + const modelFamily = normalizeModelMetricLabel(input.model); + return compactMetricAttributes({ + provider: input.provider, + ...(modelFamily ? { modelFamily } : {}), + ...input.extra, + }); +}; diff --git a/apps/server/src/observability/RpcInstrumentation.test.ts b/apps/server/src/observability/RpcInstrumentation.test.ts new file mode 100644 index 0000000000..d29b05f3c2 --- /dev/null +++ b/apps/server/src/observability/RpcInstrumentation.test.ts @@ -0,0 +1,161 @@ +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Exit, Metric, Stream } from "effect"; + +import { + observeRpcEffect, + observeRpcStream, + observeRpcStreamEffect, +} from "./RpcInstrumentation.ts"; + +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + +describe("RpcInstrumentation", () => { + it.effect("records success metrics for unary RPC handlers", () => + Effect.gen(function* () { + yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), { + "rpc.aggregate": "test", + }).pipe(Effect.withSpan("rpc.instrumentation.success.span")); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.success", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.success", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes for unary RPC handlers", () => + Effect.gen(function* () { + yield* Effect.exit( + observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), { + "rpc.aggregate": "test", + }).pipe(Effect.withSpan("rpc.instrumentation.failure.span")), + ); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.failure", + }), + true, + ); + }), + ); + + it.effect("records subscription activation metrics for stream RPC handlers", () => + Effect.gen(function* () { + const events = yield* Stream.runCollect( + observeRpcStreamEffect( + "rpc.instrumentation.stream", + Effect.succeed(Stream.make("a", "b")), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.span")), + ); + + assert.deepStrictEqual(Array.from(events), ["a", "b"]); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes for direct stream RPC handlers during consumption", () => + Effect.gen(function* () { + const exit = yield* Stream.runCollect( + observeRpcStream( + "rpc.instrumentation.stream.failure", + Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")), + ).pipe(Effect.exit); + + assert.equal(Exit.isFailure(exit), true); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream.failure", + }), + true, + ); + }), + ); + + it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () => + Effect.gen(function* () { + const exit = yield* Stream.runCollect( + observeRpcStreamEffect( + "rpc.instrumentation.stream.effect.failure", + Effect.succeed(Stream.fail("boom")), + { "rpc.aggregate": "test" }, + ).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")), + ).pipe(Effect.exit); + + assert.equal(Exit.isFailure(exit), true); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_requests_total", { + method: "rpc.instrumentation.stream.effect.failure", + outcome: "failure", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_rpc_request_duration", { + method: "rpc.instrumentation.stream.effect.failure", + }), + true, + ); + }), + ); +}); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts new file mode 100644 index 0000000000..a3ac29aa02 --- /dev/null +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -0,0 +1,89 @@ +import { Duration, Effect, Exit, Metric, Stream } from "effect"; + +import { outcomeFromExit } from "./Attributes.ts"; +import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts"; + +const annotateRpcSpan = ( + method: string, + traceAttributes?: Readonly>, +): Effect.Effect => + Effect.annotateCurrentSpan({ + "rpc.method": method, + ...traceAttributes, + }); + +const recordRpcStreamMetrics = ( + method: string, + startedAt: number, + exit: Exit.Exit, +): Effect.Effect => + Effect.gen(function* () { + yield* Metric.update( + Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })), + Duration.millis(Math.max(0, Date.now() - startedAt)), + ); + yield* Metric.update( + Metric.withAttributes( + rpcRequestsTotal, + metricAttributes({ + method, + outcome: outcomeFromExit(exit), + }), + ), + 1, + ); + }); + +export const observeRpcEffect = ( + method: string, + effect: Effect.Effect, + traceAttributes?: Readonly>, +): Effect.Effect => + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + + return yield* effect.pipe( + withMetrics({ + counter: rpcRequestsTotal, + timer: rpcRequestDuration, + attributes: { + method, + }, + }), + ); + }); + +export const observeRpcStream = ( + method: string, + stream: Stream.Stream, + traceAttributes?: Readonly>, +): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + const startedAt = Date.now(); + return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit))); + }), + ); + +export const observeRpcStreamEffect = ( + method: string, + effect: Effect.Effect, EffectError, EffectContext>, + traceAttributes?: Readonly>, +): Stream.Stream => + Stream.unwrap( + Effect.gen(function* () { + yield* annotateRpcSpan(method, traceAttributes); + const startedAt = Date.now(); + const exit = yield* Effect.exit(effect); + + if (Exit.isFailure(exit)) { + yield* recordRpcStreamMetrics(method, startedAt, exit); + return yield* Effect.failCause(exit.cause); + } + + return exit.value.pipe( + Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)), + ); + }), + ); diff --git a/apps/server/src/observability/Services/BrowserTraceCollector.ts b/apps/server/src/observability/Services/BrowserTraceCollector.ts new file mode 100644 index 0000000000..60e8f5fa13 --- /dev/null +++ b/apps/server/src/observability/Services/BrowserTraceCollector.ts @@ -0,0 +1,13 @@ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { TraceRecord } from "../TraceRecord.ts"; + +export interface BrowserTraceCollectorShape { + readonly record: (records: ReadonlyArray) => Effect.Effect; +} + +export class BrowserTraceCollector extends ServiceMap.Service< + BrowserTraceCollector, + BrowserTraceCollectorShape +>()("t3/observability/Services/BrowserTraceCollector") {} diff --git a/apps/server/src/observability/TraceRecord.ts b/apps/server/src/observability/TraceRecord.ts new file mode 100644 index 0000000000..a9a598288b --- /dev/null +++ b/apps/server/src/observability/TraceRecord.ts @@ -0,0 +1,287 @@ +import { Cause, Exit, Option, Tracer } from "effect"; + +import { compactTraceAttributes } from "./Attributes.ts"; +import { OtlpResource, OtlpTracer } from "effect/unstable/observability"; + +interface TraceRecordEvent { + readonly name: string; + readonly timeUnixNano: string; + readonly attributes: Readonly>; +} + +interface TraceRecordLink { + readonly traceId: string; + readonly spanId: string; + readonly attributes: Readonly>; +} + +interface BaseTraceRecord { + readonly name: string; + readonly kind: string; + readonly traceId: string; + readonly spanId: string; + readonly parentSpanId?: string; + readonly sampled: boolean; + readonly startTimeUnixNano: string; + readonly endTimeUnixNano: string; + readonly durationMs: number; + readonly attributes: Readonly>; + readonly events: ReadonlyArray; + readonly links: ReadonlyArray; +} + +export interface EffectTraceRecord extends BaseTraceRecord { + readonly type: "effect-span"; + readonly exit: + | { + readonly _tag: "Success"; + } + | { + readonly _tag: "Interrupted"; + readonly cause: string; + } + | { + readonly _tag: "Failure"; + readonly cause: string; + }; +} + +interface OtlpTraceRecord extends BaseTraceRecord { + readonly type: "otlp-span"; + readonly resourceAttributes: Readonly>; + readonly scope: Readonly<{ + readonly name?: string; + readonly version?: string; + readonly attributes: Readonly>; + }>; + readonly status?: + | { + readonly code?: string; + readonly message?: string; + } + | undefined; +} + +export type TraceRecord = EffectTraceRecord | OtlpTraceRecord; + +type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number]; +type OtlpSpanEvent = OtlpSpan["events"][number]; +type OtlpSpanLink = OtlpSpan["links"][number]; +type OtlpSpanStatus = OtlpSpan["status"]; + +interface SerializableSpan { + readonly name: string; + readonly traceId: string; + readonly spanId: string; + readonly parent: Option.Option; + readonly status: Tracer.SpanStatus; + readonly sampled: boolean; + readonly kind: Tracer.SpanKind; + readonly attributes: ReadonlyMap; + readonly links: ReadonlyArray; + readonly events: ReadonlyArray< + readonly [name: string, startTime: bigint, attributes: Record] + >; +} + +function formatTraceExit(exit: Exit.Exit): EffectTraceRecord["exit"] { + if (Exit.isSuccess(exit)) { + return { _tag: "Success" }; + } + if (Cause.hasInterruptsOnly(exit.cause)) { + return { + _tag: "Interrupted", + cause: Cause.pretty(exit.cause), + }; + } + return { + _tag: "Failure", + cause: Cause.pretty(exit.cause), + }; +} + +export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord { + const status = span.status as Extract; + const parentSpanId = Option.getOrUndefined(span.parent)?.spanId; + + return { + type: "effect-span", + name: span.name, + traceId: span.traceId, + spanId: span.spanId, + ...(parentSpanId ? { parentSpanId } : {}), + sampled: span.sampled, + kind: span.kind, + startTimeUnixNano: String(status.startTime), + endTimeUnixNano: String(status.endTime), + durationMs: Number(status.endTime - status.startTime) / 1_000_000, + attributes: compactTraceAttributes(Object.fromEntries(span.attributes)), + events: span.events.map(([name, startTime, attributes]) => ({ + name, + timeUnixNano: String(startTime), + attributes: compactTraceAttributes(attributes), + })), + links: span.links.map((link) => ({ + traceId: link.span.traceId, + spanId: link.span.spanId, + attributes: compactTraceAttributes(link.attributes), + })), + exit: formatTraceExit(status.exit), + }; +} + +const SPAN_KIND_MAP: Record = { + 1: "internal", + 2: "server", + 3: "client", + 4: "producer", + 5: "consumer", +}; + +export function decodeOtlpTraceRecords( + payload: OtlpTracer.TraceData, +): ReadonlyArray { + const records: Array = []; + + for (const resourceSpan of payload.resourceSpans) { + const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []); + + for (const scopeSpan of resourceSpan.scopeSpans) { + for (const span of scopeSpan.spans) { + records.push( + otlpSpanToTraceRecord({ + resourceAttributes, + scopeAttributes: decodeAttributes( + "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes) + ? scopeSpan.scope.attributes + : [], + ), + scopeName: scopeSpan.scope.name, + scopeVersion: + "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string" + ? scopeSpan.scope.version + : undefined, + span, + }), + ); + } + } + } + + return records; +} + +function otlpSpanToTraceRecord(input: { + readonly resourceAttributes: Readonly>; + readonly scopeAttributes: Readonly>; + readonly scopeName: string | undefined; + readonly scopeVersion: string | undefined; + readonly span: OtlpSpan; +}): OtlpTraceRecord { + return { + type: "otlp-span", + name: input.span.name, + traceId: input.span.traceId, + spanId: input.span.spanId, + ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}), + sampled: true, + kind: normalizeSpanKind(input.span.kind), + startTimeUnixNano: input.span.startTimeUnixNano, + endTimeUnixNano: input.span.endTimeUnixNano, + durationMs: + Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) / + 1_000_000, + attributes: decodeAttributes(input.span.attributes), + resourceAttributes: input.resourceAttributes, + scope: { + ...(input.scopeName ? { name: input.scopeName } : {}), + ...(input.scopeVersion ? { version: input.scopeVersion } : {}), + attributes: input.scopeAttributes, + }, + events: decodeEvents(input.span.events), + links: decodeLinks(input.span.links), + status: decodeStatus(input.span.status), + }; +} + +function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] { + const code = String(input.code); + const message = input.message; + + return { + code, + ...(message ? { message } : {}), + }; +} + +function decodeEvents(input: ReadonlyArray): ReadonlyArray { + return input.map((current) => ({ + name: current.name, + timeUnixNano: current.timeUnixNano, + attributes: decodeAttributes(current.attributes), + })); +} + +function decodeLinks(input: ReadonlyArray): ReadonlyArray { + return input.flatMap((current) => { + const traceId = current.traceId; + const spanId = current.spanId; + return { + traceId, + spanId, + attributes: decodeAttributes(current.attributes), + }; + }); +} + +function decodeAttributes( + input: ReadonlyArray, +): Readonly> { + const entries: Record = {}; + + for (const attribute of input) { + entries[attribute.key] = decodeValue(attribute.value); + } + + return compactTraceAttributes(entries); +} + +function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown { + if (input == null) { + return null; + } + if ("stringValue" in input) { + return input.stringValue; + } + if ("boolValue" in input) { + return input.boolValue; + } + if ("intValue" in input) { + return input.intValue; + } + if ("doubleValue" in input) { + return input.doubleValue; + } + if ("bytesValue" in input) { + return input.bytesValue; + } + if (input.arrayValue) { + return input.arrayValue.values.map((entry) => decodeValue(entry)); + } + if (input.kvlistValue) { + return decodeAttributes(input.kvlistValue.values); + } + return null; +} + +function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] { + return SPAN_KIND_MAP[input] || "internal"; +} + +function parseBigInt(input: string): bigint { + try { + return BigInt(input); + } catch { + return 0n; + } +} diff --git a/apps/server/src/observability/TraceSink.test.ts b/apps/server/src/observability/TraceSink.test.ts new file mode 100644 index 0000000000..f4db90516b --- /dev/null +++ b/apps/server/src/observability/TraceSink.test.ts @@ -0,0 +1,152 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { Effect } from "effect"; + +import type { TraceRecord } from "./TraceRecord.ts"; +import { makeTraceSink } from "./TraceSink.ts"; + +const makeRecord = (name: string, suffix = ""): TraceRecord => ({ + type: "effect-span", + name, + traceId: `trace-${name}-${suffix}`, + spanId: `span-${name}-${suffix}`, + sampled: true, + kind: "internal", + startTimeUnixNano: "1", + endTimeUnixNano: "2", + durationMs: 1, + attributes: { + payload: suffix, + }, + events: [], + links: [], + exit: { + _tag: "Success", + }, +}); + +describe("TraceSink", () => { + it.effect("flushes buffered records on close", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + sink.push(makeRecord("alpha")); + sink.push(makeRecord("beta")); + yield* sink.close(); + + const lines = fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as TraceRecord); + + assert.equal(lines.length, 2); + assert.equal(lines[0]?.name, "alpha"); + assert.equal(lines[1]?.name, "beta"); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); + + it.effect("rotates the trace file when the configured max size is exceeded", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 180, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + for (let index = 0; index < 8; index += 1) { + sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`)); + yield* sink.flush; + } + yield* sink.close(); + + const matchingFiles = fs + .readdirSync(tempDir) + .filter( + (entry) => + entry === "server.trace.ndjson" || entry.startsWith("server.trace.ndjson."), + ) + .toSorted(); + + assert.equal( + matchingFiles.some((entry) => entry === "server.trace.ndjson.1"), + true, + ); + assert.equal( + matchingFiles.some((entry) => entry === "server.trace.ndjson.3"), + false, + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); + + it.effect("drops only the invalid record when serialization fails", () => + Effect.scoped( + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-")); + const tracePath = path.join(tempDir, "server.trace.ndjson"); + + try { + const sink = yield* makeTraceSink({ + filePath: tracePath, + maxBytes: 1024, + maxFiles: 2, + batchWindowMs: 10_000, + }); + + const circular: Array = []; + circular.push(circular); + + sink.push(makeRecord("alpha")); + sink.push({ + ...makeRecord("invalid"), + attributes: { + circular, + }, + } as TraceRecord); + sink.push(makeRecord("beta")); + yield* sink.close(); + + const lines = fs + .readFileSync(tracePath, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as TraceRecord); + + assert.deepStrictEqual( + lines.map((line) => line.name), + ["alpha", "beta"], + ); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ), + ); +}); diff --git a/apps/server/src/observability/TraceSink.ts b/apps/server/src/observability/TraceSink.ts new file mode 100644 index 0000000000..1bd00b4734 --- /dev/null +++ b/apps/server/src/observability/TraceSink.ts @@ -0,0 +1,68 @@ +import { RotatingFileSink } from "@t3tools/shared/logging"; +import { Effect } from "effect"; + +import type { TraceRecord } from "./TraceRecord.ts"; + +const FLUSH_BUFFER_THRESHOLD = 32; + +export interface TraceSinkOptions { + readonly filePath: string; + readonly maxBytes: number; + readonly maxFiles: number; + readonly batchWindowMs: number; +} + +export interface TraceSink { + readonly filePath: string; + push: (record: TraceRecord) => void; + flush: Effect.Effect; + close: () => Effect.Effect; +} + +export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) { + const sink = new RotatingFileSink({ + filePath: options.filePath, + maxBytes: options.maxBytes, + maxFiles: options.maxFiles, + }); + + let buffer: Array = []; + + const flushUnsafe = () => { + if (buffer.length === 0) { + return; + } + + const chunk = buffer.join(""); + buffer = []; + + try { + sink.write(chunk); + } catch { + buffer.unshift(chunk); + } + }; + + const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false)); + + yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore)); + yield* Effect.forkScoped( + Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever), + ); + + return { + filePath: options.filePath, + push(record) { + try { + buffer.push(`${JSON.stringify(record)}\n`); + if (buffer.length >= FLUSH_BUFFER_THRESHOLD) { + flushUnsafe(); + } + } catch { + return; + } + }, + flush, + close: () => flush, + } satisfies TraceSink; +}); diff --git a/apps/server/src/open.test.ts b/apps/server/src/open.test.ts index c612922fea..76b14c8597 100644 --- a/apps/server/src/open.test.ts +++ b/apps/server/src/open.test.ts @@ -75,10 +75,19 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { command: "zed", args: ["/tmp/workspace"], }); + + const ideaLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLaunch, { + command: "idea", + args: ["/tmp/workspace"], + }); }), ); - it.effect("uses --goto when editor supports line/column suffixes", () => + it.effect("applies launch-style-specific navigation arguments", () => Effect.gen(function* () { const lineOnly = yield* resolveEditorLaunch( { cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" }, @@ -142,6 +151,33 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { command: "zed", args: ["/tmp/workspace/src/open.ts:71:5"], }); + + const zedLineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" }, + "darwin", + ); + assert.deepEqual(zedLineOnly, { + command: "zed", + args: ["/tmp/workspace/AGENTS.md:48"], + }); + + const ideaLineOnly = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLineOnly, { + command: "idea", + args: ["--line", "48", "/tmp/workspace/AGENTS.md"], + }); + + const ideaLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" }, + "darwin", + ); + assert.deepEqual(ideaLineAndColumn, { + command: "idea", + args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"], + }); }), ); diff --git a/apps/server/src/open.ts b/apps/server/src/open.ts index 212db36c01..58074ceef2 100644 --- a/apps/server/src/open.ts +++ b/apps/server/src/open.ts @@ -34,10 +34,45 @@ interface CommandAvailabilityOptions { readonly env?: NodeJS.ProcessEnv; } -const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/; +const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/; -function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean { - return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target); +function parseTargetPathAndPosition(target: string): { + path: string; + line: string | undefined; + column: string | undefined; +} | null { + const match = TARGET_WITH_POSITION_PATTERN.exec(target); + if (!match?.[1] || !match[2]) { + return null; + } + + return { + path: match[1], + line: match[2], + column: match[3], + }; +} + +function resolveCommandEditorArgs( + editor: (typeof EDITORS)[number], + target: string, +): ReadonlyArray { + const parsedTarget = parseTargetPathAndPosition(target); + + switch (editor.launchStyle) { + case "direct-path": + return [target]; + case "goto": + return parsedTarget ? ["--goto", target] : [target]; + case "line-column": { + if (!parsedTarget) { + return [target]; + } + + const { path, line, column } = parsedTarget; + return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path]; + } + } } function fileManagerCommandForPlatform(platform: NodeJS.Platform): string { @@ -198,19 +233,25 @@ export class Open extends ServiceMap.Service()("t3/open") {} // Implementations // ============================== -export const resolveEditorLaunch = Effect.fnUntraced(function* ( +export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( input: OpenInEditorInput, platform: NodeJS.Platform = process.platform, ): Effect.fn.Return { + yield* Effect.annotateCurrentSpan({ + "open.editor": input.editor, + "open.cwd": input.cwd, + "open.platform": platform, + }); const editorDef = EDITORS.find((editor) => editor.id === input.editor); if (!editorDef) { return yield* new OpenError({ message: `Unknown editor: ${input.editor}` }); } if (editorDef.command) { - return shouldUseGotoFlag(editorDef, input.cwd) - ? { command: editorDef.command, args: ["--goto", input.cwd] } - : { command: editorDef.command, args: [input.cwd] }; + return { + command: editorDef.command, + args: resolveCommandEditorArgs(editorDef, input.cwd), + }; } if (editorDef.id !== "file-manager") { diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index ab9f633e02..72adb175f9 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -96,7 +96,9 @@ function createProviderServiceHarness( listSessions, getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), rollbackConversation, - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const emit = (event: LegacyProviderRuntimeEvent): void => { diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 28609cecb3..03abebaf3a 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -119,7 +119,7 @@ const make = Effect.gen(function* () { createdAt: input.createdAt, }); - const resolveSessionRuntimeForThread = Effect.fnUntraced(function* ( + const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* ( threadId: ThreadId, ): Effect.fn.Return> { const readModel = yield* orchestrationEngine.getReadModel(); @@ -153,7 +153,7 @@ const make = Effect.gen(function* () { // active provider session CWD and falling back to the thread/project config. // Returns undefined when no CWD can be determined or the workspace is not // a git repository. - const resolveCheckpointCwd = Effect.fnUntraced(function* (input: { + const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: { readonly threadId: ThreadId; readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null }; readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>; @@ -188,7 +188,7 @@ const make = Effect.gen(function* () { // Shared tail for both capture paths: creates the git checkpoint ref, diffs // it against the previous turn, then dispatches the domain events to update // the orchestration read model. - const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: { + const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: { readonly threadId: ThreadId; readonly turnId: TurnId; readonly thread: { @@ -321,70 +321,70 @@ const make = Effect.gen(function* () { }); // Captures a real git checkpoint when a turn completes via a runtime event. - const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* ( - event: Extract, - ) { - const turnId = toTurnId(event.turnId); - if (!turnId) { - return; - } + const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")( + function* (event: Extract) { + const turnId = toTurnId(event.turnId); + if (!turnId) { + return; + } - const readModel = yield* orchestrationEngine.getReadModel(); - const thread = readModel.threads.find((entry) => entry.id === event.threadId); - if (!thread) { - return; - } + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) { + return; + } - // When a primary turn is active, only that turn may produce completion checkpoints. - if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) { - return; - } + // When a primary turn is active, only that turn may produce completion checkpoints. + if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) { + return; + } - // Only skip if a real (non-placeholder) checkpoint already exists for this turn. - // ProviderRuntimeIngestion may insert placeholder entries with status "missing" - // before this reactor runs; those must not prevent real git capture. - if ( - thread.checkpoints.some( - (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", - ) - ) { - return; - } + // Only skip if a real (non-placeholder) checkpoint already exists for this turn. + // ProviderRuntimeIngestion may insert placeholder entries with status "missing" + // before this reactor runs; those must not prevent real git capture. + if ( + thread.checkpoints.some( + (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing", + ) + ) { + return; + } - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId: thread.id, - thread, - projects: readModel.projects, - preferSessionRuntime: true, - }); - if (!checkpointCwd) { - return; - } + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId: thread.id, + thread, + projects: readModel.projects, + preferSessionRuntime: true, + }); + if (!checkpointCwd) { + return; + } - // If a placeholder checkpoint exists for this turn, reuse its turn count - // instead of incrementing past it. - const existingPlaceholder = thread.checkpoints.find( - (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing", - ); - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, - ); - const nextTurnCount = existingPlaceholder - ? existingPlaceholder.checkpointTurnCount - : currentTurnCount + 1; + // If a placeholder checkpoint exists for this turn, reuse its turn count + // instead of incrementing past it. + const existingPlaceholder = thread.checkpoints.find( + (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing", + ); + const currentTurnCount = thread.checkpoints.reduce( + (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), + 0, + ); + const nextTurnCount = existingPlaceholder + ? existingPlaceholder.checkpointTurnCount + : currentTurnCount + 1; - yield* captureAndDispatchCheckpoint({ - threadId: thread.id, - turnId, - thread, - cwd: checkpointCwd, - turnCount: nextTurnCount, - status: checkpointStatusFromRuntime(event.payload.state), - assistantMessageId: undefined, - createdAt: event.createdAt, - }); - }); + yield* captureAndDispatchCheckpoint({ + threadId: thread.id, + turnId, + thread, + cwd: checkpointCwd, + turnCount: nextTurnCount, + status: checkpointStatusFromRuntime(event.payload.state), + assistantMessageId: undefined, + createdAt: event.createdAt, + }); + }, + ); // Captures a real git checkpoint when a placeholder checkpoint (status "missing") // is detected via a domain event. This replaces the placeholder with a real @@ -394,7 +394,7 @@ const make = Effect.gen(function* () { // events from the Codex runtime. This handler fires when the corresponding // domain event arrives, allowing the reactor to capture the actual filesystem // state into a git ref and dispatch a replacement checkpoint. - const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* ( + const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* ( event: Extract, ) { const { threadId, turnId, checkpointTurnCount, status } = event.payload; @@ -448,57 +448,59 @@ const make = Effect.gen(function* () { }); }); - const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* ( - event: Extract, - ) { - const turnId = toTurnId(event.turnId); - if (!turnId) { - return; - } + const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")( + function* (event: Extract) { + const turnId = toTurnId(event.turnId); + if (!turnId) { + return; + } - const readModel = yield* orchestrationEngine.getReadModel(); - const thread = readModel.threads.find((entry) => entry.id === event.threadId); - if (!thread) { - return; - } + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) { + return; + } - const checkpointCwd = yield* resolveCheckpointCwd({ - threadId: thread.id, - thread, - projects: readModel.projects, - preferSessionRuntime: false, - }); - if (!checkpointCwd) { - return; - } + const checkpointCwd = yield* resolveCheckpointCwd({ + threadId: thread.id, + thread, + projects: readModel.projects, + preferSessionRuntime: false, + }); + if (!checkpointCwd) { + return; + } - const currentTurnCount = thread.checkpoints.reduce( - (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), - 0, - ); - const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount); - const baselineExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - if (baselineExists) { - return; - } + const currentTurnCount = thread.checkpoints.reduce( + (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), + 0, + ); + const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount); + const baselineExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + if (baselineExists) { + return; + } - yield* checkpointStore.captureCheckpoint({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); - yield* receiptBus.publish({ - type: "checkpoint.baseline.captured", - threadId: thread.id, - checkpointTurnCount: currentTurnCount, - checkpointRef: baselineCheckpointRef, - createdAt: event.createdAt, - }); - }); + yield* checkpointStore.captureCheckpoint({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + yield* receiptBus.publish({ + type: "checkpoint.baseline.captured", + threadId: thread.id, + checkpointTurnCount: currentTurnCount, + checkpointRef: baselineCheckpointRef, + createdAt: event.createdAt, + }); + }, + ); - const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* ( + const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn( + "ensurePreTurnBaselineFromDomainTurnStart", + )(function* ( event: Extract< OrchestrationEvent, { type: "thread.turn-start-requested" | "thread.message-sent" } @@ -557,7 +559,7 @@ const make = Effect.gen(function* () { }); }); - const handleRevertRequested = Effect.fnUntraced(function* ( + const handleRevertRequested = Effect.fn("handleRevertRequested")(function* ( event: Extract, ) { const now = new Date().toISOString(); @@ -685,7 +687,7 @@ const make = Effect.gen(function* () { ); }); - const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) { + const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) { if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") { yield* ensurePreTurnBaselineFromDomainTurnStart(event); return; @@ -724,7 +726,9 @@ const make = Effect.gen(function* () { } }); - const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) { + const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( + event: ProviderRuntimeEvent, + ) { if (event.type === "turn.started") { yield* ensurePreTurnBaselineFromTurnStart(event); return; diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index 16bbd98d6b..5a0a6113f0 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -8,7 +8,7 @@ import { TurnId, type OrchestrationEvent, } from "@t3tools/contracts"; -import { Effect, Layer, ManagedRuntime, Option, Queue, Stream } from "effect"; +import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect"; import { describe, expect, it } from "vitest"; import { PersistenceSqlError } from "../../persistence/Errors.ts"; @@ -62,6 +62,17 @@ function now() { return new Date().toISOString(); } +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + describe("OrchestrationEngine", () => { it("bootstraps the in-memory read model from persisted projections", async () => { const failOnHistoricalReplayStore: OrchestrationEventStoreShape = { @@ -408,6 +419,95 @@ describe("OrchestrationEngine", () => { await system.dispose(); }); + it("records command ack duration using the first committed event type", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await system.run( + engine.dispatch({ + type: "project.create", + commandId: CommandId.makeUnsafe("cmd-project-ack-create"), + projectId: asProjectId("project-ack"), + title: "Ack Project", + workspaceRoot: "/tmp/project-ack", + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt, + }), + ); + + await system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-ack-create"), + threadId: ThreadId.makeUnsafe("thread-ack"), + projectId: asProjectId("project-ack"), + title: "Ack Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ); + + const snapshots = await system.run(Metric.snapshot); + expect( + hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", { + commandType: "thread.create", + aggregateKind: "thread", + ackEventType: "thread.created", + }), + ).toBe(true); + + await system.dispose(); + }); + + it("records failed command dispatches as metric failures", async () => { + const system = await createOrchestrationSystem(); + const { engine } = system; + const createdAt = now(); + + await expect( + system.run( + engine.dispatch({ + type: "thread.create", + commandId: CommandId.makeUnsafe("cmd-thread-missing-project"), + threadId: ThreadId.makeUnsafe("thread-missing-project"), + projectId: asProjectId("project-missing"), + title: "Missing Project Thread", + modelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + createdAt, + }), + ), + ).rejects.toThrow("does not exist"); + + const snapshots = await system.run(Metric.snapshot); + expect( + hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", { + commandType: "thread.create", + aggregateKind: "thread", + outcome: "failure", + }), + ).toBe(true); + + await system.dispose(); + }); + it("stores completed checkpoint summaries even when no files changed", async () => { const system = await createOrchestrationSystem(); const { engine } = system; diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index bd3581deb6..ddd1718faf 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -5,9 +5,28 @@ import type { ThreadId, } from "@t3tools/contracts"; import { OrchestrationCommand } from "@t3tools/contracts"; -import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect"; +import { + Cause, + Deferred, + Duration, + Effect, + Exit, + Layer, + Metric, + Option, + PubSub, + Queue, + Schema, + Stream, +} from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; +import { + metricAttributes, + orchestrationCommandAckDuration, + orchestrationCommandsTotal, + orchestrationCommandDuration, +} from "../../observability/Metrics.ts"; import { toPersistenceSqlError } from "../../persistence/Errors.ts"; import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts"; @@ -28,6 +47,7 @@ import { interface CommandEnvelope { command: OrchestrationCommand; result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>; + startedAtMs: number; } function commandToAggregateRef(command: OrchestrationCommand): { @@ -64,6 +84,12 @@ const makeOrchestrationEngine = Effect.gen(function* () { const processEnvelope = (envelope: CommandEnvelope): Effect.Effect => { const dispatchStartSequence = readModel.snapshotSequence; + const processingStartedAtMs = Date.now(); + const aggregateRef = commandToAggregateRef(envelope.command); + const baseMetricAttributes = { + commandType: envelope.command.type, + aggregateKind: aggregateRef.aggregateKind, + } as const; const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () { const persistedEvents = yield* Stream.runCollect( eventStore.readFromSequence(dispatchStartSequence), @@ -83,113 +109,160 @@ const makeOrchestrationEngine = Effect.gen(function* () { } }); - return Effect.gen(function* () { - const existingReceipt = yield* commandReceiptRepository.getByCommandId({ - commandId: envelope.command.commandId, - }); - if (Option.isSome(existingReceipt)) { - if (existingReceipt.value.status === "accepted") { - yield* Deferred.succeed(envelope.result, { - sequence: existingReceipt.value.resultSequence, - }); - return; - } - yield* Deferred.fail( - envelope.result, - new OrchestrationCommandPreviouslyRejectedError({ + return Effect.exit( + Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "orchestration.command_id": envelope.command.commandId, + "orchestration.command_type": envelope.command.type, + "orchestration.aggregate_kind": aggregateRef.aggregateKind, + "orchestration.aggregate_id": aggregateRef.aggregateId, + }); + + const existingReceipt = yield* commandReceiptRepository.getByCommandId({ + commandId: envelope.command.commandId, + }); + if (Option.isSome(existingReceipt)) { + if (existingReceipt.value.status === "accepted") { + return { + sequence: existingReceipt.value.resultSequence, + }; + } + return yield* new OrchestrationCommandPreviouslyRejectedError({ commandId: envelope.command.commandId, detail: existingReceipt.value.error ?? "Previously rejected.", - }), - ); - return; - } + }); + } - const eventBase = yield* decideOrchestrationCommand({ - command: envelope.command, - readModel, - }); - const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase]; - const committedCommand = yield* sql - .withTransaction( - Effect.gen(function* () { - const committedEvents: OrchestrationEvent[] = []; - let nextReadModel = readModel; + const eventBase = yield* decideOrchestrationCommand({ + command: envelope.command, + readModel, + }); + const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase]; + const committedCommand = yield* sql + .withTransaction( + Effect.gen(function* () { + const committedEvents: OrchestrationEvent[] = []; + let nextReadModel = readModel; - for (const nextEvent of eventBases) { - const savedEvent = yield* eventStore.append(nextEvent); - nextReadModel = yield* projectEvent(nextReadModel, savedEvent); - yield* projectionPipeline.projectEvent(savedEvent); - committedEvents.push(savedEvent); - } + for (const nextEvent of eventBases) { + const savedEvent = yield* eventStore.append(nextEvent); + nextReadModel = yield* projectEvent(nextReadModel, savedEvent); + yield* projectionPipeline.projectEvent(savedEvent); + committedEvents.push(savedEvent); + } - const lastSavedEvent = committedEvents.at(-1) ?? null; - if (lastSavedEvent === null) { - return yield* new OrchestrationCommandInvariantError({ - commandType: envelope.command.type, - detail: "Command produced no events.", + const lastSavedEvent = committedEvents.at(-1) ?? null; + if (lastSavedEvent === null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: envelope.command.type, + detail: "Command produced no events.", + }); + } + + yield* commandReceiptRepository.upsert({ + commandId: envelope.command.commandId, + aggregateKind: lastSavedEvent.aggregateKind, + aggregateId: lastSavedEvent.aggregateId, + acceptedAt: lastSavedEvent.occurredAt, + resultSequence: lastSavedEvent.sequence, + status: "accepted", + error: null, }); - } - yield* commandReceiptRepository.upsert({ - commandId: envelope.command.commandId, - aggregateKind: lastSavedEvent.aggregateKind, - aggregateId: lastSavedEvent.aggregateId, - acceptedAt: lastSavedEvent.occurredAt, - resultSequence: lastSavedEvent.sequence, - status: "accepted", - error: null, - }); - - return { - committedEvents, - lastSequence: lastSavedEvent.sequence, - nextReadModel, - } as const; - }), - ) - .pipe( - Effect.catchTag("SqlError", (sqlError) => - Effect.fail( - toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError), - ), - ), - ); - - readModel = committedCommand.nextReadModel; - for (const event of committedCommand.committedEvents) { - yield* PubSub.publish(eventPubSub, event); - } - yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence }); - }).pipe( - Effect.catch((error) => - Effect.gen(function* () { - yield* reconcileReadModelAfterDispatchFailure.pipe( - Effect.catch(() => - Effect.logWarning( - "failed to reconcile orchestration read model after dispatch failure", - ).pipe( - Effect.annotateLogs({ - commandId: envelope.command.commandId, - snapshotSequence: readModel.snapshotSequence, - }), + return { + committedEvents, + lastSequence: lastSavedEvent.sequence, + nextReadModel, + } as const; + }), + ) + .pipe( + Effect.catchTag("SqlError", (sqlError) => + Effect.fail( + toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError), ), ), ); - if (Schema.is(OrchestrationCommandInvariantError)(error)) { - const aggregateRef = commandToAggregateRef(envelope.command); - yield* commandReceiptRepository - .upsert({ - commandId: envelope.command.commandId, - aggregateKind: aggregateRef.aggregateKind, - aggregateId: aggregateRef.aggregateId, - acceptedAt: new Date().toISOString(), - resultSequence: readModel.snapshotSequence, - status: "rejected", - error: error.message, - }) - .pipe(Effect.catch(() => Effect.void)); + readModel = committedCommand.nextReadModel; + for (const [index, event] of committedCommand.committedEvents.entries()) { + yield* PubSub.publish(eventPubSub, event); + if (index === 0) { + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandAckDuration, + metricAttributes({ + ...baseMetricAttributes, + ackEventType: event.type, + }), + ), + Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)), + ); } + } + return { sequence: committedCommand.lastSequence }; + }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)), + ).pipe( + Effect.flatMap((exit) => + Effect.gen(function* () { + const outcome = Exit.isSuccess(exit) + ? "success" + : Cause.hasInterruptsOnly(exit.cause) + ? "interrupt" + : "failure"; + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandDuration, + metricAttributes(baseMetricAttributes), + ), + Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)), + ); + yield* Metric.update( + Metric.withAttributes( + orchestrationCommandsTotal, + metricAttributes({ + ...baseMetricAttributes, + outcome, + }), + ), + 1, + ); + + if (Exit.isSuccess(exit)) { + yield* Deferred.succeed(envelope.result, exit.value); + return; + } + + const error = Cause.squash(exit.cause) as OrchestrationDispatchError; + if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) { + yield* reconcileReadModelAfterDispatchFailure.pipe( + Effect.catch(() => + Effect.logWarning( + "failed to reconcile orchestration read model after dispatch failure", + ).pipe( + Effect.annotateLogs({ + commandId: envelope.command.commandId, + snapshotSequence: readModel.snapshotSequence, + }), + ), + ), + ); + + if (Schema.is(OrchestrationCommandInvariantError)(error)) { + yield* commandReceiptRepository + .upsert({ + commandId: envelope.command.commandId, + aggregateKind: aggregateRef.aggregateKind, + aggregateId: aggregateRef.aggregateId, + acceptedAt: new Date().toISOString(), + resultSequence: readModel.snapshotSequence, + status: "rejected", + error: error.message, + }) + .pipe(Effect.catch(() => Effect.void)); + } + } + yield* Deferred.fail(envelope.result, error); }), ), @@ -214,7 +287,7 @@ const makeOrchestrationEngine = Effect.gen(function* () { const dispatch: OrchestrationEngineShape["dispatch"] = (command) => Effect.gen(function* () { const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>(); - yield* Queue.offer(commandQueue, { command, result }); + yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() }); return yield* Deferred.await(result); }); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index ca3dc04517..fe6cb9caf5 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -208,7 +208,9 @@ describe("ProviderCommandReactor", () => { sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", }), rollbackConversation: () => unsupported(), - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const orchestrationLayer = OrchestrationEngineLive.pipe( diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 8e2a19bcd1..419e3f3bf2 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -16,6 +16,7 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts"; import { GitCore } from "../../git/Services/GitCore.ts"; +import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts"; import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts"; import { TextGeneration } from "../../git/Services/TextGeneration.ts"; import { ProviderService } from "../../provider/Services/ProviderService.ts"; @@ -212,12 +213,12 @@ const make = Effect.gen(function* () { createdAt: input.createdAt, }); - const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) { + const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) { const readModel = yield* orchestrationEngine.getReadModel(); return readModel.threads.find((entry) => entry.id === threadId); }); - const ensureSessionForThread = Effect.fnUntraced(function* ( + const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* ( threadId: ThreadId, createdAt: string, options?: { @@ -357,7 +358,7 @@ const make = Effect.gen(function* () { return startedSession.threadId; }); - const sendTurnForThread = Effect.fnUntraced(function* (input: { + const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: { readonly threadId: ThreadId; readonly messageText: string; readonly attachments?: ReadonlyArray; @@ -409,7 +410,9 @@ const make = Effect.gen(function* () { }); }); - const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: { + const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn( + "maybeGenerateAndRenameWorktreeBranchForFirstTurn", + )(function* (input: { readonly threadId: ThreadId; readonly branch: string | null; readonly worktreePath: string | null; @@ -461,50 +464,52 @@ const make = Effect.gen(function* () { ); }); - const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: { - readonly threadId: ThreadId; - readonly cwd: string; - readonly messageText: string; - readonly attachments?: ReadonlyArray; - readonly titleSeed?: string; - }) { - const attachments = input.attachments ?? []; - yield* Effect.gen(function* () { - const { textGenerationModelSelection: modelSelection } = - yield* serverSettingsService.getSettings; + const maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")( + function* (input: { + readonly threadId: ThreadId; + readonly cwd: string; + readonly messageText: string; + readonly attachments?: ReadonlyArray; + readonly titleSeed?: string; + }) { + const attachments = input.attachments ?? []; + yield* Effect.gen(function* () { + const { textGenerationModelSelection: modelSelection } = + yield* serverSettingsService.getSettings; - const generated = yield* textGeneration.generateThreadTitle({ - cwd: input.cwd, - message: input.messageText, - ...(attachments.length > 0 ? { attachments } : {}), - modelSelection, - }); - if (!generated) return; - - const thread = yield* resolveThread(input.threadId); - if (!thread) return; - if (!canReplaceThreadTitle(thread.title, input.titleSeed)) { - return; - } - - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: serverCommandId("thread-title-rename"), - threadId: input.threadId, - title: generated.title, - }); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("provider command reactor failed to generate or rename thread title", { - threadId: input.threadId, + const generated = yield* textGeneration.generateThreadTitle({ cwd: input.cwd, - cause: Cause.pretty(cause), - }), - ), - ); - }); + message: input.messageText, + ...(attachments.length > 0 ? { attachments } : {}), + modelSelection, + }); + if (!generated) return; - const processTurnStartRequested = Effect.fnUntraced(function* ( + const thread = yield* resolveThread(input.threadId); + if (!thread) return; + if (!canReplaceThreadTitle(thread.title, input.titleSeed)) { + return; + } + + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("thread-title-rename"), + threadId: input.threadId, + title: generated.title, + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider command reactor failed to generate or rename thread title", { + threadId: input.threadId, + cwd: input.cwd, + cause: Cause.pretty(cause), + }), + ), + ); + }, + ); + + const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* ( event: Extract, ) { const key = turnStartKeyForEvent(event); @@ -583,7 +588,7 @@ const make = Effect.gen(function* () { ); }); - const processTurnInterruptRequested = Effect.fnUntraced(function* ( + const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* ( event: Extract, ) { const thread = yield* resolveThread(event.payload.threadId); @@ -606,7 +611,7 @@ const make = Effect.gen(function* () { yield* providerService.interruptTurn({ threadId: event.payload.threadId }); }); - const processApprovalResponseRequested = Effect.fnUntraced(function* ( + const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* ( event: Extract, ) { const thread = yield* resolveThread(event.payload.threadId); @@ -653,50 +658,52 @@ const make = Effect.gen(function* () { ); }); - const processUserInputResponseRequested = Effect.fnUntraced(function* ( - event: Extract, - ) { - const thread = yield* resolveThread(event.payload.threadId); - if (!thread) { - return; - } - const hasSession = thread.session && thread.session.status !== "stopped"; - if (!hasSession) { - return yield* appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - detail: "No active provider session is bound to this thread.", - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }); - } + const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")( + function* ( + event: Extract, + ) { + const thread = yield* resolveThread(event.payload.threadId); + if (!thread) { + return; + } + const hasSession = thread.session && thread.session.status !== "stopped"; + if (!hasSession) { + return yield* appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.user-input.respond.failed", + summary: "Provider user input response failed", + detail: "No active provider session is bound to this thread.", + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }); + } - yield* providerService - .respondToUserInput({ - threadId: event.payload.threadId, - requestId: event.payload.requestId, - answers: event.payload.answers, - }) - .pipe( - Effect.catchCause((cause) => - appendProviderFailureActivity({ - threadId: event.payload.threadId, - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - detail: isUnknownPendingUserInputRequestError(cause) - ? stalePendingRequestDetail("user-input", event.payload.requestId) - : Cause.pretty(cause), - turnId: null, - createdAt: event.payload.createdAt, - requestId: event.payload.requestId, - }), - ), - ); - }); + yield* providerService + .respondToUserInput({ + threadId: event.payload.threadId, + requestId: event.payload.requestId, + answers: event.payload.answers, + }) + .pipe( + Effect.catchCause((cause) => + appendProviderFailureActivity({ + threadId: event.payload.threadId, + kind: "provider.user-input.respond.failed", + summary: "Provider user input response failed", + detail: isUnknownPendingUserInputRequestError(cause) + ? stalePendingRequestDetail("user-input", event.payload.requestId) + : Cause.pretty(cause), + turnId: null, + createdAt: event.payload.createdAt, + requestId: event.payload.requestId, + }), + ), + ); + }, + ); - const processSessionStopRequested = Effect.fnUntraced(function* ( + const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* ( event: Extract, ) { const thread = yield* resolveThread(event.payload.threadId); @@ -727,6 +734,14 @@ const make = Effect.gen(function* () { const processDomainEvent = Effect.fn("processDomainEvent")(function* ( event: ProviderIntentEvent, ) { + yield* Effect.annotateCurrentSpan({ + "orchestration.event_type": event.type, + "orchestration.thread_id": event.payload.threadId, + ...(event.commandId ? { "orchestration.command_id": event.commandId } : {}), + }); + yield* increment(orchestrationEventsProcessedTotal, { + eventType: event.type, + }); switch (event.type) { case "thread.runtime-mode-set": { const thread = yield* resolveThread(event.payload.threadId); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 6c27e1010c..85f4d966e3 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -98,7 +98,9 @@ function createProviderServiceHarness() { listSessions: () => Effect.succeed([...runtimeSessions]), getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), rollbackConversation: () => unsupported(), - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const setSession = (session: ProviderSession): void => { diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index b479d1c28a..8d3fb5d752 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -524,7 +524,7 @@ const make = Effect.fn("make")(function* () { lookup: () => Effect.succeed({ text: "", createdAt: "" }), }); - const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) { + const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) { const readModel = yield* orchestrationEngine.getReadModel(); const thread = readModel.threads.find((entry) => entry.id === threadId); if (!thread) { @@ -796,9 +796,9 @@ const make = Effect.fn("make")(function* () { ).pipe(Effect.asVoid); }); - const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* ( - threadId: ThreadId, - ) { + const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn( + "getSourceProposedPlanReferenceForPendingTurnStart", + )(function* (threadId: ThreadId) { const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ threadId, }); @@ -818,16 +818,17 @@ const make = Effect.fn("make")(function* () { } as const; }); - const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) { - const sessions = yield* providerService.listSessions(); - const session = sessions.find((entry) => entry.threadId === threadId); - return session?.activeTurnId; - }); + const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")( + function* (threadId: ThreadId) { + const sessions = yield* providerService.listSessions(); + const session = sessions.find((entry) => entry.threadId === threadId); + return session?.activeTurnId; + }, + ); - const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* ( - threadId: ThreadId, - eventTurnId: TurnId | undefined, - ) { + const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn( + "getSourceProposedPlanReferenceForAcceptedTurnStart", + )(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) { if (eventTurnId === undefined) { return null; } @@ -840,34 +841,36 @@ const make = Effect.fn("make")(function* () { return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId); }); - const markSourceProposedPlanImplemented = Effect.fnUntraced(function* ( - sourceThreadId: ThreadId, - sourcePlanId: OrchestrationProposedPlanId, - implementationThreadId: ThreadId, - implementedAt: string, - ) { - const readModel = yield* orchestrationEngine.getReadModel(); - const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId); - const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId); - if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) { - return; - } + const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")( + function* ( + sourceThreadId: ThreadId, + sourcePlanId: OrchestrationProposedPlanId, + implementationThreadId: ThreadId, + implementedAt: string, + ) { + const readModel = yield* orchestrationEngine.getReadModel(); + const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId); + const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId); + if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) { + return; + } - yield* orchestrationEngine.dispatch({ - type: "thread.proposed-plan.upsert", - commandId: CommandId.makeUnsafe( - `provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`, - ), - threadId: sourceThread.id, - proposedPlan: { - ...sourcePlan, - implementedAt, - implementationThreadId, - updatedAt: implementedAt, - }, - createdAt: implementedAt, - }); - }); + yield* orchestrationEngine.dispatch({ + type: "thread.proposed-plan.upsert", + commandId: CommandId.makeUnsafe( + `provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`, + ), + threadId: sourceThread.id, + proposedPlan: { + ...sourcePlan, + implementedAt, + implementationThreadId, + updatedAt: implementedAt, + }, + createdAt: implementedAt, + }); + }, + ); const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( event: ProviderRuntimeEvent, diff --git a/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts index 56c526c08b..5c3148c943 100644 --- a/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts +++ b/apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts @@ -1,3 +1,13 @@ +/** + * RuntimeReceiptBus layers. + * + * `RuntimeReceiptBusLive` is the production default and intentionally does not + * retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory + * PubSub-backed implementation used by integration tests that need to await + * checkpoint-reactor milestones precisely. + * + * @module RuntimeReceiptBus + */ import { Effect, Layer, PubSub, Stream } from "effect"; import { @@ -6,13 +16,21 @@ import { type OrchestrationRuntimeReceipt, } from "../Services/RuntimeReceiptBus.ts"; -const makeRuntimeReceiptBus = Effect.gen(function* () { +const makeRuntimeReceiptBus = Effect.succeed({ + publish: () => Effect.void, + streamEventsForTest: Stream.empty, +} satisfies RuntimeReceiptBusShape); + +const makeRuntimeReceiptBusTest = Effect.gen(function* () { const pubSub = yield* PubSub.unbounded(); return { publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid), - stream: Stream.fromPubSub(pubSub), + get streamEventsForTest() { + return Stream.fromPubSub(pubSub); + }, } satisfies RuntimeReceiptBusShape; }); export const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus); +export const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest); diff --git a/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts b/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts index a08ff91685..bf5c94f3a0 100644 --- a/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts +++ b/apps/server/src/orchestration/Services/RuntimeReceiptBus.ts @@ -1,3 +1,19 @@ +/** + * RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts. + * + * This service exists to expose short-lived orchestration milestones that are + * useful in tests and harnesses but are not part of the production runtime + * event model. `CheckpointReactor` publishes receipts such as baseline capture, + * diff finalization, and turn-processing quiescence so integration tests can + * wait for those exact points without inferring them indirectly from persisted + * state. + * + * Production code should only call `publish`. Test code may subscribe via + * `streamEventsForTest`, which is intentionally named to make the intended + * usage explicit. + * + * @module RuntimeReceiptBus + */ import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts"; import { Schema, ServiceMap } from "effect"; import type { Effect, Stream } from "effect"; @@ -40,7 +56,7 @@ export type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Typ export interface RuntimeReceiptBusShape { readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect; - readonly stream: Stream.Stream; + readonly streamEventsForTest: Stream.Stream; } export class RuntimeReceiptBus extends ServiceMap.Service< diff --git a/apps/server/src/persistence/Layers/Sqlite.ts b/apps/server/src/persistence/Layers/Sqlite.ts index 07cbf44794..58556099db 100644 --- a/apps/server/src/persistence/Layers/Sqlite.ts +++ b/apps/server/src/persistence/Layers/Sqlite.ts @@ -6,6 +6,7 @@ import { ServerConfig } from "../../config.ts"; type RuntimeSqliteLayerConfig = { readonly filename: string; + readonly spanAttributes?: Record; }; type Loader = { @@ -41,7 +42,16 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")( const path = yield* Path.Path; yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); - return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath })); + return Layer.provideMerge( + setup, + makeRuntimeSqliteLayer({ + filename: dbPath, + spanAttributes: { + "db.name": path.basename(dbPath), + "service.name": "t3-server", + }, + }), + ); }, Layer.unwrap); export const SqlitePersistenceMemory = Layer.provideMerge( diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts new file mode 100644 index 0000000000..6366a768b7 --- /dev/null +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts @@ -0,0 +1,166 @@ +import { Effect, Layer, Stream } from "effect"; +import { describe, expect, it, vi } from "vitest"; +import type { OrchestrationReadModel } from "@t3tools/contracts"; + +import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts"; +import { TerminalManager } from "../../terminal/Services/Manager.ts"; +import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts"; +import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts"; + +const emptySnapshot = ( + scripts: OrchestrationReadModel["projects"][number]["scripts"], +): OrchestrationReadModel => + ({ + snapshotSequence: 1, + updatedAt: "2026-01-01T00:00:00.000Z", + projects: [ + { + id: "project-1", + title: "Project", + workspaceRoot: "/repo/project", + defaultModelSelection: null, + scripts, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + deletedAt: null, + }, + ], + threads: [], + providerSessions: [], + providerStatuses: [], + pendingApprovals: [], + latestTurnByThreadId: {}, + }) as unknown as OrchestrationReadModel; + +describe("ProjectSetupScriptRunner", () => { + it("returns no-script when no setup script exists", async () => { + const open = vi.fn(); + const write = vi.fn(); + const runner = await Effect.runPromise( + Effect.service(ProjectSetupScriptRunner).pipe( + Effect.provide( + ProjectSetupScriptRunnerLive.pipe( + Layer.provideMerge( + Layer.succeed(OrchestrationEngineService, { + getReadModel: () => Effect.succeed(emptySnapshot([])), + readEvents: () => Stream.empty, + dispatch: () => Effect.die(new Error("unused")), + streamDomainEvents: Stream.empty, + }), + ), + Layer.provideMerge( + Layer.succeed(TerminalManager, { + open, + write, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.die(new Error("unused")), + close: () => Effect.void, + subscribe: () => Effect.succeed(() => undefined), + }), + ), + ), + ), + ), + ); + + const result = await Effect.runPromise( + runner.runForThread({ + threadId: "thread-1", + projectId: "project-1", + worktreePath: "/repo/worktrees/a", + }), + ); + + expect(result).toEqual({ status: "no-script" }); + expect(open).not.toHaveBeenCalled(); + expect(write).not.toHaveBeenCalled(); + }); + + it("opens the deterministic setup terminal with worktree env and writes the command", async () => { + const open = vi.fn(() => + Effect.succeed({ + threadId: "thread-1", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + worktreePath: "/repo/worktrees/a", + status: "running" as const, + pid: 123, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: "2026-01-01T00:00:00.000Z", + }), + ); + const write = vi.fn(() => Effect.void); + const runner = await Effect.runPromise( + Effect.service(ProjectSetupScriptRunner).pipe( + Effect.provide( + ProjectSetupScriptRunnerLive.pipe( + Layer.provideMerge( + Layer.succeed(OrchestrationEngineService, { + getReadModel: () => + Effect.succeed( + emptySnapshot([ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + ), + readEvents: () => Stream.empty, + dispatch: () => Effect.die(new Error("unused")), + streamDomainEvents: Stream.empty, + }), + ), + Layer.provideMerge( + Layer.succeed(TerminalManager, { + open, + write, + resize: () => Effect.void, + clear: () => Effect.void, + restart: () => Effect.die(new Error("unused")), + close: () => Effect.void, + subscribe: () => Effect.succeed(() => undefined), + }), + ), + ), + ), + ), + ); + + const result = await Effect.runPromise( + runner.runForThread({ + threadId: "thread-1", + projectCwd: "/repo/project", + worktreePath: "/repo/worktrees/a", + }), + ); + + expect(result).toEqual({ + status: "started", + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + }); + expect(open).toHaveBeenCalledWith({ + threadId: "thread-1", + terminalId: "setup-setup", + cwd: "/repo/worktrees/a", + worktreePath: "/repo/worktrees/a", + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + T3CODE_WORKTREE_PATH: "/repo/worktrees/a", + }, + }); + expect(write).toHaveBeenCalledWith({ + threadId: "thread-1", + terminalId: "setup-setup", + data: "bun install\r", + }); + }); +}); diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts new file mode 100644 index 0000000000..3bac8cf0ab --- /dev/null +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.ts @@ -0,0 +1,75 @@ +import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts"; +import { Effect, Layer } from "effect"; + +import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts"; +import { TerminalManager } from "../../terminal/Services/Manager.ts"; +import { + type ProjectSetupScriptRunnerShape, + ProjectSetupScriptRunner, +} from "../Services/ProjectSetupScriptRunner.ts"; + +const makeProjectSetupScriptRunner = Effect.gen(function* () { + const orchestrationEngine = yield* OrchestrationEngineService; + const terminalManager = yield* TerminalManager; + + const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) => + Effect.gen(function* () { + const readModel = yield* orchestrationEngine.getReadModel(); + const project = + (input.projectId + ? readModel.projects.find((entry) => entry.id === input.projectId) + : null) ?? + (input.projectCwd + ? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd) + : null) ?? + null; + + if (!project) { + return yield* Effect.fail(new Error("Project was not found for setup script execution.")); + } + + const script = setupProjectScript(project.scripts); + if (!script) { + return { + status: "no-script", + } as const; + } + + const terminalId = input.preferredTerminalId ?? `setup-${script.id}`; + const cwd = input.worktreePath; + const env = projectScriptRuntimeEnv({ + project: { cwd: project.workspaceRoot }, + worktreePath: input.worktreePath, + }); + + yield* terminalManager.open({ + threadId: input.threadId, + terminalId, + cwd, + worktreePath: input.worktreePath, + env, + }); + yield* terminalManager.write({ + threadId: input.threadId, + terminalId, + data: `${script.command}\r`, + }); + + return { + status: "started", + scriptId: script.id, + scriptName: script.name, + terminalId, + cwd, + } as const; + }); + + return { + runForThread, + } satisfies ProjectSetupScriptRunnerShape; +}); + +export const ProjectSetupScriptRunnerLive = Layer.effect( + ProjectSetupScriptRunner, + makeProjectSetupScriptRunner, +); diff --git a/apps/server/src/project/Services/ProjectSetupScriptRunner.ts b/apps/server/src/project/Services/ProjectSetupScriptRunner.ts new file mode 100644 index 0000000000..3828096f85 --- /dev/null +++ b/apps/server/src/project/Services/ProjectSetupScriptRunner.ts @@ -0,0 +1,37 @@ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +export interface ProjectSetupScriptRunnerResultNoScript { + readonly status: "no-script"; +} + +export interface ProjectSetupScriptRunnerResultStarted { + readonly status: "started"; + readonly scriptId: string; + readonly scriptName: string; + readonly terminalId: string; + readonly cwd: string; +} + +export type ProjectSetupScriptRunnerResult = + | ProjectSetupScriptRunnerResultNoScript + | ProjectSetupScriptRunnerResultStarted; + +export interface ProjectSetupScriptRunnerInput { + readonly threadId: string; + readonly projectId?: string; + readonly projectCwd?: string; + readonly worktreePath: string; + readonly preferredTerminalId?: string; +} + +export interface ProjectSetupScriptRunnerShape { + readonly runForThread: ( + input: ProjectSetupScriptRunnerInput, + ) => Effect.Effect; +} + +export class ProjectSetupScriptRunner extends ServiceMap.Service< + ProjectSetupScriptRunner, + ProjectSetupScriptRunnerShape +>()("t3/project/ProjectSetupScriptRunner") {} diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index d99e2ad203..9f2eeb014e 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -3054,7 +3054,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( listSessions, hasSession, stopAll, - streamEvents: Stream.fromQueue(runtimeEventQueue), + get streamEvents() { + return Stream.fromQueue(runtimeEventQueue); + }, } satisfies ClaudeAdapterShape; }); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index cee6bca6ed..8b9f3b59e7 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -1631,7 +1631,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( listSessions, hasSession, stopAll, - streamEvents: Stream.fromQueue(runtimeEventQueue), + get streamEvents() { + return Stream.fromQueue(runtimeEventQueue); + }, } satisfies CodexAdapterShape; }); diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts index 258b50d6f2..9284ffac45 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts @@ -112,6 +112,49 @@ describe("EventNdjsonLogger", () => { }), ); + it.effect("serializes concurrent first writes for the same segment", () => + Effect.gen(function* () { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); + const basePath = path.join(tempDir, "provider-canonical.ndjson"); + + try { + const logger = yield* makeEventNdjsonLogger(basePath, { + stream: "canonical", + batchWindowMs: 0, + }); + assert.notEqual(logger, undefined); + if (!logger) { + return; + } + + yield* Effect.all( + [ + logger.write({ id: "evt-concurrent-1" }, null), + logger.write({ id: "evt-concurrent-2" }, null), + ], + { concurrency: "unbounded" }, + ); + yield* logger.close(); + + const globalPath = path.join(tempDir, "_global.log"); + assert.equal(fs.existsSync(globalPath), true); + const lines = fs + .readFileSync(globalPath, "utf8") + .trim() + .split("\n") + .map((line) => parseLogLine(line)); + + assert.equal(lines.length, 2); + assert.deepEqual(lines.map((line) => line.payload).toSorted(), [ + '{"id":"evt-concurrent-1"}', + '{"id":"evt-concurrent-2"}', + ]); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }), + ); + it.effect("rotates per-thread files when max size is exceeded", () => Effect.gen(function* () { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.ts index a4fd6f235d..2a512efe66 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.ts @@ -10,7 +10,7 @@ import path from "node:path"; import type { ThreadId } from "@t3tools/contracts"; import { RotatingFileSink } from "@t3tools/shared/logging"; -import { Effect, Exit, Logger, Scope } from "effect"; +import { Effect, Exit, Logger, Scope, SynchronizedRef } from "effect"; import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts"; @@ -40,6 +40,11 @@ interface ThreadWriter { close: () => Effect.Effect; } +interface LoggerState { + readonly threadWriters: Map; + readonly failedSegments: Set; +} + function logWarning(message: string, context: Record): Effect.Effect { return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE })); } @@ -193,34 +198,56 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function return undefined; } - const threadWriters = new Map(); - const failedSegments = new Set(); + const stateRef = yield* SynchronizedRef.make({ + threadWriters: new Map(), + failedSegments: new Set(), + }); const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* ( threadSegment: string, ): Effect.fn.Return { - if (failedSegments.has(threadSegment)) { - return undefined; - } - const existing = threadWriters.get(threadSegment); - if (existing) { - return existing; - } + return yield* SynchronizedRef.modifyEffect(stateRef, (state) => { + if (state.failedSegments.has(threadSegment)) { + return Effect.succeed([undefined, state] as const); + } - const writer = yield* makeThreadWriter({ - filePath: path.join(path.dirname(filePath), `${threadSegment}.log`), - maxBytes, - maxFiles, - batchWindowMs, - streamLabel, + const existing = state.threadWriters.get(threadSegment); + if (existing) { + return Effect.succeed([existing, state] as const); + } + + return makeThreadWriter({ + filePath: path.join(path.dirname(filePath), `${threadSegment}.log`), + maxBytes, + maxFiles, + batchWindowMs, + streamLabel, + }).pipe( + Effect.map((writer) => { + if (!writer) { + const nextFailedSegments = new Set(state.failedSegments); + nextFailedSegments.add(threadSegment); + return [ + undefined, + { + ...state, + failedSegments: nextFailedSegments, + }, + ] as const; + } + + const nextThreadWriters = new Map(state.threadWriters); + nextThreadWriters.set(threadSegment, writer); + return [ + writer, + { + ...state, + threadWriters: nextThreadWriters, + }, + ] as const; + }), + ); }); - if (!writer) { - failedSegments.add(threadSegment); - return undefined; - } - - threadWriters.set(threadSegment, writer); - return writer; }); const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) { @@ -239,10 +266,21 @@ export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function }); const close = Effect.fn("close")(function* () { - for (const writer of threadWriters.values()) { - yield* writer.close(); - } - threadWriters.clear(); + yield* SynchronizedRef.modifyEffect(stateRef, (state) => + Effect.gen(function* () { + for (const writer of state.threadWriters.values()) { + yield* writer.close(); + } + + return [ + undefined, + { + threadWriters: new Map(), + failedSegments: new Set(), + }, + ] as const; + }), + ); }); return { diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 116c008d67..ca27371b61 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -115,7 +115,9 @@ function makeMutableServerSettingsService( yield* PubSub.publish(changes, next); return next; }), - streamChanges: Stream.fromPubSub(changes), + get streamChanges() { + return Stream.fromPubSub(changes); + }, } satisfies ServerSettingsShape; }); } diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index 651a611649..fc3c9cf25c 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -20,7 +20,7 @@ import { import { it, assert, vi } from "@effect/vitest"; import { assertFailure } from "@effect/vitest/utils"; -import { Effect, Fiber, Layer, Option, PubSub, Ref, Stream } from "effect"; +import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { @@ -191,7 +191,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") { readThread, rollbackThread, stopAll, - streamEvents: Stream.fromPubSub(runtimeEventPubSub), + get streamEvents() { + return Stream.fromPubSub(runtimeEventPubSub); + }, }; const emit = (event: LegacyProviderRuntimeEvent): void => { @@ -230,6 +232,17 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") { const sleep = (ms: number) => Effect.promise(() => new Promise((resolve) => setTimeout(resolve, ms))); +const hasMetricSnapshot = ( + snapshots: ReadonlyArray, + id: string, + attributes: Readonly>, +) => + snapshots.some( + (snapshot) => + snapshot.id === id && + Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), + ); + function makeProviderServiceLayer() { const codex = makeFakeCodexAdapter(); const claude = makeFakeCodexAdapter("claudeAgent"); @@ -1060,6 +1073,120 @@ fanout.layer("ProviderServiceLive fanout", (it) => { ); }), ); + + it.effect("records provider metrics with the routed provider label", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-metrics"), { + provider: "claudeAgent", + threadId: asThreadId("thread-metrics"), + cwd: "/tmp/project", + runtimeMode: "full-access", + }); + + yield* provider.interruptTurn({ threadId: session.threadId }); + yield* provider.respondToRequest({ + threadId: session.threadId, + requestId: asRequestId("req-metrics-1"), + decision: "accept", + }); + yield* provider.respondToUserInput({ + threadId: session.threadId, + requestId: asRequestId("req-metrics-2"), + answers: { + sandbox_mode: "workspace-write", + }, + }); + yield* provider.rollbackConversation({ + threadId: session.threadId, + numTurns: 1, + }); + yield* provider.stopSession({ threadId: session.threadId }); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "interrupt", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "approval-response", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "user-input-response", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "rollback", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_sessions_total", { + provider: "claudeAgent", + operation: "stop", + outcome: "success", + }), + true, + ); + }), + ); + + it.effect( + "records sendTurn metrics with the resolved provider when modelSelection is omitted", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + + const session = yield* provider.startSession(asThreadId("thread-send-metrics"), { + provider: "claudeAgent", + threadId: asThreadId("thread-send-metrics"), + cwd: "/tmp/project-send-metrics", + runtimeMode: "full-access", + }); + + yield* provider.sendTurn({ + threadId: session.threadId, + input: "hello", + attachments: [], + }); + + const snapshots = yield* Metric.snapshot; + + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turns_total", { + provider: "claudeAgent", + operation: "send", + outcome: "success", + }), + true, + ); + assert.equal( + hasMetricSnapshot(snapshots, "t3_provider_turn_duration", { + provider: "claudeAgent", + operation: "send", + }), + true, + ); + }), + ); }); const validation = makeProviderServiceLayer(); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index f348829598..85fe9fbc32 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -22,8 +22,18 @@ import { type ProviderRuntimeEvent, type ProviderSession, } from "@t3tools/contracts"; -import { Effect, Layer, Option, PubSub, Queue, Schema, SchemaIssue, Stream } from "effect"; +import { Effect, Layer, Option, PubSub, Schema, SchemaIssue, Stream } from "effect"; +import { + increment, + providerMetricAttributes, + providerRuntimeEventsTotal, + providerSessionsTotal, + providerTurnDuration, + providerTurnsTotal, + providerTurnMetricAttributes, + withMetrics, +} from "../../observability/Metrics.ts"; import { ProviderValidationError } from "../Errors.ts"; import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts"; @@ -146,7 +156,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const registry = yield* ProviderAdapterRegistry; const directory = yield* ProviderSessionDirectory; - const runtimeEventQueue = yield* Queue.unbounded(); const runtimeEventPubSub = yield* PubSub.unbounded(); const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => @@ -179,75 +188,85 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const providers = yield* registry.listProviders(); const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider)); const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => - publishRuntimeEvent(event); - - const worker = Effect.forever( - Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)), - ); - yield* Effect.forkScoped(worker); + increment(providerRuntimeEventsTotal, { + provider: event.provider, + eventType: event.type, + }).pipe(Effect.andThen(publishRuntimeEvent(event))); yield* Effect.forEach(adapters, (adapter) => - Stream.runForEach(adapter.streamEvents, (event) => - Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid), - ).pipe(Effect.forkScoped), + Stream.runForEach(adapter.streamEvents, processRuntimeEvent).pipe(Effect.forkScoped), ).pipe(Effect.asVoid); const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: { readonly binding: ProviderRuntimeBinding; readonly operation: string; }) { - const adapter = yield* registry.getByProvider(input.binding.provider); - const hasResumeCursor = - input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined; - const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); - if (hasActiveSession) { - const activeSessions = yield* adapter.listSessions(); - const existing = activeSessions.find( - (session) => session.threadId === input.binding.threadId, - ); - if (existing) { - yield* upsertSessionBinding(existing, input.binding.threadId); - yield* analytics.record("provider.session.recovered", { - provider: existing.provider, - strategy: "adopt-existing", - hasResumeCursor: existing.resumeCursor !== undefined, - }); - return { adapter, session: existing } as const; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "recover-session", + "provider.kind": input.binding.provider, + "provider.thread_id": input.binding.threadId, + }); + return yield* Effect.gen(function* () { + const adapter = yield* registry.getByProvider(input.binding.provider); + const hasResumeCursor = + input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined; + const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); + if (hasActiveSession) { + const activeSessions = yield* adapter.listSessions(); + const existing = activeSessions.find( + (session) => session.threadId === input.binding.threadId, + ); + if (existing) { + yield* upsertSessionBinding(existing, input.binding.threadId); + yield* analytics.record("provider.session.recovered", { + provider: existing.provider, + strategy: "adopt-existing", + hasResumeCursor: existing.resumeCursor !== undefined, + }); + return { adapter, session: existing } as const; + } } - } - if (!hasResumeCursor) { - return yield* toValidationError( - input.operation, - `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`, - ); - } + if (!hasResumeCursor) { + return yield* toValidationError( + input.operation, + `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`, + ); + } - const persistedCwd = readPersistedCwd(input.binding.runtimePayload); - const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload); + const persistedCwd = readPersistedCwd(input.binding.runtimePayload); + const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload); - const resumed = yield* adapter.startSession({ - threadId: input.binding.threadId, - provider: input.binding.provider, - ...(persistedCwd ? { cwd: persistedCwd } : {}), - ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), - ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), - runtimeMode: input.binding.runtimeMode ?? "full-access", - }); - if (resumed.provider !== adapter.provider) { - return yield* toValidationError( - input.operation, - `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`, - ); - } + const resumed = yield* adapter.startSession({ + threadId: input.binding.threadId, + provider: input.binding.provider, + ...(persistedCwd ? { cwd: persistedCwd } : {}), + ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), + ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), + runtimeMode: input.binding.runtimeMode ?? "full-access", + }); + if (resumed.provider !== adapter.provider) { + return yield* toValidationError( + input.operation, + `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`, + ); + } - yield* upsertSessionBinding(resumed, input.binding.threadId); - yield* analytics.record("provider.session.recovered", { - provider: resumed.provider, - strategy: "resume-thread", - hasResumeCursor: resumed.resumeCursor !== undefined, - }); - return { adapter, session: resumed } as const; + yield* upsertSessionBinding(resumed, input.binding.threadId); + yield* analytics.record("provider.session.recovered", { + provider: resumed.provider, + strategy: "resume-thread", + hasResumeCursor: resumed.resumeCursor !== undefined, + }); + return { adapter, session: resumed } as const; + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + attributes: providerMetricAttributes(input.binding.provider, { + operation: "recover", + }), + }), + ); }); const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: { @@ -291,52 +310,69 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( threadId, provider: parsed.provider ?? "codex", }; - const settings = yield* serverSettings.getSettings.pipe( - Effect.mapError((error) => - toValidationError( - "ProviderService.startSession", - `Failed to load provider settings: ${error.message}`, - error, + yield* Effect.annotateCurrentSpan({ + "provider.operation": "start-session", + "provider.kind": input.provider, + "provider.thread_id": threadId, + "provider.runtime_mode": input.runtimeMode, + }); + return yield* Effect.gen(function* () { + const settings = yield* serverSettings.getSettings.pipe( + Effect.mapError((error) => + toValidationError( + "ProviderService.startSession", + `Failed to load provider settings: ${error.message}`, + error, + ), ), - ), + ); + if (!settings.providers[input.provider].enabled) { + return yield* toValidationError( + "ProviderService.startSession", + `Provider '${input.provider}' is disabled in T3 Code settings.`, + ); + } + const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId)); + const effectiveResumeCursor = + input.resumeCursor ?? + (persistedBinding?.provider === input.provider + ? persistedBinding.resumeCursor + : undefined); + const adapter = yield* registry.getByProvider(input.provider); + const session = yield* adapter.startSession({ + ...input, + ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), + }); + + if (session.provider !== adapter.provider) { + return yield* toValidationError( + "ProviderService.startSession", + `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, + ); + } + + yield* upsertSessionBinding(session, threadId, { + modelSelection: input.modelSelection, + }); + yield* analytics.record("provider.session.started", { + provider: session.provider, + runtimeMode: input.runtimeMode, + hasResumeCursor: session.resumeCursor !== undefined, + hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0, + hasModel: + typeof input.modelSelection?.model === "string" && + input.modelSelection.model.trim().length > 0, + }); + + return session; + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + attributes: providerMetricAttributes(input.provider, { + operation: "start", + }), + }), ); - if (!settings.providers[input.provider].enabled) { - return yield* toValidationError( - "ProviderService.startSession", - `Provider '${input.provider}' is disabled in T3 Code settings.`, - ); - } - const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId)); - const effectiveResumeCursor = - input.resumeCursor ?? - (persistedBinding?.provider === input.provider ? persistedBinding.resumeCursor : undefined); - const adapter = yield* registry.getByProvider(input.provider); - const session = yield* adapter.startSession({ - ...input, - ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), - }); - - if (session.provider !== adapter.provider) { - return yield* toValidationError( - "ProviderService.startSession", - `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, - ); - } - - yield* upsertSessionBinding(session, threadId, { - modelSelection: input.modelSelection, - }); - yield* analytics.record("provider.session.started", { - provider: session.provider, - runtimeMode: input.runtimeMode, - hasResumeCursor: session.resumeCursor !== undefined, - hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0, - hasModel: - typeof input.modelSelection?.model === "string" && - input.modelSelection.model.trim().length > 0, - }); - - return session; }, ); @@ -357,32 +393,61 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( "Either input text or at least one attachment is required", ); } - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.sendTurn", - allowRecovery: true, + yield* Effect.annotateCurrentSpan({ + "provider.operation": "send-turn", + "provider.thread_id": input.threadId, + "provider.interaction_mode": input.interactionMode, + "provider.attachment_count": input.attachments.length, }); - const turn = yield* routed.adapter.sendTurn(input); - yield* directory.upsert({ - threadId: input.threadId, - provider: routed.adapter.provider, - status: "running", - ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), - runtimePayload: { - ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), - activeTurnId: turn.turnId, - lastRuntimeEvent: "provider.sendTurn", - lastRuntimeEventAt: new Date().toISOString(), - }, - }); - yield* analytics.record("provider.turn.sent", { - provider: routed.adapter.provider, - model: input.modelSelection?.model, - interactionMode: input.interactionMode, - attachmentCount: input.attachments.length, - hasInput: typeof input.input === "string" && input.input.trim().length > 0, - }); - return turn; + let metricProvider = "unknown"; + let metricModel = input.modelSelection?.model; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.sendTurn", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + metricModel = input.modelSelection?.model; + yield* Effect.annotateCurrentSpan({ + "provider.kind": routed.adapter.provider, + ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}), + }); + const turn = yield* routed.adapter.sendTurn(input); + yield* directory.upsert({ + threadId: input.threadId, + provider: routed.adapter.provider, + status: "running", + ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), + runtimePayload: { + ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), + activeTurnId: turn.turnId, + lastRuntimeEvent: "provider.sendTurn", + lastRuntimeEventAt: new Date().toISOString(), + }, + }); + yield* analytics.record("provider.turn.sent", { + provider: routed.adapter.provider, + model: input.modelSelection?.model, + interactionMode: input.interactionMode, + attachmentCount: input.attachments.length, + hasInput: typeof input.input === "string" && input.input.trim().length > 0, + }); + return turn; + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + timer: providerTurnDuration, + attributes: () => + providerTurnMetricAttributes({ + provider: metricProvider, + model: metricModel, + extra: { + operation: "send", + }, + }), + }), + ); }); const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")( @@ -392,15 +457,33 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( schema: ProviderInterruptTurnInput, payload: rawInput, }); - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.interruptTurn", - allowRecovery: true, - }); - yield* routed.adapter.interruptTurn(routed.threadId, input.turnId); - yield* analytics.record("provider.turn.interrupted", { - provider: routed.adapter.provider, - }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.interruptTurn", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "interrupt-turn", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.turn_id": input.turnId, + }); + yield* routed.adapter.interruptTurn(routed.threadId, input.turnId); + yield* analytics.record("provider.turn.interrupted", { + provider: routed.adapter.provider, + }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "interrupt", + }), + }), + ); }, ); @@ -411,16 +494,34 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( schema: ProviderRespondToRequestInput, payload: rawInput, }); - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.respondToRequest", - allowRecovery: true, - }); - yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision); - yield* analytics.record("provider.request.responded", { - provider: routed.adapter.provider, - decision: input.decision, - }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.respondToRequest", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "respond-to-request", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.request_id": input.requestId, + }); + yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision); + yield* analytics.record("provider.request.responded", { + provider: routed.adapter.provider, + decision: input.decision, + }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "approval-response", + }), + }), + ); }, ); @@ -432,12 +533,30 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( schema: ProviderRespondToUserInputInput, payload: rawInput, }); - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.respondToUserInput", - allowRecovery: true, - }); - yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.respondToUserInput", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "respond-to-user-input", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.request_id": input.requestId, + }); + yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "user-input-response", + }), + }), + ); }); const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")( @@ -447,18 +566,35 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( schema: ProviderStopSessionInput, payload: rawInput, }); - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.stopSession", - allowRecovery: false, - }); - if (routed.isActive) { - yield* routed.adapter.stopSession(routed.threadId); - } - yield* directory.remove(input.threadId); - yield* analytics.record("provider.session.stopped", { - provider: routed.adapter.provider, - }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.stopSession", + allowRecovery: false, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "stop-session", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + }); + if (routed.isActive) { + yield* routed.adapter.stopSession(routed.threadId); + } + yield* directory.remove(input.threadId); + yield* analytics.record("provider.session.stopped", { + provider: routed.adapter.provider, + }); + }).pipe( + withMetrics({ + counter: providerSessionsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "stop", + }), + }), + ); }, ); @@ -524,16 +660,34 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( if (input.numTurns === 0) { return; } - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.rollbackConversation", - allowRecovery: true, - }); - yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns); - yield* analytics.record("provider.conversation.rolled_back", { - provider: routed.adapter.provider, - turns: input.numTurns, - }); + let metricProvider = "unknown"; + return yield* Effect.gen(function* () { + const routed = yield* resolveRoutableSession({ + threadId: input.threadId, + operation: "ProviderService.rollbackConversation", + allowRecovery: true, + }); + metricProvider = routed.adapter.provider; + yield* Effect.annotateCurrentSpan({ + "provider.operation": "rollback-conversation", + "provider.kind": routed.adapter.provider, + "provider.thread_id": input.threadId, + "provider.rollback_turns": input.numTurns, + }); + yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns); + yield* analytics.record("provider.conversation.rolled_back", { + provider: routed.adapter.provider, + turns: input.numTurns, + }); + }).pipe( + withMetrics({ + counter: providerTurnsTotal, + outcomeAttributes: () => + providerMetricAttributes(metricProvider, { + operation: "rollback", + }), + }), + ); }); const runStopAll = Effect.fn("runStopAll")(function* () { diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 4367ca40a7..7a23058fc7 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -1,13 +1,16 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeSocket from "@effect/platform-node/NodeSocket"; import * as NodeServices from "@effect/platform-node/NodeServices"; + import { CommandId, DEFAULT_SERVER_SETTINGS, GitCommandError, KeybindingRule, + MessageId, OpenError, TerminalNotRunningError, + type OrchestrationCommand, type OrchestrationEvent, ORCHESTRATION_WS_METHODS, ProjectId, @@ -19,9 +22,17 @@ import { } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; -import { Effect, FileSystem, Layer, Path, Stream } from "effect"; -import { HttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; +import { Effect, FileSystem, Layer, ManagedRuntime, Path, Stream } from "effect"; +import { + FetchHttpClient, + HttpBody, + HttpClient, + HttpRouter, + HttpServer, +} from "effect/unstable/http"; +import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; +import { vi } from "vitest"; import type { ServerConfigShape } from "./config.ts"; import { deriveServerPaths, ServerConfig } from "./config.ts"; @@ -39,6 +50,7 @@ import { OrchestrationEngineService, type OrchestrationEngineShape, } from "./orchestration/Services/OrchestrationEngine.ts"; +import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; import { ProjectionSnapshotQuery, type ProjectionSnapshotQueryShape, @@ -52,7 +64,15 @@ import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./server import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts"; import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts"; import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts"; +import { + BrowserTraceCollector, + type BrowserTraceCollectorShape, +} from "./observability/Services/BrowserTraceCollector.ts"; import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; +import { + ProjectSetupScriptRunner, + type ProjectSetupScriptRunnerShape, +} from "./project/Services/ProjectSetupScriptRunner.ts"; import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; @@ -116,6 +136,113 @@ const workspaceAndProjectServicesLayer = Layer.mergeAll( ProjectFaviconResolverLive, ); +const browserOtlpTracingLayer = Layer.mergeAll( + FetchHttpClient.layer, + OtlpSerialization.layerJson, + Layer.succeed(HttpClient.TracerDisabledWhen, () => true), +); + +const makeBrowserOtlpPayload = (spanName: string) => + Effect.gen(function* () { + const collector = yield* Effect.acquireRelease( + Effect.promise(async () => { + const NodeHttp = await import("node:http"); + + return await new Promise<{ + readonly close: () => Promise; + readonly firstRequest: Promise<{ + readonly body: string; + readonly contentType: string | null; + }>; + readonly url: string; + }>((resolve, reject) => { + let resolveFirstRequest: + | ((request: { readonly body: string; readonly contentType: string | null }) => void) + | undefined; + const firstRequest = new Promise<{ + readonly body: string; + readonly contentType: string | null; + }>((resolveRequest) => { + resolveFirstRequest = resolveRequest; + }); + + const server = NodeHttp.createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + request.on("end", () => { + resolveFirstRequest?.({ + body: Buffer.concat(chunks).toString("utf8"), + contentType: request.headers["content-type"] ?? null, + }); + resolveFirstRequest = undefined; + response.statusCode = 204; + response.end(); + }); + }); + + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Expected TCP collector address")); + return; + } + + resolve({ + url: `http://127.0.0.1:${address.port}/v1/traces`, + firstRequest, + close: () => + new Promise((resolveClose, rejectClose) => { + server.close((error) => { + if (error) { + rejectClose(error); + return; + } + resolveClose(); + }); + }), + }); + }); + }); + }), + ({ close }) => Effect.promise(close), + ); + + const runtime = ManagedRuntime.make( + OtlpTracer.layer({ + url: collector.url, + exportInterval: "10 millis", + resource: { + serviceName: "t3-web", + attributes: { + "service.runtime": "t3-web", + "service.mode": "browser", + "service.version": "test", + }, + }, + }).pipe(Layer.provide(browserOtlpTracingLayer)), + ); + + try { + yield* Effect.promise(() => runtime.runPromise(Effect.void.pipe(Effect.withSpan(spanName)))); + } finally { + yield* Effect.promise(() => runtime.dispose()); + } + + const request = yield* Effect.promise(() => + Promise.race([ + collector.firstRequest, + new Promise((_, reject) => { + setTimeout(() => reject(new Error("Timed out waiting for OTLP trace export")), 1_000); + }), + ]), + ); + + return JSON.parse(request.body) as OtlpTracer.TraceData; + }); + const buildAppUnderTest = (options?: { config?: Partial; layers?: { @@ -125,10 +252,12 @@ const buildAppUnderTest = (options?: { open?: Partial; gitCore?: Partial; gitManager?: Partial; + projectSetupScriptRunner?: Partial; terminalManager?: Partial; orchestrationEngine?: Partial; projectionSnapshotQuery?: Partial; checkpointDiffQuery?: Partial; + browserTraceCollector?: Partial; serverLifecycleEvents?: Partial; serverRuntimeStartup?: Partial; }; @@ -139,8 +268,17 @@ const buildAppUnderTest = (options?: { const baseDir = options?.config?.baseDir ?? tempBaseDir; const devUrl = options?.config?.devUrl; const derivedPaths = yield* deriveServerPaths(baseDir, devUrl); - const config = { + const config: ServerConfigShape = { logLevel: "Info", + traceMinLevel: "Info", + traceTimingEnabled: true, + traceBatchWindowMs: 200, + traceMaxBytes: 10 * 1024 * 1024, + traceMaxFiles: 10, + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + otlpExportIntervalMs: 10_000, + otlpServiceName: "t3-server", mode: "web", port: 0, host: "127.0.0.1", @@ -154,7 +292,7 @@ const buildAppUnderTest = (options?: { autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, ...options?.config, - } satisfies ServerConfigShape; + }; const layerConfig = Layer.succeed(ServerConfig, config); const appLayer = HttpRouter.serve(makeRoutesLayer, { @@ -200,6 +338,12 @@ const buildAppUnderTest = (options?: { ...options?.layers?.gitManager, }), ), + Layer.provide( + Layer.mock(ProjectSetupScriptRunner)({ + runForThread: () => Effect.succeed({ status: "no-script" as const }), + ...options?.layers?.projectSetupScriptRunner, + }), + ), Layer.provide( Layer.mock(TerminalManager)({ ...options?.layers?.terminalManager, @@ -239,6 +383,12 @@ const buildAppUnderTest = (options?: { ...options?.layers?.checkpointDiffQuery, }), ), + Layer.provide( + Layer.mock(BrowserTraceCollector)({ + record: () => Effect.void, + ...options?.layers?.browserTraceCollector, + }), + ), Layer.provide( Layer.mock(ServerLifecycleEvents)({ publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }), @@ -256,6 +406,7 @@ const buildAppUnderTest = (options?: { }), ), Layer.provide(workspaceAndProjectServicesLayer), + Layer.provideMerge(FetchHttpClient.layer), Layer.provide(layerConfig), ); @@ -413,6 +564,285 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + it.effect("proxies browser OTLP trace exports through the server", () => + Effect.gen(function* () { + const upstreamRequests: Array<{ + readonly body: string; + readonly contentType: string | null; + }> = []; + const localTraceRecords: Array = []; + const payload = { + resourceSpans: [ + { + resource: { + attributes: [ + { + key: "service.name", + value: { stringValue: "t3-web" }, + }, + ], + }, + scopeSpans: [ + { + scope: { + name: "effect", + version: "4.0.0-beta.43", + }, + spans: [ + { + traceId: "11111111111111111111111111111111", + spanId: "2222222222222222", + parentSpanId: "3333333333333333", + name: "RpcClient.server.getSettings", + kind: 3, + startTimeUnixNano: "1000000", + endTimeUnixNano: "2000000", + attributes: [ + { + key: "rpc.method", + value: { stringValue: "server.getSettings" }, + }, + ], + events: [ + { + name: "http.request", + timeUnixNano: "1500000", + attributes: [ + { + key: "http.status_code", + value: { intValue: "200" }, + }, + ], + }, + ], + links: [], + status: { + code: "STATUS_CODE_OK", + }, + flags: 1, + }, + ], + }, + ], + }, + ], + }; + + const collector = yield* Effect.acquireRelease( + Effect.promise(async () => { + const NodeHttp = await import("node:http"); + + return await new Promise<{ + readonly close: () => Promise; + readonly url: string; + }>((resolve, reject) => { + const server = NodeHttp.createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + request.on("end", () => { + upstreamRequests.push({ + body: Buffer.concat(chunks).toString("utf8"), + contentType: request.headers["content-type"] ?? null, + }); + response.statusCode = 204; + response.end(); + }); + }); + + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Expected TCP collector address")); + return; + } + + resolve({ + url: `http://127.0.0.1:${address.port}/v1/traces`, + close: () => + new Promise((resolveClose, rejectClose) => { + server.close((error) => { + if (error) { + rejectClose(error); + return; + } + resolveClose(); + }); + }), + }); + }); + }); + }), + ({ close }) => Effect.promise(close), + ); + + yield* buildAppUnderTest({ + config: { + otlpTracesUrl: collector.url, + }, + layers: { + browserTraceCollector: { + record: (records) => + Effect.sync(() => { + localTraceRecords.push(...records); + }), + }, + }, + }); + + const response = yield* HttpClient.post("/api/observability/v1/traces", { + headers: { + "content-type": "application/json", + origin: "http://localhost:5733", + }, + body: HttpBody.text(JSON.stringify(payload), "application/json"), + }); + + assert.equal(response.status, 204); + assert.equal(response.headers["access-control-allow-origin"], "*"); + assert.deepEqual(localTraceRecords, [ + { + type: "otlp-span", + name: "RpcClient.server.getSettings", + traceId: "11111111111111111111111111111111", + spanId: "2222222222222222", + parentSpanId: "3333333333333333", + sampled: true, + kind: "client", + startTimeUnixNano: "1000000", + endTimeUnixNano: "2000000", + durationMs: 1, + attributes: { + "rpc.method": "server.getSettings", + }, + resourceAttributes: { + "service.name": "t3-web", + }, + scope: { + name: "effect", + version: "4.0.0-beta.43", + attributes: {}, + }, + events: [ + { + name: "http.request", + timeUnixNano: "1500000", + attributes: { + "http.status_code": "200", + }, + }, + ], + links: [], + status: { + code: "STATUS_CODE_OK", + }, + }, + ]); + assert.deepEqual(upstreamRequests, [ + { + body: JSON.stringify(payload), + contentType: "application/json", + }, + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("responds to browser OTLP trace preflight requests with CORS headers", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const url = yield* getHttpServerUrl("/api/observability/v1/traces"); + const response = yield* Effect.promise(() => + fetch(url, { + method: "OPTIONS", + headers: { + origin: "http://localhost:5733", + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }, + }), + ); + + assert.equal(response.status, 204); + assert.equal(response.headers.get("access-control-allow-origin"), "*"); + assert.equal(response.headers.get("access-control-allow-methods"), "POST, OPTIONS"); + assert.equal(response.headers.get("access-control-allow-headers"), "content-type"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "stores browser OTLP trace exports locally when no upstream collector is configured", + () => + Effect.gen(function* () { + const localTraceRecords: Array = []; + const payload = yield* makeBrowserOtlpPayload("client.test"); + const resourceSpan = payload.resourceSpans[0]; + const scopeSpan = resourceSpan?.scopeSpans[0]; + const span = scopeSpan?.spans[0]; + + assert.notEqual(resourceSpan, undefined); + assert.notEqual(scopeSpan, undefined); + assert.notEqual(span, undefined); + if (!resourceSpan || !scopeSpan || !span) { + return; + } + + yield* buildAppUnderTest({ + layers: { + browserTraceCollector: { + record: (records) => + Effect.sync(() => { + localTraceRecords.push(...records); + }), + }, + }, + }); + + const response = yield* HttpClient.post("/api/observability/v1/traces", { + headers: { + "content-type": "application/json", + }, + body: HttpBody.text(JSON.stringify(payload), "application/json"), + }); + + assert.equal(response.status, 204); + assert.equal(localTraceRecords.length, 1); + const record = localTraceRecords[0] as { + readonly type: string; + readonly name: string; + readonly traceId: string; + readonly spanId: string; + readonly kind: string; + readonly attributes: Readonly>; + readonly events: ReadonlyArray; + readonly links: ReadonlyArray; + readonly scope: { + readonly name?: string; + readonly attributes: Readonly>; + }; + readonly resourceAttributes: Readonly>; + readonly status?: { + readonly code?: string; + }; + }; + + assert.equal(record.type, "otlp-span"); + assert.equal(record.name, span.name); + assert.equal(record.traceId, span.traceId); + assert.equal(record.spanId, span.spanId); + assert.equal(record.kind, "internal"); + assert.deepEqual(record.attributes, {}); + assert.deepEqual(record.events, []); + assert.deepEqual(record.links, []); + assert.equal(record.scope.name, scopeSpan.scope.name); + assert.deepEqual(record.scope.attributes, {}); + assert.equal(record.resourceAttributes["service.name"], "t3-web"); + assert.equal(record.status?.code, String(span.status.code)); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect("returns 404 for missing attachment id lookups", () => Effect.gen(function* () { yield* buildAppUnderTest(); @@ -533,6 +963,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => { } as const; yield* buildAppUnderTest({ + config: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, layers: { keybindings: { loadConfigState: Effect.succeed({ @@ -561,6 +995,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.deepEqual(first.config.keybindings, []); assert.deepEqual(first.config.issues, []); assert.deepEqual(first.config.providers, providers); + assert.equal(first.config.observability.logsDirectoryPath.endsWith("/logs"), true); + assert.equal(first.config.observability.localTracingEnabled, true); + assert.equal(first.config.observability.otlpTracesUrl, "http://localhost:4318/v1/traces"); + assert.equal(first.config.observability.otlpTracesEnabled, true); + assert.equal(first.config.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics"); + assert.equal(first.config.observability.otlpMetricsEnabled, true); assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS); } assert.deepEqual(second, { @@ -1228,6 +1668,413 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + it.effect( + "bootstraps first-send worktree turns on the server before dispatching turn start", + () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.succeed({ + status: "started" as const, + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/tmp/bootstrap-worktree", + }), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start"), + threadId: ThreadId.makeUnsafe("thread-bootstrap"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 5); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + [ + "thread.create", + "thread.meta.update", + "thread.activity.append", + "thread.activity.append", + "thread.turn.start", + ], + ); + assert.deepEqual(createWorktree.mock.calls[0]?.[0], { + cwd: "/tmp/project", + branch: "main", + newBranch: "t3code/bootstrap-branch", + path: null, + }); + assert.deepEqual(runForThread.mock.calls[0]?.[0], { + threadId: ThreadId.makeUnsafe("thread-bootstrap"), + projectId: defaultProjectId, + projectCwd: "/tmp/project", + worktreePath: "/tmp/bootstrap-worktree", + }); + + const setupActivities = dispatchedCommands.filter( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.deepEqual( + setupActivities.map((command) => command.activity.kind), + ["setup-script.requested", "setup-script.started"], + ); + const finalCommand = dispatchedCommands[4]; + assertTrue(finalCommand?.type === "thread.turn.start"); + if (finalCommand?.type === "thread.turn.start") { + assert.equal(finalCommand.bootstrap, undefined); + } + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("records setup-script failures without aborting bootstrap turn start", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.fail(new Error("pty unavailable")), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-failure"), + threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-failure"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap-setup-failure"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 4); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], + ); + const setupFailureActivity = dispatchedCommands.find( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed"); + assert.deepEqual(setupFailureActivity?.activity.payload, { + detail: "pty unavailable", + worktreePath: "/tmp/bootstrap-worktree", + }); + assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.succeed({ + worktree: { + branch: "t3code/bootstrap-branch", + path: "/tmp/bootstrap-worktree", + }, + }), + ); + const runForThread = vi.fn( + (_: Parameters[0]) => + Effect.succeed({ + status: "started" as const, + scriptId: "setup", + scriptName: "Setup", + terminalId: "setup-setup", + cwd: "/tmp/bootstrap-worktree", + }), + ); + let setupActivityAppendAttempt = 0; + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => { + if ( + command.type === "thread.activity.append" && + command.activity.kind.startsWith("setup-script.") + ) { + setupActivityAppendAttempt += 1; + if (setupActivityAppendAttempt === 2) { + return Effect.fail( + new OrchestrationListenerCallbackError({ + listener: "domain-event", + detail: "failed to append setup-script.started activity", + }), + ); + } + } + + return Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }); + }, + readEvents: () => Stream.empty, + }, + projectSetupScriptRunner: { + runForThread, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-setup-activity-failure"), + threadId: ThreadId.makeUnsafe("thread-bootstrap-setup-activity-failure"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap-setup-activity-failure"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: true, + }, + createdAt, + }), + ), + ); + + assert.equal(response.sequence, 4); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], + ); + const setupActivities = dispatchedCommands.filter( + (command): command is Extract => + command.type === "thread.activity.append", + ); + assert.deepEqual( + setupActivities.map((command) => command.activity.kind), + ["setup-script.requested"], + ); + assertTrue( + setupActivities.every((command) => command.activity.kind !== "setup-script.failed"), + ); + assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("cleans up created bootstrap threads when worktree creation defects", () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const createWorktree = vi.fn((_: Parameters[0]) => + Effect.die(new Error("worktree exploded")), + ); + + yield* buildAppUnderTest({ + layers: { + gitCore: { + createWorktree, + }, + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + }, + }); + + const createdAt = new Date().toISOString(); + const wsUrl = yield* getWsServerUrl("/ws"); + const result = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-bootstrap-turn-start-defect"), + threadId: ThreadId.makeUnsafe("thread-bootstrap-defect"), + message: { + messageId: MessageId.makeUnsafe("msg-bootstrap-defect"), + role: "user", + text: "hello", + attachments: [], + }, + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: defaultProjectId, + title: "Bootstrap Thread", + modelSelection: defaultModelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt, + }, + prepareWorktree: { + projectCwd: "/tmp/project", + baseBranch: "main", + branch: "t3code/bootstrap-branch", + }, + runSetupScript: false, + }, + createdAt, + }), + ).pipe(Effect.result), + ); + + assertTrue(result._tag === "Failure"); + assertTrue(result.failure._tag === "OrchestrationDispatchCommandError"); + assert.include(result.failure.message, "worktree exploded"); + assert.deepEqual( + dispatchedCommands.map((command) => command.type), + ["thread.create", "thread.delete"], + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect( "routes websocket rpc subscribeOrchestrationDomainEvents with replay/live overlap resilience", () => @@ -1323,6 +2170,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { threadId: "thread-1", terminalId: "default", cwd: "/tmp/project", + worktreePath: null, status: "running" as const, pid: 1234, history: "", diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 4e296e817a..f56edde6fa 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -2,7 +2,12 @@ import { Effect, Layer } from "effect"; import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http"; import { ServerConfig } from "./config"; -import { attachmentsRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer } from "./http"; +import { + attachmentsRouteLayer, + otlpTracesProxyRouteLayer, + projectFaviconRouteLayer, + staticAndDevRouteLayer, +} from "./http"; import { fixPath } from "./os-jank"; import { websocketRpcRouteLayer } from "./ws"; import { OpenLive } from "./open"; @@ -29,7 +34,6 @@ import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration"; import { TerminalManagerLive } from "./terminal/Layers/Manager"; import { GitManagerLive } from "./git/Layers/GitManager"; import { KeybindingsLive } from "./keybindings"; -import { ServerLoggerLive } from "./serverLogger"; import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup"; import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor"; import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus"; @@ -42,6 +46,8 @@ import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResol import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries"; import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem"; import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths"; +import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner"; +import { ObservabilityLive } from "./observability/Layers/Observability"; const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { @@ -158,6 +164,7 @@ const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersisten const GitLayerLive = Layer.empty.pipe( Layer.provideMerge( GitManagerLive.pipe( + Layer.provideMerge(ProjectSetupScriptRunnerLive), Layer.provideMerge(GitCoreLive), Layer.provideMerge(GitHubCliLive), Layer.provideMerge(RoutingTextGenerationLive), @@ -177,15 +184,12 @@ const WorkspaceLayerLive = Layer.mergeAll( ), ); -const RuntimeServicesLive = Layer.empty.pipe( - Layer.provideMerge(ServerRuntimeStartupLive), - Layer.provideMerge(ReactorLayerLive), - +const RuntimeDependenciesLive = ReactorLayerLive.pipe( // Core Services Layer.provideMerge(CheckpointingLayerLive), + Layer.provideMerge(GitLayerLive), Layer.provideMerge(OrchestrationLayerLive), Layer.provideMerge(ProviderLayerLive), - Layer.provideMerge(GitLayerLive), Layer.provideMerge(TerminalLayerLive), Layer.provideMerge(PersistenceLayerLive), Layer.provideMerge(KeybindingsLive), @@ -200,8 +204,13 @@ const RuntimeServicesLive = Layer.empty.pipe( Layer.provideMerge(ServerLifecycleEventsLive), ); +const RuntimeServicesLive = ServerRuntimeStartupLive.pipe( + Layer.provideMerge(RuntimeDependenciesLive), +); + export const makeRoutesLayer = Layer.mergeAll( attachmentsRouteLayer, + otlpTracesProxyRouteLayer, projectFaviconRouteLayer, staticAndDevRouteLayer, websocketRpcRouteLayer, @@ -231,7 +240,7 @@ export const makeServerLayer = Layer.unwrap( return serverApplicationLayer.pipe( Layer.provideMerge(RuntimeServicesLive), Layer.provideMerge(HttpServerLive), - Layer.provide(ServerLoggerLive), + Layer.provide(ObservabilityLive), Layer.provideMerge(FetchHttpClient.layer), Layer.provideMerge(PlatformServicesLive), ); diff --git a/apps/server/src/serverLogger.ts b/apps/server/src/serverLogger.ts index aea53aacfb..ea098dcbbe 100644 --- a/apps/server/src/serverLogger.ts +++ b/apps/server/src/serverLogger.ts @@ -4,11 +4,8 @@ import { ServerConfig } from "./config"; export const ServerLoggerLive = Effect.gen(function* () { const config = yield* ServerConfig; - const { serverLogPath } = config; - - const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath)); const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel); - const loggerLayer = Logger.layer([Logger.consolePretty(), fileLogger], { + const loggerLayer = Logger.layer([Logger.consolePretty(), Logger.tracerLogger], { mergeWithExisting: false, }); diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 026145eca5..7c9231ac93 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -141,6 +141,8 @@ export const recordStartupHeartbeat = Effect.gen(function* () { }); export const launchStartupHeartbeat = recordStartupHeartbeat.pipe( + Effect.annotateSpans({ "startup.phase": "heartbeat.record" }), + Effect.withSpan("server.startup.heartbeat.record"), Effect.ignoreCause({ log: true }), Effect.forkScoped, Effect.asVoid, @@ -248,7 +250,14 @@ const maybeOpenBrowser = Effect.gen(function* () { ); }); +const runStartupPhase = (phase: string, effect: Effect.Effect) => + effect.pipe( + Effect.annotateSpans({ "startup.phase": phase }), + Effect.withSpan(`server.startup.${phase}`), + ); + const makeServerRuntimeStartup = Effect.gen(function* () { + const serverConfig = yield* ServerConfig; const keybindings = yield* Keybindings; const orchestrationReactor = yield* OrchestrationReactor; const lifecycleEvents = yield* ServerLifecycleEvents; @@ -262,46 +271,65 @@ const makeServerRuntimeStartup = Effect.gen(function* () { const startup = Effect.gen(function* () { yield* Effect.logDebug("startup phase: starting keybindings runtime"); - yield* keybindings.start.pipe( - Effect.catch((error) => - Effect.logWarning("failed to start keybindings runtime", { - path: error.configPath, - detail: error.detail, - cause: error.cause, - }), + yield* runStartupPhase( + "keybindings.start", + keybindings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start keybindings runtime", { + path: error.configPath, + detail: error.detail, + cause: error.cause, + }), + ), + Effect.forkScoped, ), - Effect.forkScoped, ); yield* Effect.logDebug("startup phase: starting server settings runtime"); - yield* serverSettings.start.pipe( - Effect.catch((error) => - Effect.logWarning("failed to start server settings runtime", { - path: error.settingsPath, - detail: error.detail, - cause: error.cause, - }), + yield* runStartupPhase( + "settings.start", + serverSettings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start server settings runtime", { + path: error.settingsPath, + detail: error.detail, + cause: error.cause, + }), + ), + Effect.forkScoped, ), - Effect.forkScoped, ); yield* Effect.logDebug("startup phase: starting orchestration reactors"); - yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope)); + yield* runStartupPhase( + "reactors.start", + orchestrationReactor.start().pipe(Scope.provide(reactorScope)), + ); yield* Effect.logDebug("startup phase: preparing welcome payload"); - const welcome = yield* autoBootstrapWelcome; + const welcome = yield* runStartupPhase("welcome.prepare", autoBootstrapWelcome); yield* Effect.logDebug("startup phase: publishing welcome event", { cwd: welcome.cwd, projectName: welcome.projectName, bootstrapProjectId: welcome.bootstrapProjectId, bootstrapThreadId: welcome.bootstrapThreadId, }); - yield* lifecycleEvents.publish({ - version: 1, - type: "welcome", - payload: welcome, - }); - }); + yield* runStartupPhase( + "welcome.publish", + lifecycleEvents.publish({ + version: 1, + type: "welcome", + payload: welcome, + }), + ); + }).pipe( + Effect.annotateSpans({ + "server.mode": serverConfig.mode, + "server.port": serverConfig.port, + "server.host": serverConfig.host ?? "default", + }), + Effect.withSpan("server.startup", { kind: "server", root: true }), + ); yield* Effect.forkScoped( Effect.gen(function* () { @@ -319,18 +347,21 @@ const makeServerRuntimeStartup = Effect.gen(function* () { yield* Effect.logDebug("Accepting commands"); yield* commandGate.signalCommandReady; yield* Effect.logDebug("startup phase: waiting for http listener"); - yield* Deferred.await(httpListening); + yield* runStartupPhase("http.wait", Deferred.await(httpListening)); yield* Effect.logDebug("startup phase: publishing ready event"); - yield* lifecycleEvents.publish({ - version: 1, - type: "ready", - payload: { at: new Date().toISOString() }, - }); + yield* runStartupPhase( + "ready.publish", + lifecycleEvents.publish({ + version: 1, + type: "ready", + payload: { at: new Date().toISOString() }, + }), + ); yield* Effect.logDebug("startup phase: recording startup heartbeat"); yield* launchStartupHeartbeat; yield* Effect.logDebug("startup phase: browser open check"); - yield* maybeOpenBrowser; + yield* runStartupPhase("browser.open", maybeOpenBrowser); yield* Effect.logDebug("startup phase: complete"); }), ); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index c0aec009a0..289bc68961 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -171,6 +171,24 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(makeServerSettingsLayer())), ); + it.effect("trims observability settings when updates are applied", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + const next = yield* serverSettings.updateSettings({ + observability: { + otlpTracesUrl: " http://localhost:4318/v1/traces ", + otlpMetricsUrl: " http://localhost:4318/v1/metrics ", + }, + }); + + assert.deepEqual(next.observability, { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + it.effect("defaults blank binary paths to provider executables", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; @@ -197,6 +215,10 @@ it.layer(NodeServices.layer)("server settings", (it) => { const serverConfig = yield* ServerConfig; const fileSystem = yield* FileSystem.FileSystem; const next = yield* serverSettings.updateSettings({ + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, providers: { codex: { binaryPath: "/opt/homebrew/bin/codex", @@ -208,6 +230,10 @@ it.layer(NodeServices.layer)("server settings", (it) => { const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); assert.deepEqual(JSON.parse(raw), { + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, providers: { codex: { binaryPath: "/opt/homebrew/bin/codex", diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.ts b/apps/server/src/telemetry/Layers/AnalyticsService.ts index 06ecfd0237..e933576dff 100644 --- a/apps/server/src/telemetry/Layers/AnalyticsService.ts +++ b/apps/server/src/telemetry/Layers/AnalyticsService.ts @@ -125,17 +125,19 @@ const makeAnalyticsService = Effect.gen(function* () { } }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause }))); - const record: AnalyticsServiceShape["record"] = Effect.fnUntraced(function* (event, properties) { - if (!telemetryConfig.enabled || !identifier) return; + const record: AnalyticsServiceShape["record"] = Effect.fn("record")( + function* (event, properties) { + if (!telemetryConfig.enabled || !identifier) return; - const enqueueResult = yield* enqueueBufferedEvent(event, properties); - if (enqueueResult.dropped) { - yield* Effect.logDebug("analytics buffer full; dropping oldest event", { - size: enqueueResult.size, - event, - }); - } - }); + const enqueueResult = yield* enqueueBufferedEvent(event, properties); + if (enqueueResult.dropped) { + yield* Effect.logDebug("analytics buffer full; dropping oldest event", { + size: enqueueResult.size, + event, + }); + } + }, + ); yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), { disableYield: true, diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index ccdd477178..8207861e20 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -428,6 +428,85 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", ( }), ); + it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () => + Effect.gen(function* () { + const { manager, getEvents, baseDir } = yield* createManager(); + const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a"); + const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b"); + yield* makeDirectory(firstWorktreePath); + yield* makeDirectory(secondWorktreePath); + const startedSnapshot = yield* manager.open( + openInput({ + cwd: firstWorktreePath, + worktreePath: firstWorktreePath, + }), + ); + const restartedSnapshot = yield* manager.restart( + restartInput({ + cwd: secondWorktreePath, + worktreePath: secondWorktreePath, + }), + ); + + assert.equal(startedSnapshot.worktreePath, firstWorktreePath); + assert.equal(restartedSnapshot.worktreePath, secondWorktreePath); + + const events = yield* getEvents; + const startedEvent = events.find( + (event): event is Extract => event.type === "started", + ); + const restartedEvent = events.find( + (event): event is Extract => + event.type === "restarted", + ); + + assert.equal(startedEvent?.snapshot.worktreePath, firstWorktreePath); + assert.equal(restartedEvent?.snapshot.worktreePath, secondWorktreePath); + }), + ); + + it.effect("preserves worktree metadata when reopening an exited session", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager(); + const worktreePath = path.join(baseDir, "worktrees", "feature-a"); + yield* makeDirectory(worktreePath); + + yield* manager.open( + openInput({ + cwd: worktreePath, + worktreePath, + }), + ); + + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), + ); + + const reopenedSnapshot = yield* manager.open( + openInput({ + cwd: worktreePath, + worktreePath, + }), + ); + + assert.equal(reopenedSnapshot.worktreePath, worktreePath); + + const events = yield* getEvents; + const reopenedEvent = events + .toReversed() + .find( + (event): event is Extract => event.type === "started", + ); + + assert.equal(reopenedEvent?.snapshot.worktreePath, worktreePath); + }), + ); + it.effect("emits exited event and reopens with clean transcript after exit", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index 7ef18b1655..5dc216e37e 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -23,6 +23,11 @@ import { } from "effect"; import { ServerConfig } from "../../config"; +import { + increment, + terminalRestartsTotal, + terminalSessionsTotal, +} from "../../observability/Metrics"; import { runProcess } from "../../processRunner"; import { TerminalCwdError, @@ -75,6 +80,7 @@ interface TerminalStartInput { threadId: string; terminalId: string; cwd: string; + worktreePath?: string | null; cols: number; rows: number; env?: Record; @@ -84,6 +90,7 @@ interface TerminalSessionState { threadId: string; terminalId: string; cwd: string; + worktreePath: string | null; status: TerminalSessionStatus; pid: number | null; history: string; @@ -138,6 +145,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { threadId: session.threadId, terminalId: session.terminalId, cwd: session.cwd, + worktreePath: session.worktreePath, status: session.status, pid: session.pid, history: session.history, @@ -1294,10 +1302,17 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith eventType: "started" | "restarted", ) { yield* stopProcess(session); + yield* Effect.annotateCurrentSpan({ + "terminal.thread_id": session.threadId, + "terminal.id": session.terminalId, + "terminal.event_type": eventType, + "terminal.cwd": input.cwd, + }); yield* modifyManagerState((state) => { session.status = "starting"; session.cwd = input.cwd; + session.worktreePath = input.worktreePath ?? null; session.cols = input.cols; session.rows = input.rows; session.exitCode = null; @@ -1314,45 +1329,49 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith let startedShell: string | null = null; const startResult = yield* Effect.result( - Effect.gen(function* () { - const shellCandidates = resolveShellCandidates(shellResolver); - const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); - const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session); - ptyProcess = spawnResult.process; - startedShell = spawnResult.shellLabel; + increment(terminalSessionsTotal, { lifecycle: eventType }).pipe( + Effect.andThen( + Effect.gen(function* () { + const shellCandidates = resolveShellCandidates(shellResolver); + const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); + const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session); + ptyProcess = spawnResult.process; + startedShell = spawnResult.shellLabel; - const processPid = ptyProcess.pid; - const unsubscribeData = ptyProcess.onData((data) => { - if (!enqueueProcessEvent(session, processPid, { type: "output", data })) { - return; - } - runFork(drainProcessEvents(session, processPid)); - }); - const unsubscribeExit = ptyProcess.onExit((event) => { - if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) { - return; - } - runFork(drainProcessEvents(session, processPid)); - }); + const processPid = ptyProcess.pid; + const unsubscribeData = ptyProcess.onData((data) => { + if (!enqueueProcessEvent(session, processPid, { type: "output", data })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); + const unsubscribeExit = ptyProcess.onExit((event) => { + if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); - yield* modifyManagerState((state) => { - session.process = ptyProcess; - session.pid = processPid; - session.status = "running"; - session.updatedAt = new Date().toISOString(); - session.unsubscribeData = unsubscribeData; - session.unsubscribeExit = unsubscribeExit; - return [undefined, state] as const; - }); + yield* modifyManagerState((state) => { + session.process = ptyProcess; + session.pid = processPid; + session.status = "running"; + session.updatedAt = new Date().toISOString(); + session.unsubscribeData = unsubscribeData; + session.unsubscribeExit = unsubscribeExit; + return [undefined, state] as const; + }); - yield* publishEvent({ - type: eventType, - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - snapshot: snapshot(session), - }); - }), + yield* publishEvent({ + type: eventType, + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + snapshot: snapshot(session), + }); + }), + ), + ), ); if (startResult._tag === "Success") { @@ -1562,6 +1581,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + worktreePath: input.worktreePath ?? null, status: "starting", pid: null, history, @@ -1595,6 +1615,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), cols, rows, ...(input.env ? { env: input.env } : {}), @@ -1614,6 +1635,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith if (liveSession.cwd !== input.cwd || runtimeEnvChanged) { yield* stopProcess(liveSession); liveSession.cwd = input.cwd; + liveSession.worktreePath = input.worktreePath ?? null; liveSession.runtimeEnv = nextRuntimeEnv; liveSession.history = ""; liveSession.pendingHistoryControlSequence = ""; @@ -1627,6 +1649,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith ); } else if (liveSession.status === "exited" || liveSession.status === "error") { liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.worktreePath = input.worktreePath ?? null; liveSession.history = ""; liveSession.pendingHistoryControlSequence = ""; liveSession.pendingProcessEvents = []; @@ -1646,6 +1669,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + worktreePath: liveSession.worktreePath, cols: targetCols, rows: targetRows, ...(input.env ? { env: input.env } : {}), @@ -1722,6 +1746,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith withThreadLock( input.threadId, Effect.gen(function* () { + yield* increment(terminalRestartsTotal, { scope: "thread" }); const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; yield* assertValidCwd(input.cwd); @@ -1735,6 +1760,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + worktreePath: input.worktreePath ?? null, status: "starting", pid: null, history: "", @@ -1764,6 +1790,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session = existingSession.value; yield* stopProcess(session); session.cwd = input.cwd; + session.worktreePath = input.worktreePath ?? null; session.runtimeEnv = normalizedRuntimeEnv(input.env); } @@ -1782,6 +1809,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: input.threadId, terminalId, cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), cols, rows, ...(input.env ? { env: input.env } : {}), diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts index bdfbc85cc5..ebe83e362b 100644 --- a/apps/server/src/terminal/Services/Manager.ts +++ b/apps/server/src/terminal/Services/Manager.ts @@ -37,6 +37,7 @@ export interface TerminalSessionState { threadId: string; terminalId: string; cwd: string; + worktreePath: string | null; status: TerminalSessionStatus; pid: number | null; history: string; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e467ea4454..33a0518611 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,5 +1,8 @@ -import { Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect"; +import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect"; import { + CommandId, + EventId, + type OrchestrationCommand, type GitActionProgressEvent, type GitManagerServiceError, OrchestrationDispatchCommandError, @@ -11,6 +14,7 @@ import { ProjectSearchEntriesError, ProjectWriteFileError, OrchestrationReplayEventsError, + ThreadId, type TerminalEvent, WS_METHODS, WsRpcGroup, @@ -28,6 +32,11 @@ import { Open, resolveAvailableEditors } from "./open"; import { normalizeDispatchCommand } from "./orchestration/Normalizer"; import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; +import { + observeRpcEffect, + observeRpcStream, + observeRpcStreamEffect, +} from "./observability/RpcInstrumentation"; import { ProviderRegistry } from "./provider/Services/ProviderRegistry"; import { ServerLifecycleEvents } from "./serverLifecycleEvents"; import { ServerRuntimeStartup } from "./serverRuntimeStartup"; @@ -36,6 +45,7 @@ import { TerminalManager } from "./terminal/Services/Manager"; import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries"; import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem"; import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths"; +import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner"; const WsRpcLayer = WsRpcGroup.toLayer( Effect.gen(function* () { @@ -54,6 +64,265 @@ const WsRpcLayer = WsRpcGroup.toLayer( const startup = yield* ServerRuntimeStartup; const workspaceEntries = yield* WorkspaceEntries; const workspaceFileSystem = yield* WorkspaceFileSystem; + const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; + + const serverCommandId = (tag: string) => + CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); + + const appendSetupScriptActivity = (input: { + readonly threadId: ThreadId; + readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed"; + readonly summary: string; + readonly createdAt: string; + readonly payload: Record; + readonly tone: "info" | "error"; + }) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("setup-script-activity"), + threadId: input.threadId, + activity: { + id: EventId.makeUnsafe(crypto.randomUUID()), + tone: input.tone, + kind: input.kind, + summary: input.summary, + payload: input.payload, + turnId: null, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); + + const toDispatchCommandError = (cause: unknown, fallbackMessage: string) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: cause instanceof Error ? cause.message : fallbackMessage, + cause, + }); + + const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause) => { + const error = Cause.squash(cause); + return Schema.is(OrchestrationDispatchCommandError)(error) + ? error + : new OrchestrationDispatchCommandError({ + message: + error instanceof Error ? error.message : "Failed to bootstrap thread turn start.", + cause, + }); + }; + + const dispatchBootstrapTurnStart = ( + command: Extract, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => + Effect.gen(function* () { + const bootstrap = command.bootstrap; + const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command; + let createdThread = false; + let targetProjectId = bootstrap?.createThread?.projectId; + let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd; + let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null; + + const cleanupCreatedThread = () => + createdThread + ? orchestrationEngine + .dispatch({ + type: "thread.delete", + commandId: serverCommandId("bootstrap-thread-delete"), + threadId: command.threadId, + }) + .pipe(Effect.ignoreCause({ log: true })) + : Effect.void; + + const recordSetupScriptLaunchFailure = (input: { + readonly error: unknown; + readonly requestedAt: string; + readonly worktreePath: string; + }) => { + const detail = + input.error instanceof Error ? input.error.message : "Unknown setup failure."; + return appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.failed", + summary: "Setup script failed to start", + createdAt: input.requestedAt, + payload: { + detail, + worktreePath: input.worktreePath, + }, + tone: "error", + }).pipe( + Effect.ignoreCause({ log: false }), + Effect.flatMap(() => + Effect.logWarning("bootstrap turn start failed to launch setup script", { + threadId: command.threadId, + worktreePath: input.worktreePath, + detail, + }), + ), + ); + }; + + const recordSetupScriptStarted = (input: { + readonly requestedAt: string; + readonly worktreePath: string; + readonly scriptId: string; + readonly scriptName: string; + readonly terminalId: string; + }) => { + const payload = { + scriptId: input.scriptId, + scriptName: input.scriptName, + terminalId: input.terminalId, + worktreePath: input.worktreePath, + }; + return Effect.all([ + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.requested", + summary: "Starting setup script", + createdAt: input.requestedAt, + payload, + tone: "info", + }), + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.started", + summary: "Setup script started", + createdAt: new Date().toISOString(), + payload, + tone: "info", + }), + ]).pipe( + Effect.asVoid, + Effect.catch((error) => + Effect.logWarning( + "bootstrap turn start launched setup script but failed to record setup activity", + { + threadId: command.threadId, + worktreePath: input.worktreePath, + scriptId: input.scriptId, + terminalId: input.terminalId, + detail: + error instanceof Error + ? error.message + : "Unknown setup activity dispatch failure.", + }, + ), + ), + ); + }; + + const runSetupProgram = () => + bootstrap?.runSetupScript && targetWorktreePath + ? (() => { + const worktreePath = targetWorktreePath; + const requestedAt = new Date().toISOString(); + return projectSetupScriptRunner + .runForThread({ + threadId: command.threadId, + ...(targetProjectId ? { projectId: targetProjectId } : {}), + ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}), + worktreePath, + }) + .pipe( + Effect.matchEffect({ + onFailure: (error) => + recordSetupScriptLaunchFailure({ + error, + requestedAt, + worktreePath, + }), + onSuccess: (setupResult) => { + if (setupResult.status !== "started") { + return Effect.void; + } + return recordSetupScriptStarted({ + requestedAt, + worktreePath, + scriptId: setupResult.scriptId, + scriptName: setupResult.scriptName, + terminalId: setupResult.terminalId, + }); + }, + }), + ); + })() + : Effect.void; + + const bootstrapProgram = Effect.gen(function* () { + if (bootstrap?.createThread) { + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: serverCommandId("bootstrap-thread-create"), + threadId: command.threadId, + projectId: bootstrap.createThread.projectId, + title: bootstrap.createThread.title, + modelSelection: bootstrap.createThread.modelSelection, + runtimeMode: bootstrap.createThread.runtimeMode, + interactionMode: bootstrap.createThread.interactionMode, + branch: bootstrap.createThread.branch, + worktreePath: bootstrap.createThread.worktreePath, + createdAt: bootstrap.createThread.createdAt, + }); + createdThread = true; + } + + if (bootstrap?.prepareWorktree) { + const worktree = yield* git.createWorktree({ + cwd: bootstrap.prepareWorktree.projectCwd, + branch: bootstrap.prepareWorktree.baseBranch, + newBranch: bootstrap.prepareWorktree.branch, + path: null, + }); + targetWorktreePath = worktree.worktree.path; + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("bootstrap-thread-meta-update"), + threadId: command.threadId, + branch: worktree.worktree.branch, + worktreePath: targetWorktreePath, + }); + } + + yield* runSetupProgram(); + + return yield* orchestrationEngine.dispatch(finalTurnStartCommand); + }); + + return yield* bootstrapProgram.pipe( + Effect.catchCause((cause) => { + const dispatchError = toBootstrapDispatchCommandCauseError(cause); + if (Cause.hasInterruptsOnly(cause)) { + return Effect.fail(dispatchError); + } + return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError))); + }), + ); + }); + + const dispatchNormalizedCommand = ( + normalizedCommand: OrchestrationCommand, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => { + const dispatchEffect = + normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap + ? dispatchBootstrapTurnStart(normalizedCommand) + : orchestrationEngine + .dispatch(normalizedCommand) + .pipe( + Effect.mapError((cause) => + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + + return startup + .enqueueCommand(dispatchEffect) + .pipe( + Effect.mapError((cause) => + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + }; const loadServerConfig = Effect.gen(function* () { const keybindingsConfig = yield* keybindings.loadConfigState; @@ -67,85 +336,112 @@ const WsRpcLayer = WsRpcGroup.toLayer( issues: keybindingsConfig.issues, providers, availableEditors: resolveAvailableEditors(), + observability: { + logsDirectoryPath: config.logsDir, + localTracingEnabled: true, + ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}), + otlpTracesEnabled: config.otlpTracesUrl !== undefined, + ...(config.otlpMetricsUrl !== undefined ? { otlpMetricsUrl: config.otlpMetricsUrl } : {}), + otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, + }, settings, }; }); return WsRpcGroup.of({ [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) => - projectionSnapshotQuery.getSnapshot().pipe( - Effect.mapError( - (cause) => - new OrchestrationGetSnapshotError({ - message: "Failed to load orchestration snapshot", - cause, - }), - ), - ), - [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => - Effect.gen(function* () { - const normalizedCommand = yield* normalizeDispatchCommand(command); - const result = yield* startup.enqueueCommand( - orchestrationEngine.dispatch(normalizedCommand), - ); - if (normalizedCommand.type === "thread.archive") { - yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( - Effect.catch((error) => - Effect.logWarning("failed to close thread terminals after archive", { - threadId: normalizedCommand.threadId, - error: error.message, - }), - ), - ); - } - return result; - }).pipe( - Effect.mapError((cause) => - Schema.is(OrchestrationDispatchCommandError)(cause) - ? cause - : new OrchestrationDispatchCommandError({ - message: "Failed to dispatch orchestration command", + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getSnapshot, + projectionSnapshotQuery.getSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationGetSnapshotError({ + message: "Failed to load orchestration snapshot", cause, }), + ), ), + { "rpc.aggregate": "orchestration" }, + ), + [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.dispatchCommand, + Effect.gen(function* () { + const normalizedCommand = yield* normalizeDispatchCommand(command); + const result = yield* dispatchNormalizedCommand(normalizedCommand); + if (normalizedCommand.type === "thread.archive") { + yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to close thread terminals after archive", { + threadId: normalizedCommand.threadId, + error: error.message, + }), + ), + ); + } + return result; + }).pipe( + Effect.mapError((cause) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: "Failed to dispatch orchestration command", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, ), [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) => - checkpointDiffQuery.getTurnDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetTurnDiffError({ - message: "Failed to load turn diff", - cause, - }), + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getTurnDiff, + checkpointDiffQuery.getTurnDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetTurnDiffError({ + message: "Failed to load turn diff", + cause, + }), + ), ), + { "rpc.aggregate": "orchestration" }, ), [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) => - checkpointDiffQuery.getFullThreadDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetFullThreadDiffError({ - message: "Failed to load full thread diff", - cause, - }), + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getFullThreadDiff, + checkpointDiffQuery.getFullThreadDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetFullThreadDiffError({ + message: "Failed to load full thread diff", + cause, + }), + ), ), + { "rpc.aggregate": "orchestration" }, ), [ORCHESTRATION_WS_METHODS.replayEvents]: (input) => - Stream.runCollect( - orchestrationEngine.readEvents( - clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }), - ), - ).pipe( - Effect.map((events) => Array.from(events)), - Effect.mapError( - (cause) => - new OrchestrationReplayEventsError({ - message: "Failed to replay orchestration events", - cause, - }), + observeRpcEffect( + ORCHESTRATION_WS_METHODS.replayEvents, + Stream.runCollect( + orchestrationEngine.readEvents( + clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }), + ), + ).pipe( + Effect.map((events) => Array.from(events)), + Effect.mapError( + (cause) => + new OrchestrationReplayEventsError({ + message: "Failed to replay orchestration events", + cause, + }), + ), ), + { "rpc.aggregate": "orchestration" }, ), [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) => - Stream.unwrap( + observeRpcStreamEffect( + WS_METHODS.subscribeOrchestrationDomainEvents, Effect.gen(function* () { const snapshot = yield* orchestrationEngine.getReadModel(); const fromSequenceExclusive = snapshot.snapshotSequence; @@ -200,82 +496,167 @@ const WsRpcLayer = WsRpcGroup.toLayer( Stream.flatMap((events) => Stream.fromIterable(events)), ); }), + { "rpc.aggregate": "orchestration" }, ), - [WS_METHODS.serverGetConfig]: (_input) => loadServerConfig, - [WS_METHODS.serverRefreshProviders]: (_input) => - providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), - [WS_METHODS.serverUpsertKeybinding]: (rule) => - Effect.gen(function* () { - const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); - return { keybindings: keybindingsConfig, issues: [] }; + [WS_METHODS.serverGetConfig]: (_input) => + observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { + "rpc.aggregate": "server", + }), + [WS_METHODS.serverRefreshProviders]: (_input) => + observeRpcEffect( + WS_METHODS.serverRefreshProviders, + providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverUpsertKeybinding]: (rule) => + observeRpcEffect( + WS_METHODS.serverUpsertKeybinding, + Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); + return { keybindings: keybindingsConfig, issues: [] }; + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverGetSettings]: (_input) => + observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, { + "rpc.aggregate": "server", + }), + [WS_METHODS.serverUpdateSettings]: ({ patch }) => + observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), { + "rpc.aggregate": "server", }), - [WS_METHODS.serverGetSettings]: (_input) => serverSettings.getSettings, - [WS_METHODS.serverUpdateSettings]: ({ patch }) => serverSettings.updateSettings(patch), [WS_METHODS.projectsSearchEntries]: (input) => - workspaceEntries.search(input).pipe( - Effect.mapError( - (cause) => - new ProjectSearchEntriesError({ - message: `Failed to search workspace entries: ${cause.detail}`, - cause, - }), + observeRpcEffect( + WS_METHODS.projectsSearchEntries, + workspaceEntries.search(input).pipe( + Effect.mapError( + (cause) => + new ProjectSearchEntriesError({ + message: `Failed to search workspace entries: ${cause.detail}`, + cause, + }), + ), ), + { "rpc.aggregate": "workspace" }, ), [WS_METHODS.projectsWriteFile]: (input) => - workspaceFileSystem.writeFile(input).pipe( - Effect.mapError((cause) => { - const message = Schema.is(WorkspacePathOutsideRootError)(cause) - ? "Workspace file path must stay within the project root." - : "Failed to write workspace file"; - return new ProjectWriteFileError({ - message, - cause, - }); - }), - ), - [WS_METHODS.shellOpenInEditor]: (input) => open.openInEditor(input), - [WS_METHODS.gitStatus]: (input) => gitManager.status(input), - [WS_METHODS.gitPull]: (input) => git.pullCurrentBranch(input.cwd), - [WS_METHODS.gitRunStackedAction]: (input) => - Stream.callback((queue) => - gitManager - .runStackedAction(input, { - actionId: input.actionId, - progressReporter: { - publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid), - }, - }) - .pipe( - Effect.matchCauseEffect({ - onFailure: (cause) => Queue.failCause(queue, cause), - onSuccess: () => Queue.end(queue).pipe(Effect.asVoid), - }), - ), - ), - [WS_METHODS.gitResolvePullRequest]: (input) => gitManager.resolvePullRequest(input), - [WS_METHODS.gitPreparePullRequestThread]: (input) => - gitManager.preparePullRequestThread(input), - [WS_METHODS.gitListBranches]: (input) => git.listBranches(input), - [WS_METHODS.gitCreateWorktree]: (input) => git.createWorktree(input), - [WS_METHODS.gitRemoveWorktree]: (input) => git.removeWorktree(input), - [WS_METHODS.gitCreateBranch]: (input) => git.createBranch(input), - [WS_METHODS.gitCheckout]: (input) => Effect.scoped(git.checkoutBranch(input)), - [WS_METHODS.gitInit]: (input) => git.initRepo(input), - [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input), - [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input), - [WS_METHODS.terminalResize]: (input) => terminalManager.resize(input), - [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), - [WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input), - [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), - [WS_METHODS.subscribeTerminalEvents]: (_input) => - Stream.callback((queue) => - Effect.acquireRelease( - terminalManager.subscribe((event) => Queue.offer(queue, event)), - (unsubscribe) => Effect.sync(unsubscribe), + observeRpcEffect( + WS_METHODS.projectsWriteFile, + workspaceFileSystem.writeFile(input).pipe( + Effect.mapError((cause) => { + const message = Schema.is(WorkspacePathOutsideRootError)(cause) + ? "Workspace file path must stay within the project root." + : "Failed to write workspace file"; + return new ProjectWriteFileError({ + message, + cause, + }); + }), ), + { "rpc.aggregate": "workspace" }, + ), + [WS_METHODS.shellOpenInEditor]: (input) => + observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), { + "rpc.aggregate": "workspace", + }), + [WS_METHODS.gitStatus]: (input) => + observeRpcEffect(WS_METHODS.gitStatus, gitManager.status(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitPull]: (input) => + observeRpcEffect(WS_METHODS.gitPull, git.pullCurrentBranch(input.cwd), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitRunStackedAction]: (input) => + observeRpcStream( + WS_METHODS.gitRunStackedAction, + Stream.callback((queue) => + gitManager + .runStackedAction(input, { + actionId: input.actionId, + progressReporter: { + publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid), + }, + }) + .pipe( + Effect.matchCauseEffect({ + onFailure: (cause) => Queue.failCause(queue, cause), + onSuccess: () => Queue.end(queue).pipe(Effect.asVoid), + }), + ), + ), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitResolvePullRequest]: (input) => + observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitPreparePullRequestThread]: (input) => + observeRpcEffect( + WS_METHODS.gitPreparePullRequestThread, + gitManager.preparePullRequestThread(input), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitListBranches]: (input) => + observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCreateWorktree]: (input) => + observeRpcEffect(WS_METHODS.gitCreateWorktree, git.createWorktree(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitRemoveWorktree]: (input) => + observeRpcEffect(WS_METHODS.gitRemoveWorktree, git.removeWorktree(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCreateBranch]: (input) => + observeRpcEffect(WS_METHODS.gitCreateBranch, git.createBranch(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCheckout]: (input) => + observeRpcEffect(WS_METHODS.gitCheckout, Effect.scoped(git.checkoutBranch(input)), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitInit]: (input) => + observeRpcEffect(WS_METHODS.gitInit, git.initRepo(input), { "rpc.aggregate": "git" }), + [WS_METHODS.terminalOpen]: (input) => + observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalWrite]: (input) => + observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalResize]: (input) => + observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClear]: (input) => + observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalRestart]: (input) => + observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClose]: (input) => + observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.subscribeTerminalEvents]: (_input) => + observeRpcStream( + WS_METHODS.subscribeTerminalEvents, + Stream.callback((queue) => + Effect.acquireRelease( + terminalManager.subscribe((event) => Queue.offer(queue, event)), + (unsubscribe) => Effect.sync(unsubscribe), + ), + ), + { "rpc.aggregate": "terminal" }, ), [WS_METHODS.subscribeServerConfig]: (_input) => - Stream.unwrap( + observeRpcStreamEffect( + WS_METHODS.subscribeServerConfig, Effect.gen(function* () { const keybindingsUpdates = keybindings.streamChanges.pipe( Stream.map((event) => ({ @@ -310,9 +691,11 @@ const WsRpcLayer = WsRpcGroup.toLayer( Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)), ); }), + { "rpc.aggregate": "server" }, ), [WS_METHODS.subscribeServerLifecycle]: (_input) => - Stream.unwrap( + observeRpcStreamEffect( + WS_METHODS.subscribeServerLifecycle, Effect.gen(function* () { const snapshot = yield* lifecycleEvents.snapshot; const snapshotEvents = Array.from(snapshot.events).toSorted( @@ -323,6 +706,7 @@ const WsRpcLayer = WsRpcGroup.toLayer( ); return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents); }), + { "rpc.aggregate": "server" }, ), }); }), @@ -330,9 +714,13 @@ const WsRpcLayer = WsRpcGroup.toLayer( export const websocketRpcRouteLayer = Layer.unwrap( Effect.gen(function* () { - const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup).pipe( - Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson)), - ); + const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, { + spanPrefix: "ws.rpc", + spanAttributes: { + "rpc.transport": "websocket", + "rpc.system": "effect-rpc", + }, + }).pipe(Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson))); return HttpRouter.add( "GET", "/ws", diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 85ef2a40a3..bf79c9c2cc 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -33,6 +33,7 @@ import { isMacPlatform } from "../lib/utils"; import { __resetNativeApiForTests } from "../nativeApi"; import { getRouter } from "../router"; import { useStore } from "../store"; +import { useTerminalStateStore } from "../terminalStateStore"; import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness"; import { estimateTimelineMessageHeight } from "./timelineHeight"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; @@ -135,6 +136,12 @@ function createBaseServerConfig(): ServerConfig { }, ], availableEditors: [], + observability: { + logsDirectoryPath: "/repo/project/.t3/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, settings: { ...DEFAULT_SERVER_SETTINGS, ...DEFAULT_CLIENT_SETTINGS, @@ -676,6 +683,12 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown { threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID, terminalId: typeof body.terminalId === "string" ? body.terminalId : "default", cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project", + worktreePath: + typeof body.worktreePath === "string" + ? body.worktreePath + : body.worktreePath === null + ? null + : null, status: "running", pid: 123, history: "", @@ -1157,6 +1170,13 @@ describe("ChatView timeline estimator parity (full app)", () => { sidebarThreadSummaryById: {}, bootstrapComplete: false, }); + useTerminalStateStore.persist.clearStorage(); + useTerminalStateStore.setState({ + terminalStateByThreadId: {}, + terminalLaunchContextByThreadId: {}, + terminalEventEntriesByKey: {}, + nextTerminalEventId: 1, + }); }); afterEach(() => { @@ -1380,6 +1400,74 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("does not leak a server worktree path into drawer runtime env when launch context clears it", async () => { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-launch-context-target" as MessageId, + targetText: "launch context worktree override", + }); + const targetThread = snapshot.threads.find((thread) => thread.id === THREAD_ID); + if (targetThread) { + Object.assign(targetThread, { + branch: "feature/branch", + worktreePath: "/repo/worktrees/feature-branch", + }); + } + + useTerminalStateStore.setState({ + terminalStateByThreadId: { + [THREAD_ID]: { + terminalOpen: true, + terminalHeight: 280, + terminalIds: ["default"], + runningTerminalIds: [], + activeTerminalId: "default", + terminalGroups: [{ id: "group-default", terminalIds: ["default"] }], + activeTerminalGroupId: "group-default", + }, + }, + terminalLaunchContextByThreadId: { + [THREAD_ID]: { + cwd: "/repo/project", + worktreePath: null, + }, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot, + }); + + try { + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.terminalOpen, + ) as + | { + _tag: string; + cwd?: string; + worktreePath?: string | null; + env?: Record; + } + | undefined; + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.terminalOpen, + cwd: "/repo/project", + worktreePath: null, + env: { + T3CODE_PROJECT_ROOT: "/repo/project", + }, + }); + expect(openRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined(); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => { setDraftThreadWithoutWorktree(); @@ -1721,7 +1809,7 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); - it("runs setup scripts after preparing a pull request worktree thread", async () => { + it("lets the server own setup after preparing a pull request worktree thread", async () => { useComposerDraftStore.setState({ draftThreadsByThreadId: { [THREAD_ID]: { @@ -1826,45 +1914,188 @@ describe("ChatView timeline estimator parity (full app)", () => { cwd: "/repo/project", reference: "1359", mode: "worktree", + threadId: THREAD_ID, }); }, { timeout: 8_000, interval: 16 }, ); + expect( + wsRequests.some( + (request) => + request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r", + ), + ).toBe(false); + } finally { + await mounted.cleanup(); + } + }); + + it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => { + useTerminalStateStore.setState({ + terminalStateByThreadId: {}, + }); + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + envMode: "worktree", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return { + sequence: fixture.snapshot.snapshotSequence + 1, + }; + } + return undefined; + }, + }); + + try { + useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it"); + await waitForLayout(); + + const sendButton = await waitForSendButton(); + expect(sendButton.disabled).toBe(false); + sendButton.click(); + await vi.waitFor( () => { - const openRequest = wsRequests.find( - (request) => - request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359", - ); - expect(openRequest).toMatchObject({ - _tag: WS_METHODS.terminalOpen, - threadId: expect.any(String), - cwd: "/repo/worktrees/pr-1359", - env: { - T3CODE_PROJECT_ROOT: "/repo/project", - T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359", + const dispatchRequest = wsRequests.find( + (request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand, + ) as + | { + _tag: string; + type?: string; + bootstrap?: { + createThread?: { projectId?: string }; + prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string }; + runSetupScript?: boolean; + }; + } + | undefined; + expect(dispatchRequest).toMatchObject({ + _tag: ORCHESTRATION_WS_METHODS.dispatchCommand, + type: "thread.turn.start", + bootstrap: { + createThread: { + projectId: PROJECT_ID, + }, + prepareWorktree: { + projectCwd: "/repo/project", + baseBranch: "main", + branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/), + }, + runSetupScript: true, }, }); }, { timeout: 8_000, interval: 16 }, ); + expect(wsRequests.some((request) => request._tag === WS_METHODS.gitCreateWorktree)).toBe( + false, + ); + expect( + wsRequests.some( + (request) => + request._tag === WS_METHODS.terminalWrite && + request.threadId === THREAD_ID && + request.data === "bun install\r", + ), + ).toBe(false); + } finally { + await mounted.cleanup(); + } + }); + + it("shows the send state once bootstrap dispatch is in flight", async () => { + useTerminalStateStore.setState({ + terminalStateByThreadId: {}, + }); + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + envMode: "worktree", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + let resolveDispatch!: (value: { sequence: number }) => void; + const dispatchPromise = new Promise<{ sequence: number }>((resolve) => { + resolveDispatch = resolve; + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: withProjectScripts(createDraftOnlySnapshot(), [ + { + id: "setup", + name: "Setup", + command: "bun install", + icon: "configure", + runOnWorktreeCreate: true, + }, + ]), + resolveRpc: (body) => { + if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) { + return dispatchPromise; + } + return undefined; + }, + }); + + try { + useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it"); + await waitForLayout(); + + const sendButton = await waitForSendButton(); + expect(sendButton.disabled).toBe(false); + sendButton.click(); + await vi.waitFor( () => { - const writeRequest = wsRequests.find( - (request) => - request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r", - ); - expect(writeRequest).toMatchObject({ - _tag: WS_METHODS.terminalWrite, - threadId: expect.any(String), - data: "bun install\r", - }); + expect( + wsRequests.some((request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand), + ).toBe(true); + expect(document.querySelector('button[aria-label="Sending"]')).toBeTruthy(); + expect(document.querySelector('button[aria-label="Preparing worktree"]')).toBeNull(); }, { timeout: 8_000, interval: 16 }, ); } finally { + resolveDispatch({ sequence: fixture.snapshot.snapshotSequence + 1 }); await mounted.cleanup(); } }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 436af61404..55fa361fe7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -21,12 +21,13 @@ import { TerminalOpenInput, } from "@t3tools/contracts"; import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model"; +import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; import { truncate } from "@t3tools/shared/String"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useQuery } from "@tanstack/react-query"; import { useDebouncedValue } from "@tanstack/react-pacer"; import { useNavigate, useSearch } from "@tanstack/react-router"; -import { gitCreateWorktreeMutationOptions, gitStatusQueryOptions } from "~/lib/gitReactQuery"; +import { gitStatusQueryOptions } from "~/lib/gitReactQuery"; import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery"; import { isElectron } from "../env"; import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"; @@ -52,7 +53,6 @@ import { deriveWorkLogEntries, hasActionableProposedPlan, hasToolActivityForTurn, - isSessionActivelyRunningTurn, isLatestTurnSettled, formatElapsed, } from "../session-logic"; @@ -112,10 +112,7 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl"; import { commandForProjectScript, nextProjectScriptId, - projectScriptCwd, - projectScriptRuntimeEnv, projectScriptIdFromCommand, - setupProjectScript, } from "~/projectScripts"; import { SidebarTrigger } from "./ui/sidebar"; import { newCommandId, newMessageId, newThreadId } from "~/lib/utils"; @@ -200,6 +197,7 @@ import { useServerConfig, useServerKeybindings, } from "~/rpc/serverState"; +import { sanitizeThreadErrorMessage } from "~/rpc/transportError"; const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; @@ -352,12 +350,14 @@ interface ChatViewProps { threadId: ThreadId; } -interface PendingPullRequestSetupRequest { +interface TerminalLaunchContext { threadId: ThreadId; - worktreePath: string; - scriptId: string; + cwd: string; + worktreePath: string | null; } +type PersistentTerminalLaunchContext = Pick; + function useLocalDispatchState(input: { activeThread: Thread | undefined; activeLatestTurn: Thread["latestTurn"] | null; @@ -428,6 +428,7 @@ function useLocalDispatchState(input: { interface PersistentThreadTerminalDrawerProps { threadId: ThreadId; visible: boolean; + launchContext: PersistentTerminalLaunchContext | null; focusRequestId: number; splitShortcutLabel: string | undefined; newShortcutLabel: string | undefined; @@ -438,6 +439,7 @@ interface PersistentThreadTerminalDrawerProps { function PersistentThreadTerminalDrawer({ threadId, visible, + launchContext, focusRequestId, splitShortcutLabel, newShortcutLabel, @@ -465,25 +467,32 @@ function PersistentThreadTerminalDrawer({ const storeCloseTerminal = useTerminalStateStore((state) => state.closeTerminal); const [localFocusRequestId, setLocalFocusRequestId] = useState(0); const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; + const effectiveWorktreePath = useMemo(() => { + if (launchContext !== null) { + return launchContext.worktreePath; + } + return worktreePath; + }, [launchContext, worktreePath]); const cwd = useMemo( () => - project + launchContext?.cwd ?? + (project ? projectScriptCwd({ project: { cwd: project.cwd }, - worktreePath, + worktreePath: effectiveWorktreePath, }) - : null, - [project, worktreePath], + : null), + [effectiveWorktreePath, launchContext?.cwd, project], ); const runtimeEnv = useMemo( () => project ? projectScriptRuntimeEnv({ project: { cwd: project.cwd }, - worktreePath, + worktreePath: effectiveWorktreePath, }) : {}, - [project, worktreePath], + [effectiveWorktreePath, project], ); const bumpFocusRequestId = useCallback(() => { @@ -566,6 +575,7 @@ function PersistentThreadTerminalDrawer({ createThreadSelector(threadId), [threadId])); const setStoreThreadError = useStore((store) => store.setError); - const setStoreThreadBranch = useStore((store) => store.setThreadBranch); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); const activeThreadLastVisitedAt = useUiStateStore( (store) => store.threadLastVisitedAtById[threadId], @@ -607,8 +616,6 @@ export default function ChatView({ threadId }: ChatViewProps) { select: (params) => parseDiffRouteSearch(params), }); const { resolvedTheme } = useTheme(); - const queryClient = useQueryClient(); - const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient })); const composerDraft = useComposerThreadDraft(threadId); const prompt = composerDraft.prompt; const composerImages = composerDraft.images; @@ -699,8 +706,9 @@ export default function ChatView({ threadId }: ChatViewProps) { const [composerHighlightedItemId, setComposerHighlightedItemId] = useState(null); const [pullRequestDialogState, setPullRequestDialogState] = useState(null); - const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] = - useState(null); + const [terminalLaunchContext, setTerminalLaunchContext] = useState( + null, + ); const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState< Record >({}); @@ -767,6 +775,12 @@ export default function ChatView({ threadId }: ChatViewProps) { const storeSetActiveTerminal = useTerminalStateStore((s) => s.setActiveTerminal); const storeCloseTerminal = useTerminalStateStore((s) => s.closeTerminal); const serverThreadIds = useStore((state) => state.threadIds); + const storeServerTerminalLaunchContext = useTerminalStateStore( + (s) => s.terminalLaunchContextByThreadId[threadId] ?? null, + ); + const storeClearTerminalLaunchContext = useTerminalStateStore( + (s) => s.clearTerminalLaunchContext, + ); const draftThreadsByThreadId = useComposerDraftStore((store) => store.draftThreadsByThreadId); const draftThreadIds = useMemo( () => Object.keys(draftThreadsByThreadId) as ThreadId[], @@ -970,24 +984,13 @@ export default function ChatView({ threadId }: ChatViewProps) { const handlePreparedPullRequestThread = useCallback( async (input: { branch: string; worktreePath: string | null }) => { - const targetThreadId = await openOrReuseProjectDraftThread({ + await openOrReuseProjectDraftThread({ branch: input.branch, worktreePath: input.worktreePath, envMode: input.worktreePath ? "worktree" : "local", }); - const setupScript = - input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null; - if (targetThreadId && input.worktreePath && setupScript) { - setPendingPullRequestSetupRequest({ - threadId: targetThreadId, - worktreePath: input.worktreePath, - scriptId: setupScript.id, - }); - } else { - setPendingPullRequestSetupRequest(null); - } }, - [activeProject, openOrReuseProjectDraftThread], + [openOrReuseProjectDraftThread], ); useEffect(() => { @@ -1148,11 +1151,7 @@ export default function ChatView({ threadId }: ChatViewProps) { activePendingUserInput: activePendingUserInput?.requestId ?? null, threadError: activeThread?.error, }); - const isTurnRunning = isSessionActivelyRunningTurn( - activeLatestTurn, - activeThread?.session ?? null, - ); - const isWorking = isTurnRunning || isSendBusy || isConnecting || isRevertingCheckpoint; + const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; const nowIso = new Date(nowTick).toISOString(); const activeWorkStartedAt = deriveActiveWorkStartedAt( activeLatestTurn, @@ -1169,7 +1168,7 @@ export default function ChatView({ threadId }: ChatViewProps) { if (activePendingProgress) { return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`; } - if (isTurnRunning) { + if (phase === "running") { return "running"; } if (showPlanFollowUpPrompt) { @@ -1183,7 +1182,7 @@ export default function ChatView({ threadId }: ChatViewProps) { isConnecting, isPreparingWorktree, isSendBusy, - isTurnRunning, + phase, prompt, showPlanFollowUpPrompt, ]); @@ -1552,6 +1551,12 @@ export default function ChatView({ threadId }: ChatViewProps) { () => providerStatuses.find((status) => status.provider === selectedProvider) ?? null, [selectedProvider, providerStatuses], ); + const activeProjectCwd = activeProject?.cwd ?? null; + const activeThreadWorktreePath = activeThread?.worktreePath ?? null; + const activeTerminalLaunchContext = + terminalLaunchContext?.threadId === activeThreadId + ? terminalLaunchContext + : (storeServerTerminalLaunchContext ?? null); // Default true while loading to avoid toolbar flicker. const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const terminalShortcutLabelOptions = useMemo( @@ -1622,17 +1627,18 @@ export default function ChatView({ threadId }: ChatViewProps) { const setThreadError = useCallback( (targetThreadId: ThreadId | null, error: string | null) => { if (!targetThreadId) return; + const nextError = sanitizeThreadErrorMessage(error); if (useStore.getState().threadShellById[targetThreadId] !== undefined) { - setStoreThreadError(targetThreadId, error); + setStoreThreadError(targetThreadId, nextError); return; } setLocalDraftErrorsByThreadId((existing) => { - if ((existing[targetThreadId] ?? null) === error) { + if ((existing[targetThreadId] ?? null) === nextError) { return existing; } return { ...existing, - [targetThreadId]: error, + [targetThreadId]: nextError, }; }); }, @@ -1772,7 +1778,13 @@ export default function ChatView({ threadId }: ChatViewProps) { const targetTerminalId = shouldCreateNewTerminal ? `terminal-${randomUUID()}` : baseTerminalId; + const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null; + setTerminalLaunchContext({ + threadId: activeThreadId, + cwd: targetCwd, + worktreePath: targetWorktreePath, + }); setTerminalOpen(true); if (shouldCreateNewTerminal) { storeNewTerminal(activeThreadId, targetTerminalId); @@ -1785,7 +1797,7 @@ export default function ChatView({ threadId }: ChatViewProps) { project: { cwd: activeProject.cwd, }, - worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null, + worktreePath: targetWorktreePath, ...(options?.env ? { extraEnv: options.env } : {}), }); const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal @@ -1793,6 +1805,7 @@ export default function ChatView({ threadId }: ChatViewProps) { threadId: activeThreadId, terminalId: targetTerminalId, cwd: targetCwd, + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), env: runtimeEnv, cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS, @@ -1801,6 +1814,7 @@ export default function ChatView({ threadId }: ChatViewProps) { threadId: activeThreadId, terminalId: targetTerminalId, cwd: targetCwd, + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), env: runtimeEnv, }; @@ -1834,44 +1848,6 @@ export default function ChatView({ threadId }: ChatViewProps) { ], ); - useEffect(() => { - if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) { - return; - } - if (pendingPullRequestSetupRequest.threadId !== activeThreadId) { - return; - } - if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) { - return; - } - - const setupScript = - activeProject.scripts.find( - (script) => script.id === pendingPullRequestSetupRequest.scriptId, - ) ?? null; - setPendingPullRequestSetupRequest(null); - if (!setupScript) { - return; - } - - void runProjectScript(setupScript, { - cwd: pendingPullRequestSetupRequest.worktreePath, - worktreePath: pendingPullRequestSetupRequest.worktreePath, - rememberAsLastInvoked: false, - }).catch((error) => { - toastManager.add({ - type: "error", - title: "Failed to run setup script.", - description: error instanceof Error ? error.message : "An error occurred.", - }); - }); - }, [ - activeProject, - activeThread, - activeThreadId, - pendingPullRequestSetupRequest, - runProjectScript, - ]); const persistProjectScripts = useCallback( async (input: { projectId: ProjectId; @@ -2343,10 +2319,10 @@ export default function ChatView({ threadId }: ChatViewProps) { scheduleStickToBottom(); }, [messageCount, scheduleStickToBottom]); useEffect(() => { - if (!isTurnRunning) return; + if (phase !== "running") return; if (!shouldAutoScrollRef.current) return; scheduleStickToBottom(); - }, [isTurnRunning, scheduleStickToBottom, timelineEntries]); + }, [phase, scheduleStickToBottom, timelineEntries]); useEffect(() => { setExpandedWorkGroups({}); @@ -2565,14 +2541,82 @@ export default function ChatView({ threadId }: ChatViewProps) { : "local"; useEffect(() => { - if (!isTurnRunning) return; + if (!activeThreadId) { + setTerminalLaunchContext(null); + storeClearTerminalLaunchContext(threadId); + return; + } + setTerminalLaunchContext((current) => { + if (!current) return current; + if (current.threadId === activeThreadId) return current; + return null; + }); + }, [activeThreadId, storeClearTerminalLaunchContext, threadId]); + + useEffect(() => { + if (!activeThreadId || !activeProjectCwd) { + return; + } + setTerminalLaunchContext((current) => { + if (!current || current.threadId !== activeThreadId) { + return current; + } + const settledCwd = projectScriptCwd({ + project: { cwd: activeProjectCwd }, + worktreePath: activeThreadWorktreePath, + }); + if ( + settledCwd === current.cwd && + (activeThreadWorktreePath ?? null) === current.worktreePath + ) { + storeClearTerminalLaunchContext(activeThreadId); + return null; + } + return current; + }); + }, [activeProjectCwd, activeThreadId, activeThreadWorktreePath, storeClearTerminalLaunchContext]); + + useEffect(() => { + if (!activeThreadId || !activeProjectCwd || !storeServerTerminalLaunchContext) { + return; + } + const settledCwd = projectScriptCwd({ + project: { cwd: activeProjectCwd }, + worktreePath: activeThreadWorktreePath, + }); + if ( + settledCwd === storeServerTerminalLaunchContext.cwd && + (activeThreadWorktreePath ?? null) === storeServerTerminalLaunchContext.worktreePath + ) { + storeClearTerminalLaunchContext(activeThreadId); + } + }, [ + activeProjectCwd, + activeThreadId, + activeThreadWorktreePath, + storeClearTerminalLaunchContext, + storeServerTerminalLaunchContext, + ]); + + useEffect(() => { + if (terminalState.terminalOpen) { + return; + } + if (activeThreadId) { + storeClearTerminalLaunchContext(activeThreadId); + } + setTerminalLaunchContext((current) => (current?.threadId === activeThreadId ? null : current)); + }, [activeThreadId, storeClearTerminalLaunchContext, terminalState.terminalOpen]); + + useEffect(() => { + if (phase !== "running") return; const timer = window.setInterval(() => { setNowTick(Date.now()); }, 1000); return () => { window.clearInterval(timer); }; - }, [isTurnRunning]); + }, [phase]); useEffect(() => { if (!activeThreadId) return; @@ -2792,7 +2836,7 @@ export default function ChatView({ threadId }: ChatViewProps) { const api = readNativeApi(); if (!api || !activeThread || isRevertingCheckpoint) return; - if (isTurnRunning || isSendBusy || isConnecting) { + if (phase === "running" || isSendBusy || isConnecting) { setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); return; } @@ -2825,7 +2869,7 @@ export default function ChatView({ threadId }: ChatViewProps) { } setIsRevertingCheckpoint(false); }, - [activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, isTurnRunning, setThreadError], + [activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError], ); const onSend = async (e?: { preventDefault: () => void }) => { @@ -2978,36 +3022,8 @@ export default function ChatView({ threadId }: ChatViewProps) { setComposerCursor(0); setComposerTrigger(null); - let createdServerThreadForLocalDraft = false; let turnStartSucceeded = false; - let nextThreadBranch = activeThread.branch; - let nextThreadWorktreePath = activeThread.worktreePath; await (async () => { - // On first message: lock in branch + create worktree if needed. - if (baseBranchForWorktree) { - beginLocalDispatch({ preparingWorktree: true }); - const newBranch = buildTemporaryWorktreeBranchName(); - const result = await createWorktreeMutation.mutateAsync({ - cwd: activeProject.cwd, - branch: baseBranchForWorktree, - newBranch, - }); - nextThreadBranch = result.worktree.branch; - nextThreadWorktreePath = result.worktree.path; - if (isServerThread) { - await api.orchestration.dispatchCommand({ - type: "thread.meta.update", - commandId: newCommandId(), - threadId: threadIdForSend, - branch: result.worktree.branch, - worktreePath: result.worktree.path, - }); - // Keep local thread state in sync immediately so terminal drawer opens - // with the worktree cwd/env instead of briefly using the project root. - setStoreThreadBranch(threadIdForSend, result.worktree.branch, result.worktree.path); - } - } - let firstComposerImageName: string | null = null; if (composerImagesSnapshot.length > 0) { const firstComposerImage = composerImagesSnapshot[0]; @@ -3035,48 +3051,6 @@ export default function ChatView({ threadId }: ChatViewProps) { ...(selectedModelSelection.options ? { options: selectedModelSelection.options } : {}), }; - if (isLocalDraftThread) { - await api.orchestration.dispatchCommand({ - type: "thread.create", - commandId: newCommandId(), - threadId: threadIdForSend, - projectId: activeProject.id, - title, - modelSelection: threadCreateModelSelection, - runtimeMode, - interactionMode, - branch: nextThreadBranch, - worktreePath: nextThreadWorktreePath, - createdAt: activeThread.createdAt, - }); - createdServerThreadForLocalDraft = true; - } - - let setupScript: ProjectScript | null = null; - if (baseBranchForWorktree) { - setupScript = setupProjectScript(activeProject.scripts); - } - if (setupScript) { - let shouldRunSetupScript = false; - if (isServerThread) { - shouldRunSetupScript = true; - } else { - if (createdServerThreadForLocalDraft) { - shouldRunSetupScript = true; - } - } - if (shouldRunSetupScript) { - const setupScriptOptions: Parameters[1] = { - worktreePath: nextThreadWorktreePath, - rememberAsLastInvoked: false, - }; - if (nextThreadWorktreePath) { - setupScriptOptions.cwd = nextThreadWorktreePath; - } - await runProjectScript(setupScript, setupScriptOptions); - } - } - // Auto-title from first message if (isFirstMessage && isServerThread) { await api.orchestration.dispatchCommand({ @@ -3097,8 +3071,37 @@ export default function ChatView({ threadId }: ChatViewProps) { }); } - beginLocalDispatch({ preparingWorktree: false }); const turnAttachments = await turnAttachmentsPromise; + const bootstrap = + isLocalDraftThread || baseBranchForWorktree + ? { + ...(isLocalDraftThread + ? { + createThread: { + projectId: activeProject.id, + title, + modelSelection: threadCreateModelSelection, + runtimeMode, + interactionMode, + branch: activeThread.branch, + worktreePath: activeThread.worktreePath, + createdAt: activeThread.createdAt, + }, + } + : {}), + ...(baseBranchForWorktree + ? { + prepareWorktree: { + projectCwd: activeProject.cwd, + baseBranch: baseBranchForWorktree, + branch: buildTemporaryWorktreeBranchName(), + }, + runSetupScript: true, + } + : {}), + } + : undefined; + beginLocalDispatch({ preparingWorktree: false }); await api.orchestration.dispatchCommand({ type: "thread.turn.start", commandId: newCommandId(), @@ -3113,19 +3116,11 @@ export default function ChatView({ threadId }: ChatViewProps) { titleSeed: title, runtimeMode, interactionMode, + ...(bootstrap ? { bootstrap } : {}), createdAt: messageCreatedAt, }); turnStartSucceeded = true; })().catch(async (err: unknown) => { - if (createdServerThreadForLocalDraft && !turnStartSucceeded) { - await api.orchestration - .dispatchCommand({ - type: "thread.delete", - commandId: newCommandId(), - threadId: threadIdForSend, - }) - .catch(() => undefined); - } if ( !turnStartSucceeded && promptRef.current.length === 0 && @@ -3187,14 +3182,14 @@ export default function ChatView({ threadId }: ChatViewProps) { createdAt: new Date().toISOString(), }) .catch((err: unknown) => { - setStoreThreadError( + setThreadError( activeThreadId, err instanceof Error ? err.message : "Failed to submit approval decision.", ); }); setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); }, - [activeThreadId, setStoreThreadError], + [activeThreadId, setThreadError], ); const onRespondToUserInput = useCallback( @@ -3215,14 +3210,14 @@ export default function ChatView({ threadId }: ChatViewProps) { createdAt: new Date().toISOString(), }) .catch((err: unknown) => { - setStoreThreadError( + setThreadError( activeThreadId, err instanceof Error ? err.message : "Failed to submit user input.", ); }); setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); }, - [activeThreadId, setStoreThreadError], + [activeThreadId, setThreadError], ); const setActivePendingUserInputQuestionIndex = useCallback( @@ -4414,7 +4409,7 @@ export default function ChatView({ threadId }: ChatViewProps) { } : null } - isRunning={isTurnRunning} + isRunning={phase === "running"} showPlanFollowUpPrompt={ pendingUserInputs.length === 0 && showPlanFollowUpPrompt } @@ -4450,6 +4445,7 @@ export default function ChatView({ threadId }: ChatViewProps) { { @@ -4489,6 +4485,9 @@ export default function ChatView({ threadId }: ChatViewProps) { key={mountedThreadId} threadId={mountedThreadId} visible={mountedThreadId === activeThreadId && terminalState.terminalOpen} + launchContext={ + mountedThreadId === activeThreadId ? (activeTerminalLaunchContext ?? null) : null + } focusRequestId={mountedThreadId === activeThreadId ? terminalFocusRequestId : 0} splitShortcutLabel={splitTerminalShortcutLabel ?? undefined} newShortcutLabel={newTerminalShortcutLabel ?? undefined} diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx index 3f4844af80..2e95b54e25 100644 --- a/apps/web/src/components/Icons.tsx +++ b/apps/web/src/components/Icons.tsx @@ -310,6 +310,107 @@ export const AntigravityIcon: Icon = (props) => ( ); +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 ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + export const OpenCodeIcon: Icon = (props) => ( diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index 68e8935106..b04972c497 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -1,6 +1,7 @@ import "../index.css"; import { + DEFAULT_SERVER_SETTINGS, ORCHESTRATION_WS_METHODS, type MessageId, type OrchestrationReadModel, @@ -56,7 +57,14 @@ function createBaseServerConfig(): ServerConfig { }, ], availableEditors: [], + observability: { + logsDirectoryPath: "/repo/project/.t3/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, settings: { + ...DEFAULT_SERVER_SETTINGS, enableAssistantStreaming: false, defaultThreadEnvMode: "local" as const, textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" }, diff --git a/apps/web/src/components/PullRequestThreadDialog.tsx b/apps/web/src/components/PullRequestThreadDialog.tsx index 2a69facd10..8fa899343e 100644 --- a/apps/web/src/components/PullRequestThreadDialog.tsx +++ b/apps/web/src/components/PullRequestThreadDialog.tsx @@ -1,4 +1,4 @@ -import type { GitResolvePullRequestResult } from "@t3tools/contracts"; +import type { GitResolvePullRequestResult, ThreadId } from "@t3tools/contracts"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useDebouncedValue } from "@tanstack/react-pacer"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -24,6 +24,7 @@ import { Spinner } from "./ui/spinner"; interface PullRequestThreadDialogProps { open: boolean; + threadId: ThreadId; cwd: string | null; initialReference: string | null; onOpenChange: (open: boolean) => void; @@ -32,6 +33,7 @@ interface PullRequestThreadDialogProps { export function PullRequestThreadDialog({ open, + threadId, cwd, initialReference, onOpenChange, @@ -130,6 +132,7 @@ export function PullRequestThreadDialog({ const result = await preparePullRequestThreadMutation.mutateAsync({ reference: parsedReference, mode, + ...(mode === "worktree" ? { threadId } : {}), }); await onPrepared({ branch: result.branch, @@ -147,6 +150,7 @@ export function PullRequestThreadDialog({ parsedReference, preparePullRequestThreadMutation, resolvedPullRequest, + threadId, ], ); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 835834bd18..ffb7c1e4d0 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -212,6 +212,7 @@ interface TerminalViewportProps { terminalId: string; terminalLabel: string; cwd: string; + worktreePath?: string | null; runtimeEnv?: Record; onSessionExited: () => void; onAddTerminalContext: (selection: TerminalContextSelection) => void; @@ -226,6 +227,7 @@ function TerminalViewport({ terminalId, terminalLabel, cwd, + worktreePath, runtimeEnv, onSessionExited, onAddTerminalContext, @@ -597,6 +599,7 @@ function TerminalViewport({ threadId, terminalId, cwd, + ...(worktreePath !== undefined ? { worktreePath } : {}), cols: activeTerminal.cols, rows: activeTerminal.rows, ...(runtimeEnv ? { env: runtimeEnv } : {}), @@ -720,6 +723,7 @@ function TerminalViewport({ interface ThreadTerminalDrawerProps { threadId: ThreadId; cwd: string; + worktreePath?: string | null; runtimeEnv?: Record; visible?: boolean; height: number; @@ -771,6 +775,7 @@ function TerminalActionButton({ label, className, onClick, children }: TerminalA export default function ThreadTerminalDrawer({ threadId, cwd, + worktreePath, runtimeEnv, visible = true, height, @@ -1097,6 +1102,7 @@ export default function ThreadTerminalDrawer({ terminalId={terminalId} terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"} cwd={cwd} + {...(worktreePath !== undefined ? { worktreePath } : {})} {...(runtimeEnv ? { runtimeEnv } : {})} onSessionExited={() => onCloseTerminal(terminalId)} onAddTerminalContext={onAddTerminalContext} @@ -1117,6 +1123,7 @@ export default function ThreadTerminalDrawer({ terminalId={resolvedActiveTerminalId} terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"} cwd={cwd} + {...(worktreePath !== undefined ? { worktreePath } : {})} {...(runtimeEnv ? { runtimeEnv } : {})} onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)} onAddTerminalContext={onAddTerminalContext} diff --git a/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts b/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts new file mode 100644 index 0000000000..2e371b7d76 --- /dev/null +++ b/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from "vitest"; + +import type { WsConnectionStatus } from "../rpc/wsConnectionState"; +import { shouldAutoReconnect } from "./WebSocketConnectionSurface"; + +function makeStatus(overrides: Partial = {}): WsConnectionStatus { + return { + attemptCount: 0, + closeCode: null, + closeReason: null, + connectedAt: null, + disconnectedAt: null, + hasConnected: false, + lastError: null, + lastErrorAt: null, + nextRetryAt: null, + online: true, + phase: "idle", + reconnectAttemptCount: 0, + reconnectMaxAttempts: 8, + reconnectPhase: "idle", + socketUrl: null, + ...overrides, + }; +} + +describe("WebSocketConnectionSurface.logic", () => { + it("forces reconnect on online when the app was offline", () => { + expect( + shouldAutoReconnect( + makeStatus({ + disconnectedAt: "2026-04-03T20:00:00.000Z", + online: false, + phase: "disconnected", + }), + "online", + ), + ).toBe(true); + }); + + it("forces reconnect on focus only for previously connected disconnected states", () => { + expect( + shouldAutoReconnect( + makeStatus({ + hasConnected: true, + online: true, + phase: "disconnected", + reconnectAttemptCount: 3, + reconnectPhase: "waiting", + }), + "focus", + ), + ).toBe(true); + + expect( + shouldAutoReconnect( + makeStatus({ + hasConnected: false, + online: true, + phase: "disconnected", + reconnectAttemptCount: 1, + reconnectPhase: "waiting", + }), + "focus", + ), + ).toBe(false); + }); + + it("forces reconnect on focus for exhausted reconnect loops", () => { + expect( + shouldAutoReconnect( + makeStatus({ + hasConnected: true, + online: true, + phase: "disconnected", + reconnectAttemptCount: 8, + reconnectPhase: "exhausted", + }), + "focus", + ), + ).toBe(true); + }); +}); diff --git a/apps/web/src/components/WebSocketConnectionSurface.tsx b/apps/web/src/components/WebSocketConnectionSurface.tsx new file mode 100644 index 0000000000..1855046a62 --- /dev/null +++ b/apps/web/src/components/WebSocketConnectionSurface.tsx @@ -0,0 +1,544 @@ +import { AlertTriangle, CloudOff, LoaderCircle, RotateCw } from "lucide-react"; +import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react"; + +import { APP_DISPLAY_NAME } from "../branding"; +import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState"; +import { useServerConfig } from "../rpc/serverState"; +import { + exhaustWsReconnectIfStillWaiting, + getWsConnectionStatus, + getWsConnectionUiState, + setBrowserOnlineStatus, + type WsConnectionStatus, + type WsConnectionUiState, + useWsConnectionStatus, + WS_RECONNECT_MAX_ATTEMPTS, +} from "../rpc/wsConnectionState"; +import { Button } from "./ui/button"; +import { toastManager } from "./ui/toast"; +import { getWsRpcClient } from "~/wsRpcClient"; + +const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000; +type WsAutoReconnectTrigger = "focus" | "online"; + +const connectionTimeFormatter = new Intl.DateTimeFormat(undefined, { + day: "numeric", + hour: "numeric", + minute: "2-digit", + month: "short", + second: "2-digit", +}); + +function formatConnectionMoment(isoDate: string | null): string | null { + if (!isoDate) { + return null; + } + + return connectionTimeFormatter.format(new Date(isoDate)); +} + +function formatRetryCountdown(nextRetryAt: string, nowMs: number): string { + const remainingMs = Math.max(0, new Date(nextRetryAt).getTime() - nowMs); + return `${Math.max(1, Math.ceil(remainingMs / 1000))}s`; +} + +function describeOfflineToast(): string { + return "WebSocket disconnected. Waiting for network."; +} + +function formatReconnectAttemptLabel(status: WsConnectionStatus): string { + const reconnectAttempt = Math.max( + 1, + Math.min(status.reconnectAttemptCount, WS_RECONNECT_MAX_ATTEMPTS), + ); + return `Attempt ${reconnectAttempt}/${status.reconnectMaxAttempts}`; +} + +function describeExhaustedToast(): string { + return "Retries exhausted trying to reconnect"; +} + +function buildReconnectTitle(status: WsConnectionStatus): string { + if (status.nextRetryAt === null) { + return "Disconnected from T3 Server"; + } + + return "Disconnected from T3 Server"; +} + +function describeRecoveredToast( + previousDisconnectedAt: string | null, + connectedAt: string | null, +): string { + const reconnectedAtLabel = formatConnectionMoment(connectedAt); + const disconnectedAtLabel = formatConnectionMoment(previousDisconnectedAt); + + if (disconnectedAtLabel && reconnectedAtLabel) { + return `Disconnected at ${disconnectedAtLabel} and reconnected at ${reconnectedAtLabel}.`; + } + + if (reconnectedAtLabel) { + return `Connection restored at ${reconnectedAtLabel}.`; + } + + return "Connection restored."; +} + +function describeSlowRpcAckToast(requests: ReadonlyArray): ReactNode { + const count = requests.length; + const thresholdSeconds = Math.round((requests[0]?.thresholdMs ?? 0) / 1000); + + return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`; +} + +export function shouldAutoReconnect( + status: WsConnectionStatus, + trigger: WsAutoReconnectTrigger, +): boolean { + const uiState = getWsConnectionUiState(status); + + if (trigger === "online") { + return ( + uiState === "offline" || + uiState === "reconnecting" || + uiState === "error" || + status.reconnectPhase === "exhausted" + ); + } + + return ( + status.online && + status.hasConnected && + (uiState === "reconnecting" || status.reconnectPhase === "exhausted") + ); +} + +function buildBlockingCopy( + uiState: WsConnectionUiState, + status: WsConnectionStatus, +): { + readonly description: string; + readonly eyebrow: string; + readonly title: string; +} { + if (uiState === "connecting") { + return { + description: `Opening the WebSocket connection to the ${APP_DISPLAY_NAME} server and waiting for the initial config snapshot.`, + eyebrow: "Starting Session", + title: `Connecting to ${APP_DISPLAY_NAME}`, + }; + } + + if (uiState === "offline") { + return { + description: + "Your browser is offline, so the web client cannot reach the T3 server. Reconnect to the network and the app will retry automatically.", + eyebrow: "Offline", + title: "WebSocket connection unavailable", + }; + } + + if (status.lastError?.trim()) { + return { + description: `${status.lastError} Verify that the T3 server is running and reachable, then reload the app if needed.`, + eyebrow: "Connection Error", + title: "Cannot reach the T3 server", + }; + } + + return { + description: + "The web client could not complete its initial WebSocket connection to the T3 server. It will keep retrying in the background.", + eyebrow: "Connection Error", + title: "Cannot reach the T3 server", + }; +} + +function buildConnectionDetails(status: WsConnectionStatus, uiState: WsConnectionUiState): string { + const details = [ + `state: ${uiState}`, + `online: ${status.online ? "yes" : "no"}`, + `attempts: ${status.attemptCount}`, + ]; + + if (status.socketUrl) { + details.push(`socket: ${status.socketUrl}`); + } + if (status.connectedAt) { + details.push(`connectedAt: ${status.connectedAt}`); + } + if (status.disconnectedAt) { + details.push(`disconnectedAt: ${status.disconnectedAt}`); + } + if (status.lastErrorAt) { + details.push(`lastErrorAt: ${status.lastErrorAt}`); + } + if (status.lastError) { + details.push(`lastError: ${status.lastError}`); + } + if (status.closeCode !== null) { + details.push(`closeCode: ${status.closeCode}`); + } + if (status.closeReason) { + details.push(`closeReason: ${status.closeReason}`); + } + + return details.join("\n"); +} + +function WebSocketBlockingState({ + status, + uiState, +}: { + readonly status: WsConnectionStatus; + readonly uiState: WsConnectionUiState; +}) { + const copy = buildBlockingCopy(uiState, status); + const disconnectedAt = formatConnectionMoment(status.disconnectedAt ?? status.lastErrorAt); + const Icon = + uiState === "connecting" ? LoaderCircle : uiState === "offline" ? CloudOff : AlertTriangle; + + return ( +
+
+
+
+
+ +
+
+
+

+ {copy.eyebrow} +

+

{copy.title}

+
+
+ +
+
+ +

{copy.description}

+ +
+
+

+ Connection +

+

+ {uiState === "connecting" + ? "Opening WebSocket" + : uiState === "offline" + ? "Waiting for network" + : "Retrying server connection"} +

+
+
+

+ Latest Event +

+

{disconnectedAt ?? "Pending"}

+
+
+ +
+ +
+ +
+ + Show connection details + Hide connection details + +
+            {buildConnectionDetails(status, uiState)}
+          
+
+
+
+ ); +} + +export function WebSocketConnectionCoordinator() { + const status = useWsConnectionStatus(); + const [nowMs, setNowMs] = useState(() => Date.now()); + const lastForcedReconnectAtRef = useRef(0); + const toastIdRef = useRef | null>(null); + const toastResetTimerRef = useRef(null); + const previousUiStateRef = useRef(getWsConnectionUiState(status)); + const previousDisconnectedAtRef = useRef(status.disconnectedAt); + + const runReconnect = useEffectEvent((showFailureToast: boolean) => { + if (toastResetTimerRef.current !== null) { + window.clearTimeout(toastResetTimerRef.current); + toastResetTimerRef.current = null; + } + lastForcedReconnectAtRef.current = Date.now(); + void getWsRpcClient() + .reconnect() + .catch((error) => { + if (!showFailureToast) { + console.warn("Automatic WebSocket reconnect failed", { error }); + return; + } + toastManager.add({ + type: "error", + title: "Reconnect failed", + description: error instanceof Error ? error.message : "Unable to restart the WebSocket.", + data: { + dismissAfterVisibleMs: 8_000, + hideCopyButton: true, + }, + }); + }); + }); + const syncBrowserOnlineStatus = useEffectEvent(() => { + setBrowserOnlineStatus(navigator.onLine !== false); + }); + const triggerManualReconnect = useEffectEvent(() => { + runReconnect(true); + }); + const triggerAutoReconnect = useEffectEvent((trigger: WsAutoReconnectTrigger) => { + const currentStatus = + trigger === "online" ? setBrowserOnlineStatus(true) : getWsConnectionStatus(); + + if (!shouldAutoReconnect(currentStatus, trigger)) { + return; + } + if (Date.now() - lastForcedReconnectAtRef.current < FORCED_WS_RECONNECT_DEBOUNCE_MS) { + return; + } + + runReconnect(false); + }); + + useEffect(() => { + const handleOnline = () => { + triggerAutoReconnect("online"); + }; + const handleFocus = () => { + triggerAutoReconnect("focus"); + }; + + syncBrowserOnlineStatus(); + window.addEventListener("online", handleOnline); + window.addEventListener("offline", syncBrowserOnlineStatus); + window.addEventListener("focus", handleFocus); + return () => { + window.removeEventListener("online", handleOnline); + window.removeEventListener("offline", syncBrowserOnlineStatus); + window.removeEventListener("focus", handleFocus); + }; + }, []); + + useEffect(() => { + if (status.reconnectPhase !== "waiting" || status.nextRetryAt === null) { + return; + } + + setNowMs(Date.now()); + const intervalId = window.setInterval(() => { + setNowMs(Date.now()); + }, 1_000); + + return () => { + window.clearInterval(intervalId); + }; + }, [status.nextRetryAt, status.reconnectPhase]); + + useEffect(() => { + if ( + status.reconnectPhase !== "waiting" || + status.nextRetryAt === null || + !status.online || + !status.hasConnected + ) { + return; + } + + const nextRetryAt = status.nextRetryAt; + const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500; + const timeoutId = window.setTimeout(() => { + exhaustWsReconnectIfStillWaiting(nextRetryAt); + }, timeoutMs); + + return () => { + window.clearTimeout(timeoutId); + }; + }, [ + status.hasConnected, + status.nextRetryAt, + status.online, + status.reconnectAttemptCount, + status.reconnectPhase, + ]); + + useEffect(() => { + const uiState = getWsConnectionUiState(status); + const previousUiState = previousUiStateRef.current; + const previousDisconnectedAt = previousDisconnectedAtRef.current; + const shouldShowReconnectToast = status.hasConnected && uiState === "reconnecting"; + const shouldShowOfflineToast = uiState === "offline" && status.disconnectedAt !== null; + const shouldShowExhaustedToast = status.hasConnected && status.reconnectPhase === "exhausted"; + + if ( + toastResetTimerRef.current !== null && + (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) + ) { + window.clearTimeout(toastResetTimerRef.current); + toastResetTimerRef.current = null; + } + + if (shouldShowReconnectToast || shouldShowOfflineToast || shouldShowExhaustedToast) { + const toastPayload = shouldShowOfflineToast + ? { + description: describeOfflineToast(), + timeout: 0, + title: "Offline", + type: "warning" as const, + data: { + hideCopyButton: true, + }, + } + : shouldShowExhaustedToast + ? { + actionProps: { + children: "Retry", + onClick: triggerManualReconnect, + }, + description: describeExhaustedToast(), + timeout: 0, + title: "Disconnected from T3 Server", + type: "error" as const, + data: { + hideCopyButton: true, + }, + } + : { + actionProps: { + children: "Retry now", + onClick: triggerManualReconnect, + }, + description: + status.nextRetryAt === null + ? `Reconnecting... ${formatReconnectAttemptLabel(status)}` + : `Reconnecting in ${formatRetryCountdown(status.nextRetryAt, nowMs)}... ${formatReconnectAttemptLabel(status)}`, + timeout: 0, + title: buildReconnectTitle(status), + type: "loading" as const, + data: { + hideCopyButton: true, + }, + }; + + if (toastIdRef.current) { + toastManager.update(toastIdRef.current, toastPayload); + } else { + toastIdRef.current = toastManager.add(toastPayload); + } + } else if (toastIdRef.current) { + toastManager.close(toastIdRef.current); + toastIdRef.current = null; + } + + if ( + uiState === "connected" && + (previousUiState === "offline" || previousUiState === "reconnecting") && + previousDisconnectedAt !== null + ) { + const successToast = { + description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt), + title: "Reconnected to T3 Server", + type: "success" as const, + timeout: 0, + data: { + dismissAfterVisibleMs: 8_000, + hideCopyButton: true, + }, + }; + + if (toastIdRef.current) { + toastManager.update(toastIdRef.current, successToast); + } else { + toastIdRef.current = toastManager.add(successToast); + } + + toastResetTimerRef.current = window.setTimeout(() => { + toastIdRef.current = null; + toastResetTimerRef.current = null; + }, 8_250); + } + + previousUiStateRef.current = uiState; + previousDisconnectedAtRef.current = status.disconnectedAt; + }, [nowMs, status]); + + useEffect(() => { + return () => { + if (toastResetTimerRef.current !== null) { + window.clearTimeout(toastResetTimerRef.current); + } + }; + }, []); + + return null; +} + +export function SlowRpcAckToastCoordinator() { + const slowRequests = useSlowRpcAckRequests(); + const status = useWsConnectionStatus(); + const toastIdRef = useRef | null>(null); + + useEffect(() => { + if (getWsConnectionUiState(status) !== "connected") { + if (toastIdRef.current) { + toastManager.close(toastIdRef.current); + toastIdRef.current = null; + } + return; + } + + if (slowRequests.length === 0) { + if (toastIdRef.current) { + toastManager.close(toastIdRef.current); + toastIdRef.current = null; + } + return; + } + + const nextToast = { + description: describeSlowRpcAckToast(slowRequests), + timeout: 0, + title: "Some requests are slow", + type: "warning" as const, + }; + + if (toastIdRef.current) { + toastManager.update(toastIdRef.current, nextToast); + } else { + toastIdRef.current = toastManager.add(nextToast); + } + }, [slowRequests, status]); + + return null; +} + +export function WebSocketConnectionSurface({ children }: { readonly children: ReactNode }) { + const serverConfig = useServerConfig(); + const status = useWsConnectionStatus(); + + if (serverConfig === null) { + const uiState = getWsConnectionUiState(status); + return ( + + ); + } + + return children; +} diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index bb5362439e..703bfadaa3 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -6,7 +6,15 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react"; import { Button } from "../ui/button"; import { Group, GroupSeparator } from "../ui/group"; import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu"; -import { AntigravityIcon, CursorIcon, Icon, TraeIcon, VisualStudioCode, Zed } from "../Icons"; +import { + AntigravityIcon, + CursorIcon, + Icon, + TraeIcon, + IntelliJIdeaIcon, + VisualStudioCode, + Zed, +} from "../Icons"; import { isMacPlatform, isWindowsPlatform } from "~/lib/utils"; import { readNativeApi } from "~/nativeApi"; @@ -47,6 +55,11 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray { + beforeEach(() => { + resetServerStateForTests(); + __resetNativeApiForTests(); + localStorage.clear(); + document.body.innerHTML = ""; + }); + + afterEach(() => { + resetServerStateForTests(); + __resetNativeApiForTests(); + document.body.innerHTML = ""; + }); + + it("shows diagnostics inside About with a single logs-folder action", async () => { + setServerConfigSnapshot(createBaseServerConfig()); + + await render( + + + , + ); + + 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 })) + .toBeInTheDocument(); + await expect + .element( + page.getByText( + "Local trace file. OTLP exporting traces to http://localhost:4318/v1/traces.", + ), + ) + .toBeInTheDocument(); + }); + + it("opens the logs folder in the preferred editor", async () => { + const openInEditor = vi.fn().mockResolvedValue(undefined); + window.nativeApi = { + shell: { + openInEditor, + }, + } as unknown as NativeApi; + + setServerConfigSnapshot(createBaseServerConfig()); + + await render( + + + , + ); + + const openLogsButton = page.getByText("Open logs folder"); + await openLogsButton.click(); + + expect(openInEditor).toHaveBeenCalledWith("/repo/project/.t3/logs", "cursor"); + }); +}); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 4c258b62e8..97c84271a7 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -61,6 +61,7 @@ import { ProjectFavicon } from "../ProjectFavicon"; import { useServerAvailableEditors, useServerKeybindingsConfigPath, + useServerObservability, useServerProviders, } from "../../rpc/serverState"; @@ -518,8 +519,13 @@ export function GeneralSettingsPanel() { const { theme, setTheme } = useTheme(); const settings = useSettings(); const { updateSettings } = useUpdateSettings(); - const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false); - const [openKeybindingsError, setOpenKeybindingsError] = useState(null); + const [openingPathByTarget, setOpeningPathByTarget] = useState({ + keybindings: false, + logsDirectory: false, + }); + const [openPathErrorByTarget, setOpenPathErrorByTarget] = useState< + Partial> + >({}); const [openProviderDetails, setOpenProviderDetails] = useState>({ codex: Boolean( settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath || @@ -561,8 +567,21 @@ export function GeneralSettingsPanel() { const keybindingsConfigPath = useServerKeybindingsConfigPath(); const availableEditors = useServerAvailableEditors(); + const observability = useServerObservability(); const serverProviders = useServerProviders(); const codexHomePath = settings.providers.codex.homePath; + 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 textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders); const textGenProvider = textGenerationModelSelection.provider; @@ -579,27 +598,49 @@ 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 ensureNativeApi() + .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(() => { - if (!keybindingsConfigPath) return; - setOpenKeybindingsError(null); - setIsOpeningKeybindings(true); - const editor = resolveAndPersistPreferredEditor(availableEditors ?? []); - if (!editor) { - setOpenKeybindingsError("No available editors found."); - setIsOpeningKeybindings(false); - return; - } - void ensureNativeApi() - .shell.openInEditor(keybindingsConfigPath, editor) - .catch((error) => { - setOpenKeybindingsError( - error instanceof Error ? error.message : "Unable to open keybindings file.", - ); - }) - .finally(() => { - setIsOpeningKeybindings(false); - }); - }, [availableEditors, keybindingsConfigPath]); + 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 addCustomModel = useCallback( (provider: ProviderKind) => { @@ -1408,6 +1449,30 @@ export function GeneralSettingsPanel() { description="Current version of the application." /> )} + + + {logsDirectoryPath ?? "Resolving logs directory..."} + + {openDiagnosticsError ? ( + {openDiagnosticsError} + ) : null} + + } + control={ + + } + /> ); diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx index 123bb388cc..dbe546cc82 100644 --- a/apps/web/src/components/ui/toast.tsx +++ b/apps/web/src/components/ui/toast.tsx @@ -23,6 +23,7 @@ export type ThreadToastData = { threadId?: ThreadId | null; tooltipStyle?: boolean; dismissAfterVisibleMs?: number; + hideCopyButton?: boolean; }; const toastManager = Toast.createToastManager(); @@ -308,15 +309,15 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
- {toast.type === "error" && typeof toast.description === "string" && ( - - )} + {toast.type === "error" && + typeof toast.description === "string" && + !toast.data?.hideCopyButton && }
@@ -402,15 +403,17 @@ function AnchoredToasts() {
- {toast.type === "error" && typeof toast.description === "string" && ( - - )} + {toast.type === "error" && + typeof toast.description === "string" && + !toast.data?.hideCopyButton && ( + + )}
diff --git a/apps/web/src/lib/gitReactQuery.ts b/apps/web/src/lib/gitReactQuery.ts index 53f04848c7..bfac623db9 100644 --- a/apps/web/src/lib/gitReactQuery.ts +++ b/apps/web/src/lib/gitReactQuery.ts @@ -1,4 +1,8 @@ -import { type GitActionProgressEvent, type GitStackedAction } from "@t3tools/contracts"; +import { + type GitActionProgressEvent, + type GitStackedAction, + type ThreadId, +} from "@t3tools/contracts"; import { infiniteQueryOptions, mutationOptions, @@ -244,13 +248,22 @@ export function gitPreparePullRequestThreadMutationOptions(input: { queryClient: QueryClient; }) { return mutationOptions({ - mutationFn: async ({ reference, mode }: { reference: string; mode: "local" | "worktree" }) => { + mutationFn: async ({ + reference, + mode, + threadId, + }: { + reference: string; + mode: "local" | "worktree"; + threadId?: ThreadId; + }) => { const api = ensureNativeApi(); if (!input.cwd) throw new Error("Pull request thread preparation is unavailable."); return api.git.preparePullRequestThread({ cwd: input.cwd, reference, mode, + ...(threadId ? { threadId } : {}), }); }, mutationKey: gitMutationKeys.preparePullRequestThread(input.cwd), diff --git a/apps/web/src/observability/clientTracing.ts b/apps/web/src/observability/clientTracing.ts new file mode 100644 index 0000000000..aa9d50c114 --- /dev/null +++ b/apps/web/src/observability/clientTracing.ts @@ -0,0 +1,147 @@ +import { Exit, Layer, ManagedRuntime, Scope, Tracer } from "effect"; +import { FetchHttpClient, HttpClient } from "effect/unstable/http"; +import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; + +import { isElectron } from "../env"; +import { resolveServerUrl } from "../lib/utils"; +import { APP_VERSION } from "~/branding"; + +const DEFAULT_EXPORT_INTERVAL_MS = 1_000; +const CLIENT_TRACING_RESOURCE = { + serviceName: "t3-web", + attributes: { + "service.runtime": "t3-web", + "service.mode": isElectron ? "electron" : "browser", + "service.version": APP_VERSION, + }, +} as const; + +const delegateRuntimeLayer = Layer.mergeAll( + FetchHttpClient.layer, + OtlpSerialization.layerJson, + Layer.succeed(HttpClient.TracerDisabledWhen, () => true), +); + +let activeDelegate: Tracer.Tracer | null = null; +let activeRuntime: ManagedRuntime.ManagedRuntime | null = null; +let activeScope: Scope.Closeable | null = null; +let activeConfigKey: string | null = null; +let configurationGeneration = 0; +let pendingConfiguration = Promise.resolve(); + +export interface ClientTracingConfig { + readonly exportIntervalMs?: number; +} + +export const ClientTracingLive = Layer.succeed( + Tracer.Tracer, + Tracer.make({ + span(options) { + return activeDelegate?.span(options) ?? new Tracer.NativeSpan(options); + }, + }), +); + +export function configureClientTracing(config: ClientTracingConfig = {}): Promise { + if (config.exportIntervalMs === undefined && activeConfigKey !== null) { + return pendingConfiguration; + } + pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config)); + return pendingConfiguration; +} + +async function applyClientTracingConfig(config: ClientTracingConfig): Promise { + const otlpTracesUrl = resolveServerUrl({ + protocol: window.location.protocol === "https:" ? "https" : "http", + pathname: "/api/observability/v1/traces", + }); + const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS); + const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`; + + if (activeConfigKey === nextConfigKey && activeDelegate !== null) { + return; + } + + activeConfigKey = nextConfigKey; + const generation = ++configurationGeneration; + + const previousRuntime = activeRuntime; + const previousScope = activeScope; + + activeDelegate = null; + activeRuntime = null; + activeScope = null; + + await disposeTracerRuntime(previousRuntime, previousScope); + + const runtime = ManagedRuntime.make(delegateRuntimeLayer); + const scope = runtime.runSync(Scope.make()); + + try { + const delegate = await runtime.runPromise( + Scope.provide(scope)( + OtlpTracer.make({ + url: otlpTracesUrl, + exportInterval: `${exportIntervalMs} millis`, + resource: CLIENT_TRACING_RESOURCE, + }), + ), + ); + + if (generation !== configurationGeneration) { + await disposeTracerRuntime(runtime, scope); + return; + } + + activeDelegate = delegate; + activeRuntime = runtime; + activeScope = scope; + } catch (error) { + await disposeTracerRuntime(runtime, scope); + + if (generation === configurationGeneration) { + console.warn("Failed to configure client tracing exporter", { + error: formatError(error), + otlpTracesUrl, + }); + } + } +} + +async function disposeTracerRuntime( + runtime: ManagedRuntime.ManagedRuntime | null, + scope: Scope.Closeable | null, +): Promise { + if (runtime === null || scope === null) { + return; + } + + await runtime + .runPromise(Scope.close(scope, Exit.void)) + .catch(() => undefined) + .finally(() => { + runtime.dispose(); + }); +} + +function formatError(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; + } + + return String(error); +} + +export async function __resetClientTracingForTests() { + configurationGeneration++; + activeConfigKey = null; + activeDelegate = null; + pendingConfiguration = Promise.resolve(); + + const runtime = activeRuntime; + const scope = activeScope; + activeRuntime = null; + activeScope = null; + + await disposeTracerRuntime(runtime, scope); +} diff --git a/apps/web/src/orchestrationRecovery.test.ts b/apps/web/src/orchestrationRecovery.test.ts index fbdbea4ee3..b04622cdbd 100644 --- a/apps/web/src/orchestrationRecovery.test.ts +++ b/apps/web/src/orchestrationRecovery.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "vitest"; -import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery"; +import { + createOrchestrationRecoveryCoordinator, + deriveReplayRetryDecision, +} from "./orchestrationRecovery"; describe("createOrchestrationRecoveryCoordinator", () => { it("defers live events until bootstrap completes and then requests replay", () => { @@ -59,10 +62,13 @@ describe("createOrchestrationRecoveryCoordinator", () => { coordinator.classifyDomainEvent(7); coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]); - expect(coordinator.completeReplayRecovery()).toBe(true); + expect(coordinator.completeReplayRecovery()).toEqual({ + replayMadeProgress: true, + shouldReplay: true, + }); }); - it("does not immediately replay again when replay returns no new events", () => { + it("retries replay when no progress was made but higher live sequences were observed", () => { const coordinator = createOrchestrationRecoveryCoordinator(); coordinator.beginSnapshotRecovery("bootstrap"); @@ -70,7 +76,10 @@ describe("createOrchestrationRecoveryCoordinator", () => { coordinator.classifyDomainEvent(5); coordinator.beginReplayRecovery("sequence-gap"); - expect(coordinator.completeReplayRecovery()).toBe(false); + expect(coordinator.completeReplayRecovery()).toEqual({ + replayMadeProgress: false, + shouldReplay: true, + }); expect(coordinator.getState()).toMatchObject({ latestSequence: 3, highestObservedSequence: 5, @@ -79,6 +88,19 @@ describe("createOrchestrationRecoveryCoordinator", () => { }); }); + it("does not request another replay when a replay made no progress and nothing newer was observed", () => { + const coordinator = createOrchestrationRecoveryCoordinator(); + + coordinator.beginSnapshotRecovery("bootstrap"); + coordinator.completeSnapshotRecovery(3); + coordinator.beginReplayRecovery("sequence-gap"); + + expect(coordinator.completeReplayRecovery()).toEqual({ + replayMadeProgress: false, + shouldReplay: false, + }); + }); + it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => { const coordinator = createOrchestrationRecoveryCoordinator(); @@ -131,3 +153,154 @@ describe("createOrchestrationRecoveryCoordinator", () => { }); }); }); + +describe("deriveReplayRetryDecision", () => { + it("retries immediately when replay made progress", () => { + expect( + deriveReplayRetryDecision({ + previousTracker: { + attempts: 2, + latestSequence: 3, + highestObservedSequence: 5, + }, + completion: { + replayMadeProgress: true, + shouldReplay: true, + }, + recoveryState: { + latestSequence: 5, + highestObservedSequence: 5, + }, + baseDelayMs: 100, + maxNoProgressRetries: 3, + }), + ).toEqual({ + shouldRetry: true, + delayMs: 0, + tracker: null, + }); + }); + + it("caps no-progress retries for the same frontier", () => { + const first = deriveReplayRetryDecision({ + previousTracker: null, + completion: { + replayMadeProgress: false, + shouldReplay: true, + }, + recoveryState: { + latestSequence: 3, + highestObservedSequence: 5, + }, + baseDelayMs: 100, + maxNoProgressRetries: 3, + }); + + const second = deriveReplayRetryDecision({ + previousTracker: first.tracker, + completion: { + replayMadeProgress: false, + shouldReplay: true, + }, + recoveryState: { + latestSequence: 3, + highestObservedSequence: 5, + }, + baseDelayMs: 100, + maxNoProgressRetries: 3, + }); + + const third = deriveReplayRetryDecision({ + previousTracker: second.tracker, + completion: { + replayMadeProgress: false, + shouldReplay: true, + }, + recoveryState: { + latestSequence: 3, + highestObservedSequence: 5, + }, + baseDelayMs: 100, + maxNoProgressRetries: 3, + }); + + const fourth = deriveReplayRetryDecision({ + previousTracker: third.tracker, + completion: { + replayMadeProgress: false, + shouldReplay: true, + }, + recoveryState: { + latestSequence: 3, + highestObservedSequence: 5, + }, + baseDelayMs: 100, + maxNoProgressRetries: 3, + }); + + expect(first).toEqual({ + shouldRetry: true, + delayMs: 100, + tracker: { + attempts: 1, + latestSequence: 3, + highestObservedSequence: 5, + }, + }); + expect(second).toEqual({ + shouldRetry: true, + delayMs: 200, + tracker: { + attempts: 2, + latestSequence: 3, + highestObservedSequence: 5, + }, + }); + expect(third).toEqual({ + shouldRetry: true, + delayMs: 400, + tracker: { + attempts: 3, + latestSequence: 3, + highestObservedSequence: 5, + }, + }); + expect(fourth).toEqual({ + shouldRetry: false, + delayMs: 0, + tracker: null, + }); + }); + + it("resets the retry budget when the replay frontier changes", () => { + const exhausted = { + attempts: 3, + latestSequence: 3, + highestObservedSequence: 5, + }; + + expect( + deriveReplayRetryDecision({ + previousTracker: exhausted, + completion: { + replayMadeProgress: false, + shouldReplay: true, + }, + recoveryState: { + latestSequence: 3, + highestObservedSequence: 6, + }, + baseDelayMs: 100, + maxNoProgressRetries: 3, + }), + ).toEqual({ + shouldRetry: true, + delayMs: 100, + tracker: { + attempts: 1, + latestSequence: 3, + highestObservedSequence: 6, + }, + }); + }); +}); diff --git a/apps/web/src/orchestrationRecovery.ts b/apps/web/src/orchestrationRecovery.ts index 5af48f85b9..c9ccf3a393 100644 --- a/apps/web/src/orchestrationRecovery.ts +++ b/apps/web/src/orchestrationRecovery.ts @@ -1,4 +1,8 @@ -export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed"; +export type OrchestrationRecoveryReason = + | "bootstrap" + | "sequence-gap" + | "resubscribe" + | "replay-failed"; export interface OrchestrationRecoveryPhase { kind: "snapshot" | "replay"; @@ -13,8 +17,74 @@ export interface OrchestrationRecoveryState { inFlight: OrchestrationRecoveryPhase | null; } +export interface ReplayRecoveryCompletion { + replayMadeProgress: boolean; + shouldReplay: boolean; +} + +export interface ReplayRetryTracker { + attempts: number; + latestSequence: number; + highestObservedSequence: number; +} + +export interface ReplayRetryDecision { + shouldRetry: boolean; + delayMs: number; + tracker: ReplayRetryTracker | null; +} + type SequencedEvent = Readonly<{ sequence: number }>; +export function deriveReplayRetryDecision(input: { + previousTracker: ReplayRetryTracker | null; + completion: ReplayRecoveryCompletion; + recoveryState: Pick; + baseDelayMs: number; + maxNoProgressRetries: number; +}): ReplayRetryDecision { + if (!input.completion.shouldReplay) { + return { + shouldRetry: false, + delayMs: 0, + tracker: null, + }; + } + + if (input.completion.replayMadeProgress) { + return { + shouldRetry: true, + delayMs: 0, + tracker: null, + }; + } + + const previousTracker = input.previousTracker; + const sameFrontier = + previousTracker !== null && + previousTracker.latestSequence === input.recoveryState.latestSequence && + previousTracker.highestObservedSequence === input.recoveryState.highestObservedSequence; + + const attempts = sameFrontier && previousTracker !== null ? previousTracker.attempts + 1 : 1; + if (attempts > input.maxNoProgressRetries) { + return { + shouldRetry: false, + delayMs: 0, + tracker: null, + }; + } + + return { + shouldRetry: true, + delayMs: input.baseDelayMs * 2 ** (attempts - 1), + tracker: { + attempts, + latestSequence: input.recoveryState.latestSequence, + highestObservedSequence: input.recoveryState.highestObservedSequence, + }, + }; +} + export function createOrchestrationRecoveryCoordinator() { let state: OrchestrationRecoveryState = { latestSequence: 0, @@ -120,16 +190,16 @@ export function createOrchestrationRecoveryCoordinator() { return true; }, - completeReplayRecovery(): boolean { + completeReplayRecovery(): ReplayRecoveryCompletion { const replayMadeProgress = replayStartSequence !== null && state.latestSequence > replayStartSequence; replayStartSequence = null; state.inFlight = null; - if (!replayMadeProgress) { - state.pendingReplay = false; - return false; - } - return resolveReplayNeedAfterRecovery().shouldReplay; + const replayResolution = resolveReplayNeedAfterRecovery(); + return { + replayMadeProgress, + shouldReplay: replayResolution.shouldReplay, + }; }, failReplayRecovery(): void { diff --git a/apps/web/src/projectScripts.test.ts b/apps/web/src/projectScripts.test.ts index 08678f8730..1e05ff5ef6 100644 --- a/apps/web/src/projectScripts.test.ts +++ b/apps/web/src/projectScripts.test.ts @@ -1,13 +1,15 @@ import { describe, expect, it } from "vitest"; +import { + projectScriptCwd, + projectScriptRuntimeEnv, + setupProjectScript, +} from "@t3tools/shared/projectScripts"; import { commandForProjectScript, nextProjectScriptId, primaryProjectScript, - projectScriptCwd, - projectScriptRuntimeEnv, projectScriptIdFromCommand, - setupProjectScript, } from "./projectScripts"; describe("projectScripts helpers", () => { diff --git a/apps/web/src/projectScripts.ts b/apps/web/src/projectScripts.ts index c11c3923bc..03e3d29116 100644 --- a/apps/web/src/projectScripts.ts +++ b/apps/web/src/projectScripts.ts @@ -55,43 +55,7 @@ export function nextProjectScriptId(name: string, existingIds: Iterable) return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH); } -interface ProjectScriptRuntimeEnvInput { - project: { - cwd: string; - }; - worktreePath?: string | null; - extraEnv?: Record; -} - -export function projectScriptCwd(input: { - project: { - cwd: string; - }; - worktreePath?: string | null; -}): string { - return input.worktreePath ?? input.project.cwd; -} - -export function projectScriptRuntimeEnv( - input: ProjectScriptRuntimeEnvInput, -): Record { - const env: Record = { - T3CODE_PROJECT_ROOT: input.project.cwd, - }; - if (input.worktreePath) { - env.T3CODE_WORKTREE_PATH = input.worktreePath; - } - if (input.extraEnv) { - return { ...env, ...input.extraEnv }; - } - return env; -} - export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null { const regular = scripts.find((script) => !script.runOnWorktreeCreate); return regular ?? scripts[0] ?? null; } - -export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null { - return scripts.find((script) => script.runOnWorktreeCreate) ?? null; -} diff --git a/apps/web/src/pullRequestReference.test.ts b/apps/web/src/pullRequestReference.test.ts index e3e870cf19..2a1ed52079 100644 --- a/apps/web/src/pullRequestReference.test.ts +++ b/apps/web/src/pullRequestReference.test.ts @@ -14,7 +14,7 @@ describe("parsePullRequestReference", () => { }); it("accepts #number references", () => { - expect(parsePullRequestReference("#42")).toBe("#42"); + expect(parsePullRequestReference("#42")).toBe("42"); }); it("accepts gh pr checkout commands with raw numbers", () => { @@ -22,7 +22,7 @@ describe("parsePullRequestReference", () => { }); it("accepts gh pr checkout commands with #number references", () => { - expect(parsePullRequestReference("gh pr checkout #42")).toBe("#42"); + expect(parsePullRequestReference("gh pr checkout #42")).toBe("42"); }); it("accepts gh pr checkout commands with GitHub pull request URLs", () => { diff --git a/apps/web/src/pullRequestReference.ts b/apps/web/src/pullRequestReference.ts index c775c1c66e..b033db7d21 100644 --- a/apps/web/src/pullRequestReference.ts +++ b/apps/web/src/pullRequestReference.ts @@ -22,7 +22,7 @@ export function parsePullRequestReference(input: string): string | null { const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput); if (numberMatch?.[1]) { - return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1]; + return numberMatch[1]; } return null; diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 04bfd61308..48c835ae79 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -1,7 +1,7 @@ import { OrchestrationEvent, - ThreadId, type ServerLifecycleWelcomePayload, + ThreadId, } from "@t3tools/contracts"; import { Outlet, @@ -16,6 +16,11 @@ import { Throttler } from "@tanstack/react-pacer"; import { APP_DISPLAY_NAME } from "../branding"; import { AppSidebarLayout } from "../components/AppSidebarLayout"; +import { + SlowRpcAckToastCoordinator, + WebSocketConnectionCoordinator, + WebSocketConnectionSurface, +} from "../components/WebSocketConnectionSurface"; import { Button } from "../components/ui/button"; import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast"; import { resolveAndPersistPreferredEditor } from "../editorPreferences"; @@ -36,13 +41,13 @@ import { import { selectProjects, selectThreadById, selectThreads, useStore } from "../store"; import { useUiStateStore } from "../uiStateStore"; import { useTerminalStateStore } from "../terminalStateStore"; -import { terminalRunningSubprocessFromEvent } from "../terminalActivity"; import { migrateLocalSettingsToServer } from "../hooks/useSettings"; import { providerQueryKeys } from "../lib/providerReactQuery"; import { projectQueryKeys } from "../lib/projectReactQuery"; import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup"; import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects"; import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery"; +import { deriveReplayRetryDecision } from "../orchestrationRecovery"; import { getWsRpcClient } from "~/wsRpcClient"; export const Route = createRootRouteWithContext<{ @@ -73,9 +78,13 @@ function RootRouteView() { - - - + + + + + + + ); @@ -189,6 +198,9 @@ function coalesceOrchestrationUiEvents( return coalesced; } +const REPLAY_RECOVERY_RETRY_DELAY_MS = 100; +const MAX_NO_PROGRESS_REPLAY_RETRIES = 3; + function ServerStateBootstrap() { useEffect(() => startServerStateSync(getWsRpcClient().server), []); @@ -206,6 +218,7 @@ function EventRouter() { const removeOrphanedTerminalStates = useTerminalStateStore( (store) => store.removeOrphanedTerminalStates, ); + const applyTerminalEvent = useTerminalStateStore((store) => store.applyTerminalEvent); const queryClient = useQueryClient(); const navigate = useNavigate(); const pathname = useLocation({ select: (loc) => loc.pathname }); @@ -309,6 +322,7 @@ function EventRouter() { let disposed = false; disposedRef.current = false; const recovery = createOrchestrationRecoveryCoordinator(); + let replayRetryTracker: import("../orchestrationRecovery").ReplayRetryTracker | null = null; let needsProviderInvalidation = false; const pendingDomainEvents: OrchestrationEvent[] = []; let flushPendingDomainEventsScheduled = false; @@ -424,8 +438,8 @@ function EventRouter() { queueMicrotask(flushPendingDomainEvents); }; - const recoverFromSequenceGap = async (): Promise => { - if (!recovery.beginReplayRecovery("sequence-gap")) { + const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise => { + if (!recovery.beginReplayRecovery(reason)) { return; } @@ -436,13 +450,42 @@ function EventRouter() { applyEventBatch(events); } } catch { + replayRetryTracker = null; recovery.failReplayRecovery(); void fallbackToSnapshotRecovery(); return; } - if (!disposed && recovery.completeReplayRecovery()) { - void recoverFromSequenceGap(); + if (!disposed) { + const replayCompletion = recovery.completeReplayRecovery(); + const retryDecision = deriveReplayRetryDecision({ + previousTracker: replayRetryTracker, + completion: replayCompletion, + recoveryState: recovery.getState(), + baseDelayMs: REPLAY_RECOVERY_RETRY_DELAY_MS, + maxNoProgressRetries: MAX_NO_PROGRESS_REPLAY_RETRIES, + }); + replayRetryTracker = retryDecision.tracker; + + if (retryDecision.shouldRetry) { + if (retryDecision.delayMs > 0) { + await new Promise((resolve) => { + setTimeout(resolve, retryDecision.delayMs); + }); + if (disposed) { + return; + } + } + void runReplayRecovery(reason); + } else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") { + console.warn( + "[orchestration-recovery]", + "Stopping replay recovery after no-progress retries.", + { + state: recovery.getState(), + }, + ); + } } }; @@ -472,7 +515,7 @@ function EventRouter() { syncServerReadModel(snapshot); reconcileSnapshotDerivedState(); if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) { - void recoverFromSequenceGap(); + void runReplayRecovery("sequence-gap"); } } } catch { @@ -489,35 +532,35 @@ function EventRouter() { const fallbackToSnapshotRecovery = async (): Promise => { await runSnapshotRecovery("replay-failed"); }; - const unsubDomainEvent = api.orchestration.onDomainEvent((event) => { - const action = recovery.classifyDomainEvent(event.sequence); - if (action === "apply") { - pendingDomainEvents.push(event); - schedulePendingDomainEventFlush(); - return; - } - if (action === "recover") { - flushPendingDomainEvents(); - void recoverFromSequenceGap(); - } - }); + const unsubDomainEvent = api.orchestration.onDomainEvent( + (event) => { + const action = recovery.classifyDomainEvent(event.sequence); + if (action === "apply") { + pendingDomainEvents.push(event); + schedulePendingDomainEventFlush(); + return; + } + if (action === "recover") { + flushPendingDomainEvents(); + void runReplayRecovery("sequence-gap"); + } + }, + { + onResubscribe: () => { + if (disposed) { + return; + } + flushPendingDomainEvents(); + void runReplayRecovery("resubscribe"); + }, + }, + ); const unsubTerminalEvent = api.terminal.onEvent((event) => { const thread = selectThreadById(ThreadId.makeUnsafe(event.threadId))(useStore.getState()); if (thread && thread.archivedAt !== null) { return; } - useTerminalStateStore.getState().recordTerminalEvent(event); - const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event); - if (hasRunningSubprocess === null) { - return; - } - useTerminalStateStore - .getState() - .setTerminalActivity( - ThreadId.makeUnsafe(event.threadId), - event.terminalId, - hasRunningSubprocess, - ); + applyTerminalEvent(event); }); return () => { disposed = true; @@ -535,6 +578,7 @@ function EventRouter() { queryClient, removeTerminalState, removeOrphanedTerminalStates, + applyTerminalEvent, clearThreadUi, setProjectExpanded, syncProjects, diff --git a/apps/web/src/rpc/client.test.ts b/apps/web/src/rpc/client.test.ts index c19b85dd36..8e3e1a281d 100644 --- a/apps/web/src/rpc/client.test.ts +++ b/apps/web/src/rpc/client.test.ts @@ -2,6 +2,10 @@ import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { AsyncResult, AtomRegistry } from "effect/unstable/reactivity"; +import { + configureClientTracing, + __resetClientTracingForTests, +} from "../observability/clientTracing"; import { __resetWsRpcAtomClientForTests, runRpc, WsRpcAtomClient } from "./client"; type WsEventType = "open" | "message" | "close" | "error"; @@ -66,6 +70,7 @@ class MockWebSocket { } const originalWebSocket = globalThis.WebSocket; +const originalFetch = globalThis.fetch; function getSocket(): MockWebSocket { const socket = sockets.at(-1); @@ -112,6 +117,7 @@ beforeEach(() => { afterEach(() => { __resetWsRpcAtomClientForTests(); globalThis.WebSocket = originalWebSocket; + globalThis.fetch = originalFetch; vi.restoreAllMocks(); }); @@ -228,4 +234,46 @@ describe("WsRpcAtomClient", () => { release(); registry.dispose(); }); + + it("attaches distributed trace ids when client OTLP tracing is enabled", async () => { + await configureClientTracing({ + exportIntervalMs: 10, + }); + + const requestPromise = runRpc((client) => client(WS_METHODS.serverGetSettings, {})); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + socket.open(); + + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); + + const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { + id: string; + spanId?: string; + tag: string; + traceId?: string; + }; + expect(requestMessage.tag).toBe(WS_METHODS.serverGetSettings); + expect(requestMessage.traceId).toMatch(/^[0-9a-f]{32}$/); + expect(requestMessage.spanId).toMatch(/^[0-9a-f]{16}$/); + + socket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: requestMessage.id, + exit: { + _tag: "Success", + value: DEFAULT_SERVER_SETTINGS, + }, + }), + ); + + await expect(requestPromise).resolves.toEqual(DEFAULT_SERVER_SETTINGS); + }); }); diff --git a/apps/web/src/rpc/client.ts b/apps/web/src/rpc/client.ts index 117f7c0aaf..e4f9a6bbdd 100644 --- a/apps/web/src/rpc/client.ts +++ b/apps/web/src/rpc/client.ts @@ -2,6 +2,11 @@ import { WsRpcGroup } from "@t3tools/contracts"; import { Effect, Layer, ManagedRuntime } from "effect"; import { AtomRpc } from "effect/unstable/reactivity"; +import { + __resetClientTracingForTests, + ClientTracingLive, + configureClientTracing, +} from "../observability/clientTracing"; import { createWsRpcProtocolLayer } from "./protocol"; export class WsRpcAtomClient extends AtomRpc.Service()("WsRpcAtomClient", { @@ -16,18 +21,22 @@ function getRuntime() { return sharedRuntime; } - sharedRuntime = ManagedRuntime.make(WsRpcAtomClient.layer); + sharedRuntime = ManagedRuntime.make(Layer.mergeAll(WsRpcAtomClient.layer, ClientTracingLive)); return sharedRuntime; } export function runRpc( execute: (client: typeof WsRpcAtomClient.Service) => Effect.Effect, ): Promise { - return getRuntime().runPromise(WsRpcAtomClient.use(execute)); + return configureClientTracing().then(() => { + const runtime = getRuntime(); + return runtime.runPromise(WsRpcAtomClient.use(execute)); + }); } export async function __resetWsRpcAtomClientForTests() { const runtime = sharedRuntime; sharedRuntime = null; await runtime?.dispose(); + await __resetClientTracingForTests(); } diff --git a/apps/web/src/rpc/protocol.ts b/apps/web/src/rpc/protocol.ts index 38012e507d..fc5ab9097f 100644 --- a/apps/web/src/rpc/protocol.ts +++ b/apps/web/src/rpc/protocol.ts @@ -1,9 +1,22 @@ import { WsRpcGroup } from "@t3tools/contracts"; -import { Effect, Layer } from "effect"; +import { Duration, Effect, Layer, Schedule } from "effect"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; import * as Socket from "effect/unstable/socket/Socket"; import { resolveServerUrl } from "../lib/utils"; +import { + acknowledgeRpcRequest, + clearAllTrackedRpcRequests, + trackRpcRequestSent, +} from "./requestLatencyState"; +import { + getWsReconnectDelayMsForRetry, + recordWsConnectionAttempt, + recordWsConnectionClosed, + recordWsConnectionErrored, + recordWsConnectionOpened, + WS_RECONNECT_MAX_RETRIES, +} from "./wsConnectionState"; export const makeWsRpcProtocolClient = RpcClient.make(WsRpcGroup); @@ -17,11 +30,75 @@ export function createWsRpcProtocolLayer(url?: string) { protocol: window.location.protocol === "https:" ? "wss" : "ws", pathname: "/ws", }); + const trackingWebSocketConstructorLayer = Layer.succeed( + Socket.WebSocketConstructor, + (socketUrl, protocols) => { + recordWsConnectionAttempt(socketUrl); + const socket = new globalThis.WebSocket(socketUrl, protocols); + + socket.addEventListener( + "open", + () => { + recordWsConnectionOpened(); + }, + { once: true }, + ); + socket.addEventListener( + "error", + () => { + clearAllTrackedRpcRequests(); + recordWsConnectionErrored("Unable to connect to the T3 server WebSocket."); + }, + { once: true }, + ); + socket.addEventListener( + "close", + (event) => { + clearAllTrackedRpcRequests(); + recordWsConnectionClosed({ + code: event.code, + reason: event.reason, + }); + }, + { once: true }, + ); + + return socket; + }, + ); const socketLayer = Socket.layerWebSocket(resolvedUrl).pipe( - Layer.provide(Socket.layerWebSocketConstructorGlobal), + Layer.provide(trackingWebSocketConstructorLayer), + ); + const retryPolicy = Schedule.addDelay(Schedule.recurs(WS_RECONNECT_MAX_RETRIES), (retryCount) => + Effect.succeed(Duration.millis(getWsReconnectDelayMsForRetry(retryCount) ?? 0)), + ); + const protocolLayer = Layer.effect( + RpcClient.Protocol, + Effect.map( + RpcClient.makeProtocolSocket({ + retryPolicy, + retryTransientErrors: true, + }), + (protocol) => ({ + ...protocol, + run: (writeResponse) => + protocol.run((response) => { + if (response._tag === "Chunk" || response._tag === "Exit") { + acknowledgeRpcRequest(response.requestId); + } else if (response._tag === "ClientProtocolError" || response._tag === "Defect") { + clearAllTrackedRpcRequests(); + } + return writeResponse(response); + }), + send: (request, transferables) => { + if (request._tag === "Request") { + trackRpcRequestSent(request.id, request.tag); + } + return protocol.send(request, transferables); + }, + }), + ), ); - return RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe( - Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson)), - ); + return protocolLayer.pipe(Layer.provide(Layer.mergeAll(socketLayer, RpcSerialization.layerJson))); } diff --git a/apps/web/src/rpc/requestLatencyState.test.ts b/apps/web/src/rpc/requestLatencyState.test.ts new file mode 100644 index 0000000000..ac83c3b265 --- /dev/null +++ b/apps/web/src/rpc/requestLatencyState.test.ts @@ -0,0 +1,65 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + acknowledgeRpcRequest, + getSlowRpcAckRequests, + resetRequestLatencyStateForTests, + trackRpcRequestSent, + SLOW_RPC_ACK_THRESHOLD_MS, + MAX_TRACKED_RPC_ACK_REQUESTS, +} from "./requestLatencyState"; + +describe("requestLatencyState", () => { + beforeEach(() => { + vi.useFakeTimers(); + resetRequestLatencyStateForTests(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("marks unary requests as slow when the ack threshold is exceeded", () => { + trackRpcRequestSent("1", "server.getConfig"); + vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS - 1); + expect(getSlowRpcAckRequests()).toEqual([]); + + vi.advanceTimersByTime(1); + expect(getSlowRpcAckRequests()).toMatchObject([ + { + requestId: "1", + tag: "server.getConfig", + thresholdMs: SLOW_RPC_ACK_THRESHOLD_MS, + }, + ]); + }); + + it("clears the slow request once the server acknowledges it", () => { + trackRpcRequestSent("1", "git.status"); + vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS); + expect(getSlowRpcAckRequests()).toHaveLength(1); + + acknowledgeRpcRequest("1"); + expect(getSlowRpcAckRequests()).toEqual([]); + }); + + it("ignores long-lived subscribe requests", () => { + trackRpcRequestSent("1", "subscribeServerConfig"); + vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS * 2); + + expect(getSlowRpcAckRequests()).toEqual([]); + }); + + it("evicts the oldest pending requests once the tracker reaches capacity", () => { + for (let index = 0; index < MAX_TRACKED_RPC_ACK_REQUESTS + 1; index += 1) { + trackRpcRequestSent(String(index), "server.getConfig"); + } + + vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS); + + const slowRequests = getSlowRpcAckRequests(); + expect(slowRequests).toHaveLength(MAX_TRACKED_RPC_ACK_REQUESTS); + expect(slowRequests[0]?.requestId).toBe("1"); + expect(slowRequests.at(-1)?.requestId).toBe(String(MAX_TRACKED_RPC_ACK_REQUESTS)); + }); +}); diff --git a/apps/web/src/rpc/requestLatencyState.ts b/apps/web/src/rpc/requestLatencyState.ts new file mode 100644 index 0000000000..01c59ea0d5 --- /dev/null +++ b/apps/web/src/rpc/requestLatencyState.ts @@ -0,0 +1,127 @@ +import { useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/unstable/reactivity"; + +import { appAtomRegistry } from "./atomRegistry"; + +export const SLOW_RPC_ACK_THRESHOLD_MS = 2_500; +export const MAX_TRACKED_RPC_ACK_REQUESTS = 256; + +export interface SlowRpcAckRequest { + readonly requestId: string; + readonly startedAt: string; + readonly startedAtMs: number; + readonly tag: string; + readonly thresholdMs: number; +} + +interface PendingRpcAckRequest { + readonly request: SlowRpcAckRequest; + readonly timeoutId: ReturnType; +} + +const pendingRpcAckRequests = new Map(); + +const slowRpcAckRequestsAtom = Atom.make>([]).pipe( + Atom.keepAlive, + Atom.withLabel("slow-rpc-ack-requests"), +); + +function setSlowRpcAckRequests(requests: ReadonlyArray) { + appAtomRegistry.set(slowRpcAckRequestsAtom, [...requests]); +} + +function getSlowRpcAckRequestsValue(): ReadonlyArray { + return appAtomRegistry.get(slowRpcAckRequestsAtom); +} + +function shouldTrackRpcAck(tag: string): boolean { + return !tag.startsWith("subscribe"); +} + +export function getSlowRpcAckRequests(): ReadonlyArray { + return getSlowRpcAckRequestsValue(); +} + +export function trackRpcRequestSent(requestId: string, tag: string): void { + if (!shouldTrackRpcAck(tag)) { + return; + } + + clearTrackedRpcRequest(requestId); + evictOldestPendingRpcRequestIfNeeded(); + + const startedAtMs = Date.now(); + const request: SlowRpcAckRequest = { + requestId, + startedAt: new Date(startedAtMs).toISOString(), + startedAtMs, + tag, + thresholdMs: SLOW_RPC_ACK_THRESHOLD_MS, + }; + const timeoutId = setTimeout(() => { + pendingRpcAckRequests.delete(requestId); + appendSlowRpcAckRequest(request); + }, SLOW_RPC_ACK_THRESHOLD_MS); + + pendingRpcAckRequests.set(requestId, { + request, + timeoutId, + }); +} + +export function acknowledgeRpcRequest(requestId: string): void { + clearTrackedRpcRequest(requestId); + const slowRequests = getSlowRpcAckRequestsValue(); + if (!slowRequests.some((request) => request.requestId === requestId)) { + return; + } + + setSlowRpcAckRequests(slowRequests.filter((request) => request.requestId !== requestId)); +} + +export function clearAllTrackedRpcRequests(): void { + for (const pending of pendingRpcAckRequests.values()) { + clearTimeout(pending.timeoutId); + } + pendingRpcAckRequests.clear(); + setSlowRpcAckRequests([]); +} + +function clearTrackedRpcRequest(requestId: string): void { + const pending = pendingRpcAckRequests.get(requestId); + if (!pending) { + return; + } + + clearTimeout(pending.timeoutId); + pendingRpcAckRequests.delete(requestId); +} + +function appendSlowRpcAckRequest(request: SlowRpcAckRequest): void { + const requests = [...getSlowRpcAckRequestsValue(), request]; + if (requests.length <= MAX_TRACKED_RPC_ACK_REQUESTS) { + setSlowRpcAckRequests(requests); + return; + } + + setSlowRpcAckRequests(requests.slice(-MAX_TRACKED_RPC_ACK_REQUESTS)); +} + +function evictOldestPendingRpcRequestIfNeeded(): void { + while (pendingRpcAckRequests.size >= MAX_TRACKED_RPC_ACK_REQUESTS) { + const oldestRequestId = pendingRpcAckRequests.keys().next().value; + if (oldestRequestId === undefined) { + return; + } + + clearTrackedRpcRequest(oldestRequestId); + } +} + +export function resetRequestLatencyStateForTests(): void { + clearAllTrackedRpcRequests(); +} + +export function useSlowRpcAckRequests(): ReadonlyArray { + return useAtomValue(slowRpcAckRequestsAtom); +} diff --git a/apps/web/src/rpc/serverState.test.ts b/apps/web/src/rpc/serverState.test.ts index 8da5846fe6..721ce25fb5 100644 --- a/apps/web/src/rpc/serverState.test.ts +++ b/apps/web/src/rpc/serverState.test.ts @@ -57,6 +57,12 @@ const baseServerConfig: ServerConfig = { issues: [], providers: defaultProviders, availableEditors: ["cursor"], + observability: { + logsDirectoryPath: "/tmp/workspace/.config/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, settings: DEFAULT_SERVER_SETTINGS, }; diff --git a/apps/web/src/rpc/serverState.ts b/apps/web/src/rpc/serverState.ts index 2a69394062..3e8dbab28c 100644 --- a/apps/web/src/rpc/serverState.ts +++ b/apps/web/src/rpc/serverState.ts @@ -50,6 +50,7 @@ const selectAvailableEditors = (config: ServerConfig | null): ReadonlyArray config?.keybindings ?? EMPTY_KEYBINDINGS; const selectKeybindingsConfigPath = (config: ServerConfig | null) => config?.keybindingsConfigPath ?? null; +const selectObservability = (config: ServerConfig | null) => config?.observability ?? null; const selectProviders = (config: ServerConfig | null) => config?.providers ?? EMPTY_SERVER_PROVIDERS; const selectSettings = (config: ServerConfig | null): ServerSettings => @@ -281,6 +282,10 @@ export function useServerKeybindingsConfigPath(): string | null { return useAtomValue(serverConfigAtom, selectKeybindingsConfigPath); } +export function useServerObservability(): ServerConfig["observability"] | null { + return useAtomValue(serverConfigAtom, selectObservability); +} + export function useServerWelcomeSubscription( listener: (payload: ServerLifecycleWelcomePayload) => void, ): void { diff --git a/apps/web/src/rpc/transportError.test.ts b/apps/web/src/rpc/transportError.test.ts new file mode 100644 index 0000000000..f9da05abbc --- /dev/null +++ b/apps/web/src/rpc/transportError.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; + +import { isTransportConnectionErrorMessage, sanitizeThreadErrorMessage } from "./transportError"; + +describe("transportError", () => { + it("detects websocket transport failures", () => { + expect(isTransportConnectionErrorMessage("SocketCloseError: 1006")).toBe(true); + expect(isTransportConnectionErrorMessage("Unable to connect to the T3 server WebSocket.")).toBe( + true, + ); + expect(isTransportConnectionErrorMessage("SocketOpenError: Timeout")).toBe(true); + }); + + it("preserves non-transport thread errors", () => { + expect(sanitizeThreadErrorMessage("Turn failed")).toBe("Turn failed"); + expect(sanitizeThreadErrorMessage("Select a base branch before sending.")).toBe( + "Select a base branch before sending.", + ); + }); + + it("drops transport failures from thread surfaces", () => { + expect(sanitizeThreadErrorMessage("SocketCloseError: 1006")).toBeNull(); + }); +}); diff --git a/apps/web/src/rpc/transportError.ts b/apps/web/src/rpc/transportError.ts new file mode 100644 index 0000000000..edc90a5a3c --- /dev/null +++ b/apps/web/src/rpc/transportError.ts @@ -0,0 +1,23 @@ +const TRANSPORT_ERROR_PATTERNS = [ + /\bSocketCloseError\b/i, + /\bSocketOpenError\b/i, + /Unable to connect to the T3 server WebSocket\./i, + /\bping timeout\b/i, +] as const; + +export function isTransportConnectionErrorMessage(message: string | null | undefined): boolean { + if (typeof message !== "string") { + return false; + } + + const normalizedMessage = message.trim(); + if (normalizedMessage.length === 0) { + return false; + } + + return TRANSPORT_ERROR_PATTERNS.some((pattern) => pattern.test(normalizedMessage)); +} + +export function sanitizeThreadErrorMessage(message: string | null | undefined): string | null { + return isTransportConnectionErrorMessage(message) ? null : (message ?? null); +} diff --git a/apps/web/src/rpc/wsConnectionState.test.ts b/apps/web/src/rpc/wsConnectionState.test.ts new file mode 100644 index 0000000000..f4e8689a58 --- /dev/null +++ b/apps/web/src/rpc/wsConnectionState.test.ts @@ -0,0 +1,112 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { + exhaustWsReconnectIfStillWaiting, + getWsConnectionStatus, + getWsReconnectDelayMsForRetry, + getWsConnectionUiState, + recordWsConnectionAttempt, + recordWsConnectionClosed, + recordWsConnectionErrored, + recordWsConnectionOpened, + resetWsConnectionStateForTests, + setBrowserOnlineStatus, + WS_RECONNECT_MAX_ATTEMPTS, +} from "./wsConnectionState"; + +describe("wsConnectionState", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-04-03T20:30:00.000Z")); + resetWsConnectionStateForTests(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("treats a disconnected browser as offline once the websocket drops", () => { + recordWsConnectionAttempt("ws://localhost:3020/ws"); + recordWsConnectionOpened(); + recordWsConnectionClosed({ code: 1006, reason: "offline" }); + setBrowserOnlineStatus(false); + + expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("offline"); + }); + + it("stays in the initial connecting state until the first disconnect", () => { + recordWsConnectionAttempt("ws://localhost:3020/ws"); + + expect(getWsConnectionStatus()).toMatchObject({ + attemptCount: 1, + hasConnected: false, + phase: "connecting", + }); + expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("connecting"); + }); + + it("schedules the next retry after a failed websocket attempt", () => { + recordWsConnectionAttempt("ws://localhost:3020/ws"); + recordWsConnectionErrored("Unable to connect to the T3 server WebSocket."); + + const firstRetryDelayMs = getWsReconnectDelayMsForRetry(0); + if (firstRetryDelayMs === null) { + throw new Error("Expected an initial retry delay."); + } + + expect(getWsConnectionStatus()).toMatchObject({ + nextRetryAt: new Date(Date.now() + firstRetryDelayMs).toISOString(), + reconnectAttemptCount: 1, + reconnectPhase: "waiting", + }); + }); + + it("marks the reconnect cycle as exhausted after the final attempt fails", () => { + for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS; attempt += 1) { + recordWsConnectionAttempt("ws://localhost:3020/ws"); + recordWsConnectionErrored("Unable to connect to the T3 server WebSocket."); + } + + expect(getWsConnectionStatus()).toMatchObject({ + nextRetryAt: null, + reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS, + reconnectPhase: "exhausted", + }); + }); + + it("can exhaust a stalled final retry window when no new attempt starts", () => { + recordWsConnectionAttempt("ws://localhost:3020/ws"); + recordWsConnectionOpened(); + + for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS - 1; attempt += 1) { + recordWsConnectionAttempt("ws://localhost:3020/ws"); + recordWsConnectionErrored("Unable to connect to the T3 server WebSocket."); + } + + const finalRetryDelayMs = getWsReconnectDelayMsForRetry(WS_RECONNECT_MAX_ATTEMPTS - 2); + if (finalRetryDelayMs === null) { + throw new Error("Expected a final retry delay."); + } + + const statusBeforeExhaust = getWsConnectionStatus(); + expect(statusBeforeExhaust).toMatchObject({ + nextRetryAt: new Date(Date.now() + finalRetryDelayMs).toISOString(), + reconnectAttemptCount: 7, + reconnectPhase: "waiting", + }); + + const nextRetryAt = statusBeforeExhaust.nextRetryAt; + if (!nextRetryAt) { + throw new Error("Expected a scheduled retry."); + } + + vi.setSystemTime(new Date(Date.now() + finalRetryDelayMs + 1_000)); + exhaustWsReconnectIfStillWaiting(nextRetryAt); + + expect(getWsConnectionStatus()).toMatchObject({ + nextRetryAt: null, + reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS, + reconnectPhase: "exhausted", + }); + }); +}); diff --git a/apps/web/src/rpc/wsConnectionState.ts b/apps/web/src/rpc/wsConnectionState.ts new file mode 100644 index 0000000000..5020a1c453 --- /dev/null +++ b/apps/web/src/rpc/wsConnectionState.ts @@ -0,0 +1,219 @@ +import { useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/unstable/reactivity"; + +import { appAtomRegistry } from "./atomRegistry"; + +export type WsConnectionUiState = "connected" | "connecting" | "error" | "offline" | "reconnecting"; +export type WsReconnectPhase = "attempting" | "exhausted" | "idle" | "waiting"; + +export const WS_RECONNECT_INITIAL_DELAY_MS = 1_000; +export const WS_RECONNECT_BACKOFF_FACTOR = 2; +export const WS_RECONNECT_MAX_DELAY_MS = 64_000; +export const WS_RECONNECT_MAX_RETRIES = 7; +export const WS_RECONNECT_MAX_ATTEMPTS = WS_RECONNECT_MAX_RETRIES + 1; + +export interface WsConnectionStatus { + readonly attemptCount: number; + readonly closeCode: number | null; + readonly closeReason: string | null; + readonly connectedAt: string | null; + readonly disconnectedAt: string | null; + readonly hasConnected: boolean; + readonly lastError: string | null; + readonly lastErrorAt: string | null; + readonly nextRetryAt: string | null; + readonly online: boolean; + readonly phase: "idle" | "connecting" | "connected" | "disconnected"; + readonly reconnectAttemptCount: number; + readonly reconnectMaxAttempts: number; + readonly reconnectPhase: WsReconnectPhase; + readonly socketUrl: string | null; +} + +const INITIAL_WS_CONNECTION_STATUS = Object.freeze({ + attemptCount: 0, + closeCode: null, + closeReason: null, + connectedAt: null, + disconnectedAt: null, + hasConnected: false, + lastError: null, + lastErrorAt: null, + nextRetryAt: null, + online: typeof navigator === "undefined" ? true : navigator.onLine !== false, + phase: "idle", + reconnectAttemptCount: 0, + reconnectMaxAttempts: WS_RECONNECT_MAX_ATTEMPTS, + reconnectPhase: "idle", + socketUrl: null, +}); + +export const wsConnectionStatusAtom = Atom.make(INITIAL_WS_CONNECTION_STATUS).pipe( + Atom.keepAlive, + Atom.withLabel("ws-connection-status"), +); + +function isoNow() { + return new Date().toISOString(); +} + +function updateWsConnectionStatus( + updater: (current: WsConnectionStatus) => WsConnectionStatus, +): WsConnectionStatus { + const nextStatus = updater(getWsConnectionStatus()); + appAtomRegistry.set(wsConnectionStatusAtom, nextStatus); + return nextStatus; +} + +export function getWsConnectionStatus(): WsConnectionStatus { + return appAtomRegistry.get(wsConnectionStatusAtom); +} + +export function getWsConnectionUiState(status: WsConnectionStatus): WsConnectionUiState { + if (status.phase === "connected") { + return "connected"; + } + + if (!status.online && (status.disconnectedAt !== null || status.phase === "disconnected")) { + return "offline"; + } + + if (!status.hasConnected) { + return status.phase === "disconnected" ? "error" : "connecting"; + } + + return "reconnecting"; +} + +export function recordWsConnectionAttempt(socketUrl: string): WsConnectionStatus { + return updateWsConnectionStatus((current) => ({ + ...current, + attemptCount: current.attemptCount + 1, + nextRetryAt: null, + phase: "connecting", + reconnectAttemptCount: current.phase === "connected" ? 1 : current.reconnectAttemptCount + 1, + reconnectPhase: "attempting", + socketUrl, + })); +} + +export function recordWsConnectionOpened(): WsConnectionStatus { + return updateWsConnectionStatus((current) => ({ + ...current, + closeCode: null, + closeReason: null, + connectedAt: isoNow(), + disconnectedAt: null, + hasConnected: true, + nextRetryAt: null, + phase: "connected", + reconnectAttemptCount: 0, + reconnectPhase: "idle", + })); +} + +export function recordWsConnectionErrored(message?: string | null): WsConnectionStatus { + return updateWsConnectionStatus((current) => + applyDisconnectState(current, { + lastError: message?.trim() ? message : current.lastError, + lastErrorAt: isoNow(), + }), + ); +} + +export function recordWsConnectionClosed(details?: { + readonly code?: number; + readonly reason?: string; +}): WsConnectionStatus { + return updateWsConnectionStatus((current) => + applyDisconnectState(current, { + closeCode: details?.code ?? current.closeCode, + closeReason: details?.reason?.trim() ? details.reason : current.closeReason, + }), + ); +} + +export function setBrowserOnlineStatus(online: boolean): WsConnectionStatus { + return updateWsConnectionStatus((current) => ({ + ...current, + online, + })); +} + +export function resetWsReconnectBackoff(): WsConnectionStatus { + return updateWsConnectionStatus((current) => ({ + ...current, + nextRetryAt: null, + reconnectAttemptCount: 0, + reconnectPhase: "idle", + })); +} + +export function exhaustWsReconnectIfStillWaiting(expectedNextRetryAt: string): WsConnectionStatus { + return updateWsConnectionStatus((current) => { + if ( + current.reconnectPhase !== "waiting" || + current.nextRetryAt !== expectedNextRetryAt || + !current.online || + !current.hasConnected + ) { + return current; + } + + return { + ...current, + nextRetryAt: null, + reconnectAttemptCount: current.reconnectMaxAttempts, + reconnectPhase: "exhausted", + }; + }); +} + +export function resetWsConnectionStateForTests(): void { + appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS); +} + +export function useWsConnectionStatus(): WsConnectionStatus { + return useAtomValue(wsConnectionStatusAtom); +} + +export function getWsReconnectDelayMsForRetry(retryIndex: number): number | null { + if (!Number.isInteger(retryIndex) || retryIndex < 0 || retryIndex >= WS_RECONNECT_MAX_RETRIES) { + return null; + } + + return Math.min( + Math.round(WS_RECONNECT_INITIAL_DELAY_MS * WS_RECONNECT_BACKOFF_FACTOR ** retryIndex), + WS_RECONNECT_MAX_DELAY_MS, + ); +} + +function applyDisconnectState( + current: WsConnectionStatus, + updates: Partial< + Pick + >, +): WsConnectionStatus { + const disconnectedAt = current.disconnectedAt ?? isoNow(); + const nextRetryDelayMs = + current.nextRetryAt !== null || current.reconnectPhase === "exhausted" + ? null + : getWsReconnectDelayMsForRetry(Math.max(0, current.reconnectAttemptCount - 1)); + + return { + ...current, + ...updates, + disconnectedAt, + nextRetryAt: + nextRetryDelayMs === null + ? current.nextRetryAt + : new Date(Date.now() + nextRetryDelayMs).toISOString(), + phase: "disconnected", + reconnectPhase: + current.reconnectPhase === "waiting" || current.reconnectPhase === "exhausted" + ? current.reconnectPhase + : nextRetryDelayMs === null + ? "exhausted" + : "waiting", + }; +} diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index bc1b69841d..e05c3b5e93 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -20,7 +20,6 @@ import { findSidebarProposedPlan, hasActionableProposedPlan, hasToolActivityForTurn, - isSessionActivelyRunningTurn, isLatestTurnSettled, } from "./session-logic"; @@ -1073,30 +1072,15 @@ describe("isLatestTurnSettled", () => { } as const; it("returns false while the same turn is still active in a running session", () => { - expect( - isLatestTurnSettled( - { - ...latestTurn, - completedAt: null, - }, - { - orchestrationStatus: "running", - activeTurnId: TurnId.makeUnsafe("turn-1"), - }, - ), - ).toBe(false); - }); - - it("returns true when the turn completed but the session status stayed stale-running", () => { expect( isLatestTurnSettled(latestTurn, { orchestrationStatus: "running", activeTurnId: TurnId.makeUnsafe("turn-1"), }), - ).toBe(true); + ).toBe(false); }); - it("returns false while a different turn is still running", () => { + it("returns false while any turn is running to avoid stale latest-turn banners", () => { expect( isLatestTurnSettled(latestTurn, { orchestrationStatus: "running", @@ -1128,56 +1112,6 @@ describe("isLatestTurnSettled", () => { }); }); -describe("isSessionActivelyRunningTurn", () => { - const completedTurn = { - turnId: TurnId.makeUnsafe("turn-1"), - startedAt: "2026-02-27T21:10:00.000Z", - completedAt: "2026-02-27T21:10:06.000Z", - } as const; - - it("returns true when the current turn has not completed yet", () => { - expect( - isSessionActivelyRunningTurn( - { - ...completedTurn, - completedAt: null, - }, - { - orchestrationStatus: "running", - activeTurnId: TurnId.makeUnsafe("turn-1"), - }, - ), - ).toBe(true); - }); - - it("returns false when the same turn already completed and only the session is stale", () => { - expect( - isSessionActivelyRunningTurn(completedTurn, { - orchestrationStatus: "running", - activeTurnId: TurnId.makeUnsafe("turn-1"), - }), - ).toBe(false); - }); - - it("returns true when a different turn is still active", () => { - expect( - isSessionActivelyRunningTurn(completedTurn, { - orchestrationStatus: "running", - activeTurnId: TurnId.makeUnsafe("turn-2"), - }), - ).toBe(true); - }); - - it("returns false when the session is not running", () => { - expect( - isSessionActivelyRunningTurn(completedTurn, { - orchestrationStatus: "ready", - activeTurnId: undefined, - }), - ).toBe(false); - }); -}); - describe("deriveActiveWorkStartedAt", () => { const latestTurn = { turnId: TurnId.makeUnsafe("turn-1"), @@ -1186,22 +1120,6 @@ describe("deriveActiveWorkStartedAt", () => { } as const; it("prefers the in-flight turn start when the latest turn is not settled", () => { - expect( - deriveActiveWorkStartedAt( - { - ...latestTurn, - completedAt: null, - }, - { - orchestrationStatus: "running", - activeTurnId: TurnId.makeUnsafe("turn-1"), - }, - "2026-02-27T21:11:00.000Z", - ), - ).toBe("2026-02-27T21:10:00.000Z"); - }); - - it("falls back to sendStartedAt when only the session status is stale-running", () => { expect( deriveActiveWorkStartedAt( latestTurn, @@ -1211,7 +1129,7 @@ describe("deriveActiveWorkStartedAt", () => { }, "2026-02-27T21:11:00.000Z", ), - ).toBe("2026-02-27T21:11:00.000Z"); + ).toBe("2026-02-27T21:10:00.000Z"); }); it("falls back to sendStartedAt once the latest turn is settled", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 90d8da8208..fc33827014 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -128,30 +128,15 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str type LatestTurnTiming = Pick; type SessionActivityState = Pick; -export function isSessionActivelyRunningTurn( - latestTurn: LatestTurnTiming | null, - session: SessionActivityState | null, -): boolean { - if (!session || session.orchestrationStatus !== "running") return false; - if (!latestTurn) return true; - - const activeTurnId = session.activeTurnId; - if (activeTurnId === undefined) { - return latestTurn.completedAt === null; - } - if (latestTurn.turnId !== activeTurnId) { - return true; - } - return latestTurn.completedAt === null; -} - export function isLatestTurnSettled( latestTurn: LatestTurnTiming | null, session: SessionActivityState | null, ): boolean { if (!latestTurn?.startedAt) return false; if (!latestTurn.completedAt) return false; - return !isSessionActivelyRunningTurn(latestTurn, session); + if (!session) return true; + if (session.orchestrationStatus === "running") return false; + return true; } export function deriveActiveWorkStartedAt( diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 236050ba75..4fbb11942c 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -33,6 +33,7 @@ import { type ThreadTurnState, type TurnDiffSummary, } from "./types"; +import { sanitizeThreadErrorMessage } from "./rpc/transportError"; export interface AppState { projectIds: ProjectId[]; @@ -194,7 +195,7 @@ function mapThread(thread: OrchestrationThread): Thread { session: thread.session ? mapSession(thread.session) : null, messages: thread.messages.map(mapMessage), proposedPlans: thread.proposedPlans.map(mapProposedPlan), - error: thread.session?.lastError ?? null, + error: sanitizeThreadErrorMessage(thread.session?.lastError), createdAt: thread.createdAt, archivedAt: thread.archivedAt, updatedAt: thread.updatedAt, @@ -1293,7 +1294,7 @@ export function applyOrchestrationEvent(state: AppState, event: OrchestrationEve return updateThreadState(state, event.payload.threadId, (thread) => ({ ...thread, session: mapSession(event.payload.session), - error: event.payload.session.lastError ?? null, + error: sanitizeThreadErrorMessage(event.payload.session.lastError), latestTurn: event.payload.session.status === "running" && event.payload.session.activeTurnId !== null ? buildLatestTurn({ diff --git a/apps/web/src/terminalActivity.test.ts b/apps/web/src/terminalActivity.test.ts index 8fda326266..6f38dcbfcb 100644 --- a/apps/web/src/terminalActivity.test.ts +++ b/apps/web/src/terminalActivity.test.ts @@ -7,6 +7,7 @@ const snapshot: TerminalSessionSnapshot = { threadId: "thread-1", terminalId: "default", cwd: "/tmp", + worktreePath: null, status: "running", pid: 1234, history: "", diff --git a/apps/web/src/terminalStateStore.test.ts b/apps/web/src/terminalStateStore.test.ts index 071d30abc2..4ded76fba1 100644 --- a/apps/web/src/terminalStateStore.test.ts +++ b/apps/web/src/terminalStateStore.test.ts @@ -39,6 +39,7 @@ function makeTerminalEvent( threadId: THREAD_ID, terminalId: "default", cwd: "/tmp/workspace", + worktreePath: null, status: "running", pid: 123, history: "", @@ -56,6 +57,7 @@ describe("terminalStateStore actions", () => { useTerminalStateStore.persist.clearStorage(); useTerminalStateStore.setState({ terminalStateByThreadId: {}, + terminalLaunchContextByThreadId: {}, terminalEventEntriesByKey: {}, nextTerminalEventId: 1, }); @@ -132,6 +134,23 @@ describe("terminalStateStore actions", () => { ]); }); + it("ensures unknown server terminals are registered, opened, and activated", () => { + const store = useTerminalStateStore.getState(); + store.ensureTerminal(THREAD_ID, "setup-setup", { open: true, active: true }); + + const terminalState = selectThreadTerminalState( + useTerminalStateStore.getState().terminalStateByThreadId, + THREAD_ID, + ); + expect(terminalState.terminalOpen).toBe(true); + expect(terminalState.terminalIds).toEqual(["default", "setup-setup"]); + expect(terminalState.activeTerminalId).toBe("setup-setup"); + expect(terminalState.terminalGroups).toEqual([ + { id: "group-default", terminalIds: ["default"] }, + { id: "group-setup-setup", terminalIds: ["setup-setup"] }, + ]); + }); + it("allows unlimited groups while keeping each group capped at four terminals", () => { const store = useTerminalStateStore.getState(); store.splitTerminal(THREAD_ID, "terminal-2"); @@ -219,6 +238,84 @@ describe("terminalStateStore actions", () => { expect(entries.map((entry) => entry.event.type)).toEqual(["output", "activity"]); }); + it("applies started terminal events to terminal state, launch context, and event buffer", () => { + const store = useTerminalStateStore.getState(); + store.applyTerminalEvent( + makeTerminalEvent("started", { + terminalId: "setup-bootstrap", + snapshot: { + threadId: THREAD_ID, + terminalId: "setup-bootstrap", + cwd: "/tmp/worktree", + worktreePath: "/tmp/worktree", + status: "running", + pid: 123, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: "2026-04-02T20:00:00.000Z", + }, + }), + ); + + const terminalState = selectThreadTerminalState( + useTerminalStateStore.getState().terminalStateByThreadId, + THREAD_ID, + ); + const entries = selectTerminalEventEntries( + useTerminalStateStore.getState().terminalEventEntriesByKey, + THREAD_ID, + "setup-bootstrap", + ); + + expect(terminalState.terminalOpen).toBe(true); + expect(terminalState.activeTerminalId).toBe("setup-bootstrap"); + expect(terminalState.terminalIds).toEqual(["default", "setup-bootstrap"]); + expect(useTerminalStateStore.getState().terminalLaunchContextByThreadId[THREAD_ID]).toEqual({ + cwd: "/tmp/worktree", + worktreePath: "/tmp/worktree", + }); + expect(entries).toHaveLength(1); + expect(entries[0]?.event.type).toBe("started"); + }); + + it("applies activity and exited terminal events to subprocess state while buffering events", () => { + const store = useTerminalStateStore.getState(); + store.ensureTerminal(THREAD_ID, "terminal-2", { open: true, active: true }); + + store.applyTerminalEvent( + makeTerminalEvent("activity", { + terminalId: "terminal-2", + hasRunningSubprocess: true, + }), + ); + expect( + selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID) + .runningTerminalIds, + ).toEqual(["terminal-2"]); + + store.applyTerminalEvent( + makeTerminalEvent("exited", { + terminalId: "terminal-2", + exitCode: 0, + exitSignal: null, + }), + ); + + const terminalState = selectThreadTerminalState( + useTerminalStateStore.getState().terminalStateByThreadId, + THREAD_ID, + ); + const entries = selectTerminalEventEntries( + useTerminalStateStore.getState().terminalEventEntriesByKey, + THREAD_ID, + "terminal-2", + ); + + expect(terminalState.runningTerminalIds).toEqual([]); + expect(entries.map((entry) => entry.event.type)).toEqual(["activity", "exited"]); + }); + it("clears buffered terminal events when a thread terminal state is removed", () => { const store = useTerminalStateStore.getState(); store.recordTerminalEvent(makeTerminalEvent("output")); diff --git a/apps/web/src/terminalStateStore.ts b/apps/web/src/terminalStateStore.ts index cd17aa295f..7189e715a4 100644 --- a/apps/web/src/terminalStateStore.ts +++ b/apps/web/src/terminalStateStore.ts @@ -5,10 +5,11 @@ * API constrained to store actions/selectors. */ -import type { TerminalEvent, ThreadId } from "@t3tools/contracts"; +import { ThreadId, type TerminalEvent } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; import { resolveStorage } from "./lib/storage"; +import { terminalRunningSubprocessFromEvent } from "./terminalActivity"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -26,6 +27,11 @@ interface ThreadTerminalState { activeTerminalGroupId: string; } +export interface ThreadTerminalLaunchContext { + cwd: string; + worktreePath: string | null; +} + export interface TerminalEventEntry { id: number; event: TerminalEvent; @@ -245,6 +251,40 @@ function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[ })); } +function appendTerminalEventEntry( + terminalEventEntriesByKey: Record>, + nextTerminalEventId: number, + event: TerminalEvent, +) { + const key = terminalEventBufferKey(ThreadId.makeUnsafe(event.threadId), event.terminalId); + const currentEntries = terminalEventEntriesByKey[key] ?? EMPTY_TERMINAL_EVENT_ENTRIES; + const nextEntry: TerminalEventEntry = { + id: nextTerminalEventId, + event, + }; + const nextEntries = + currentEntries.length >= MAX_TERMINAL_EVENT_BUFFER + ? [...currentEntries.slice(1), nextEntry] + : [...currentEntries, nextEntry]; + + return { + terminalEventEntriesByKey: { + ...terminalEventEntriesByKey, + [key]: nextEntries, + }, + nextTerminalEventId: nextTerminalEventId + 1, + }; +} + +function launchContextFromStartEvent( + event: Extract, +): ThreadTerminalLaunchContext { + return { + cwd: event.snapshot.cwd, + worktreePath: event.snapshot.worktreePath, + }; +} + function upsertTerminalIntoGroups( state: ThreadTerminalState, terminalId: string, @@ -498,20 +538,29 @@ export function selectTerminalEventEntries( interface TerminalStateStoreState { terminalStateByThreadId: Record; + terminalLaunchContextByThreadId: Record; terminalEventEntriesByKey: Record>; nextTerminalEventId: number; setTerminalOpen: (threadId: ThreadId, open: boolean) => void; setTerminalHeight: (threadId: ThreadId, height: number) => void; splitTerminal: (threadId: ThreadId, terminalId: string) => void; newTerminal: (threadId: ThreadId, terminalId: string) => void; + ensureTerminal: ( + threadId: ThreadId, + terminalId: string, + options?: { open?: boolean; active?: boolean }, + ) => void; setActiveTerminal: (threadId: ThreadId, terminalId: string) => void; closeTerminal: (threadId: ThreadId, terminalId: string) => void; + setTerminalLaunchContext: (threadId: ThreadId, context: ThreadTerminalLaunchContext) => void; + clearTerminalLaunchContext: (threadId: ThreadId) => void; setTerminalActivity: ( threadId: ThreadId, terminalId: string, hasRunningSubprocess: boolean, ) => void; recordTerminalEvent: (event: TerminalEvent) => void; + applyTerminalEvent: (event: TerminalEvent) => void; clearTerminalState: (threadId: ThreadId) => void; removeTerminalState: (threadId: ThreadId) => void; removeOrphanedTerminalStates: (activeThreadIds: Set) => void; @@ -541,6 +590,7 @@ export const useTerminalStateStore = create()( return { terminalStateByThreadId: {}, + terminalLaunchContextByThreadId: {}, terminalEventEntriesByKey: {}, nextTerminalEventId: 1, setTerminalOpen: (threadId, open) => @@ -551,33 +601,104 @@ export const useTerminalStateStore = create()( updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)), newTerminal: (threadId, terminalId) => updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)), + ensureTerminal: (threadId, terminalId, options) => + updateTerminal(threadId, (state) => { + let nextState = state; + if (!state.terminalIds.includes(terminalId)) { + nextState = newThreadTerminal(nextState, terminalId); + } + if (options?.active === false) { + nextState = { + ...nextState, + activeTerminalId: state.activeTerminalId, + activeTerminalGroupId: state.activeTerminalGroupId, + }; + } + if (options?.active ?? true) { + nextState = setThreadActiveTerminal(nextState, terminalId); + } + if (options?.open) { + nextState = setThreadTerminalOpen(nextState, true); + } + return normalizeThreadTerminalState(nextState); + }), setActiveTerminal: (threadId, terminalId) => updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)), closeTerminal: (threadId, terminalId) => updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)), + setTerminalLaunchContext: (threadId, context) => + set((state) => ({ + terminalLaunchContextByThreadId: { + ...state.terminalLaunchContextByThreadId, + [threadId]: context, + }, + })), + clearTerminalLaunchContext: (threadId) => + set((state) => { + if (!state.terminalLaunchContextByThreadId[threadId]) { + return state; + } + const { [threadId]: _removed, ...rest } = state.terminalLaunchContextByThreadId; + return { terminalLaunchContextByThreadId: rest }; + }), setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) => updateTerminal(threadId, (state) => setThreadTerminalActivity(state, terminalId, hasRunningSubprocess), ), recordTerminalEvent: (event) => - set((state) => { - const key = terminalEventBufferKey(event.threadId as ThreadId, event.terminalId); - const currentEntries = - state.terminalEventEntriesByKey[key] ?? EMPTY_TERMINAL_EVENT_ENTRIES; - const nextEntry: TerminalEventEntry = { - id: state.nextTerminalEventId, + set((state) => + appendTerminalEventEntry( + state.terminalEventEntriesByKey, + state.nextTerminalEventId, event, - }; - const nextEntries = - currentEntries.length >= MAX_TERMINAL_EVENT_BUFFER - ? [...currentEntries.slice(1), nextEntry] - : [...currentEntries, nextEntry]; + ), + ), + applyTerminalEvent: (event) => + set((state) => { + const threadId = ThreadId.makeUnsafe(event.threadId); + let nextTerminalStateByThreadId = state.terminalStateByThreadId; + let nextTerminalLaunchContextByThreadId = state.terminalLaunchContextByThreadId; + + if (event.type === "started" || event.type === "restarted") { + nextTerminalStateByThreadId = updateTerminalStateByThreadId( + nextTerminalStateByThreadId, + threadId, + (current) => { + let nextState = current; + if (!current.terminalIds.includes(event.terminalId)) { + nextState = newThreadTerminal(nextState, event.terminalId); + } + nextState = setThreadActiveTerminal(nextState, event.terminalId); + nextState = setThreadTerminalOpen(nextState, true); + return normalizeThreadTerminalState(nextState); + }, + ); + nextTerminalLaunchContextByThreadId = { + ...nextTerminalLaunchContextByThreadId, + [threadId]: launchContextFromStartEvent(event), + }; + } + + const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event); + if (hasRunningSubprocess !== null) { + nextTerminalStateByThreadId = updateTerminalStateByThreadId( + nextTerminalStateByThreadId, + threadId, + (current) => + setThreadTerminalActivity(current, event.terminalId, hasRunningSubprocess), + ); + } + + const nextEventState = appendTerminalEventEntry( + state.terminalEventEntriesByKey, + state.nextTerminalEventId, + event, + ); + return { - terminalEventEntriesByKey: { - ...state.terminalEventEntriesByKey, - [key]: nextEntries, - }, - nextTerminalEventId: state.nextTerminalEventId + 1, + terminalStateByThreadId: nextTerminalStateByThreadId, + terminalLaunchContextByThreadId: nextTerminalLaunchContextByThreadId, + ...nextEventState, }; }), clearTerminalState: (threadId) => @@ -587,6 +708,9 @@ export const useTerminalStateStore = create()( threadId, () => createDefaultThreadTerminalState(), ); + const hadLaunchContext = state.terminalLaunchContextByThreadId[threadId] !== undefined; + const { [threadId]: _removed, ...remainingLaunchContexts } = + state.terminalLaunchContextByThreadId; const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey }; let removedEventEntries = false; for (const key of Object.keys(nextTerminalEventEntriesByKey)) { @@ -597,18 +721,21 @@ export const useTerminalStateStore = create()( } if ( nextTerminalStateByThreadId === state.terminalStateByThreadId && + !hadLaunchContext && !removedEventEntries ) { return state; } return { terminalStateByThreadId: nextTerminalStateByThreadId, + terminalLaunchContextByThreadId: remainingLaunchContexts, terminalEventEntriesByKey: nextTerminalEventEntriesByKey, }; }), removeTerminalState: (threadId) => set((state) => { - const hasThreadState = state.terminalStateByThreadId[threadId] !== undefined; + const hadTerminalState = state.terminalStateByThreadId[threadId] !== undefined; + const hadLaunchContext = state.terminalLaunchContextByThreadId[threadId] !== undefined; const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey }; let removedEventEntries = false; for (const key of Object.keys(nextTerminalEventEntriesByKey)) { @@ -617,13 +744,16 @@ export const useTerminalStateStore = create()( removedEventEntries = true; } } - if (!hasThreadState && !removedEventEntries) { + if (!hadTerminalState && !hadLaunchContext && !removedEventEntries) { return state; } - const next = { ...state.terminalStateByThreadId }; - delete next[threadId]; + const nextTerminalStateByThreadId = { ...state.terminalStateByThreadId }; + delete nextTerminalStateByThreadId[threadId]; + const nextLaunchContexts = { ...state.terminalLaunchContextByThreadId }; + delete nextLaunchContexts[threadId]; return { - terminalStateByThreadId: next, + terminalStateByThreadId: nextTerminalStateByThreadId, + terminalLaunchContextByThreadId: nextLaunchContexts, terminalEventEntriesByKey: nextTerminalEventEntriesByKey, }; }), @@ -632,6 +762,9 @@ export const useTerminalStateStore = create()( const orphanedIds = Object.keys(state.terminalStateByThreadId).filter( (id) => !activeThreadIds.has(id as ThreadId), ); + const orphanedLaunchContextIds = Object.keys( + state.terminalLaunchContextByThreadId, + ).filter((id) => !activeThreadIds.has(id as ThreadId)); const nextTerminalEventEntriesByKey = { ...state.terminalEventEntriesByKey }; let removedEventEntries = false; for (const key of Object.keys(nextTerminalEventEntriesByKey)) { @@ -641,13 +774,24 @@ export const useTerminalStateStore = create()( removedEventEntries = true; } } - if (orphanedIds.length === 0 && !removedEventEntries) return state; + if ( + orphanedIds.length === 0 && + orphanedLaunchContextIds.length === 0 && + !removedEventEntries + ) { + return state; + } const next = { ...state.terminalStateByThreadId }; for (const id of orphanedIds) { delete next[id as ThreadId]; } + const nextLaunchContexts = { ...state.terminalLaunchContextByThreadId }; + for (const id of orphanedLaunchContextIds) { + delete nextLaunchContexts[id as ThreadId]; + } return { terminalStateByThreadId: next, + terminalLaunchContextByThreadId: nextLaunchContexts, terminalEventEntriesByKey: nextTerminalEventEntriesByKey, }; }), diff --git a/apps/web/src/wsNativeApi.test.ts b/apps/web/src/wsNativeApi.test.ts index c9bcc7ffd2..cfa6ca6942 100644 --- a/apps/web/src/wsNativeApi.test.ts +++ b/apps/web/src/wsNativeApi.test.ts @@ -159,6 +159,12 @@ const baseServerConfig: ServerConfig = { issues: [], providers: defaultProviders, availableEditors: ["cursor"], + observability: { + logsDirectoryPath: "/tmp/workspace/.config/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, settings: DEFAULT_SERVER_SETTINGS, }; @@ -237,6 +243,20 @@ describe("wsNativeApi", () => { expect(onDomainEvent).toHaveBeenCalledWith(orchestrationEvent); }); + it("forwards orchestration stream subscription options to the RPC client", async () => { + const { createWsNativeApi } = await import("./wsNativeApi"); + + const api = createWsNativeApi(); + const onDomainEvent = vi.fn(); + const onResubscribe = vi.fn(); + + api.orchestration.onDomainEvent(onDomainEvent, { onResubscribe }); + + expect(rpcClientMock.orchestration.onDomainEvent).toHaveBeenCalledWith(onDomainEvent, { + onResubscribe, + }); + }); + it("sends orchestration dispatch commands as the direct RPC payload", async () => { rpcClientMock.orchestration.dispatchCommand.mockResolvedValue({ sequence: 1 }); const { createWsNativeApi } = await import("./wsNativeApi"); diff --git a/apps/web/src/wsNativeApi.ts b/apps/web/src/wsNativeApi.ts index 31160dfa1c..99045dbf07 100644 --- a/apps/web/src/wsNativeApi.ts +++ b/apps/web/src/wsNativeApi.ts @@ -1,7 +1,9 @@ import { type ContextMenuItem, type NativeApi } from "@t3tools/contracts"; import { showContextMenuFallback } from "./contextMenuFallback"; +import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState"; import { resetServerStateForTests } from "./rpc/serverState"; +import { resetWsConnectionStateForTests } from "./rpc/wsConnectionState"; import { __resetWsRpcClientForTests, getWsRpcClient } from "./wsRpcClient"; let instance: { api: NativeApi } | null = null; @@ -9,7 +11,9 @@ let instance: { api: NativeApi } | null = null; export function __resetWsNativeApiForTests() { instance = null; __resetWsRpcClientForTests(); + resetRequestLatencyStateForTests(); resetServerStateForTests(); + resetWsConnectionStateForTests(); } export function createWsNativeApi(): NativeApi { @@ -98,7 +102,8 @@ export function createWsNativeApi(): NativeApi { rpcClient.orchestration .replayEvents({ fromSequenceExclusive }) .then((events) => [...events]), - onDomainEvent: (callback) => rpcClient.orchestration.onDomainEvent(callback), + onDomainEvent: (callback, options) => + rpcClient.orchestration.onDomainEvent(callback, options), }, }; diff --git a/apps/web/src/wsRpcClient.ts b/apps/web/src/wsRpcClient.ts index 60f51ba707..1d411aa1b9 100644 --- a/apps/web/src/wsRpcClient.ts +++ b/apps/web/src/wsRpcClient.ts @@ -10,12 +10,17 @@ import { import { Effect, Stream } from "effect"; import { type WsRpcProtocolClient } from "./rpc/protocol"; +import { resetWsReconnectBackoff } from "./rpc/wsConnectionState"; import { WsTransport } from "./wsTransport"; type RpcTag = keyof WsRpcProtocolClient & string; type RpcMethod = WsRpcProtocolClient[TTag]; type RpcInput = Parameters>[0]; +interface StreamSubscriptionOptions { + readonly onResubscribe?: () => void; +} + type RpcUnaryMethod = RpcMethod extends (input: any, options?: any) => Effect.Effect ? (input: RpcInput) => Promise @@ -28,7 +33,7 @@ type RpcUnaryNoArgMethod = type RpcStreamMethod = RpcMethod extends (input: any, options?: any) => Stream.Stream - ? (listener: (event: TEvent) => void) => () => void + ? (listener: (event: TEvent) => void, options?: StreamSubscriptionOptions) => () => void : never; interface GitRunStackedActionOptions { @@ -37,6 +42,7 @@ interface GitRunStackedActionOptions { export interface WsRpcClient { readonly dispose: () => Promise; + readonly reconnect: () => Promise; readonly terminal: { readonly open: RpcUnaryMethod; readonly write: RpcUnaryMethod; @@ -113,6 +119,10 @@ export async function __resetWsRpcClientForTests() { export function createWsRpcClient(transport = new WsTransport()): WsRpcClient { return { dispose: () => transport.dispose(), + reconnect: async () => { + resetWsReconnectBackoff(); + await transport.reconnect(); + }, terminal: { open: (input) => transport.request((client) => client[WS_METHODS.terminalOpen](input)), write: (input) => transport.request((client) => client[WS_METHODS.terminalWrite](input)), @@ -120,8 +130,12 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient { clear: (input) => transport.request((client) => client[WS_METHODS.terminalClear](input)), restart: (input) => transport.request((client) => client[WS_METHODS.terminalRestart](input)), close: (input) => transport.request((client) => client[WS_METHODS.terminalClose](input)), - onEvent: (listener) => - transport.subscribe((client) => client[WS_METHODS.subscribeTerminalEvents]({}), listener), + onEvent: (listener, options) => + transport.subscribe( + (client) => client[WS_METHODS.subscribeTerminalEvents]({}), + listener, + options, + ), }, projects: { searchEntries: (input) => @@ -179,10 +193,18 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient { getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})), updateSettings: (patch) => transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })), - subscribeConfig: (listener) => - transport.subscribe((client) => client[WS_METHODS.subscribeServerConfig]({}), listener), - subscribeLifecycle: (listener) => - transport.subscribe((client) => client[WS_METHODS.subscribeServerLifecycle]({}), listener), + subscribeConfig: (listener, options) => + transport.subscribe( + (client) => client[WS_METHODS.subscribeServerConfig]({}), + listener, + options, + ), + subscribeLifecycle: (listener, options) => + transport.subscribe( + (client) => client[WS_METHODS.subscribeServerLifecycle]({}), + listener, + options, + ), }, orchestration: { getSnapshot: () => @@ -197,10 +219,11 @@ export function createWsRpcClient(transport = new WsTransport()): WsRpcClient { transport .request((client) => client[ORCHESTRATION_WS_METHODS.replayEvents](input)) .then((events) => [...events]), - onDomainEvent: (listener) => + onDomainEvent: (listener, options) => transport.subscribe( (client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}), listener, + options, ), }, }; diff --git a/apps/web/src/wsTransport.test.ts b/apps/web/src/wsTransport.test.ts index 2f64f2a692..af02a5288f 100644 --- a/apps/web/src/wsTransport.test.ts +++ b/apps/web/src/wsTransport.test.ts @@ -1,6 +1,16 @@ -import { WS_METHODS } from "@t3tools/contracts"; +import { DEFAULT_SERVER_SETTINGS, WS_METHODS } from "@t3tools/contracts"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + __resetClientTracingForTests, + configureClientTracing, +} from "./observability/clientTracing"; +import { getSlowRpcAckRequests, resetRequestLatencyStateForTests } from "./rpc/requestLatencyState"; +import { + getWsConnectionStatus, + getWsConnectionUiState, + resetWsConnectionStateForTests, +} from "./rpc/wsConnectionState"; import { WsTransport } from "./wsTransport"; type WsEventType = "open" | "message" | "close" | "error"; @@ -53,6 +63,10 @@ class MockWebSocket { this.emit("message", { data, type: "message" }); } + error() { + this.emit("error", { type: "error" }); + } + private emit(type: WsEventType, event?: WsEvent) { const listeners = this.listeners.get(type); if (!listeners) return; @@ -63,6 +77,7 @@ class MockWebSocket { } const originalWebSocket = globalThis.WebSocket; +const originalFetch = globalThis.fetch; function getSocket(): MockWebSocket { const socket = sockets.at(-1); @@ -88,7 +103,10 @@ async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise } beforeEach(() => { + vi.useRealTimers(); sockets.length = 0; + resetRequestLatencyStateForTests(); + resetWsConnectionStateForTests(); Object.defineProperty(globalThis, "window", { configurable: true, @@ -102,12 +120,20 @@ beforeEach(() => { desktopBridge: undefined, }, }); + Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { onLine: true }, + }); globalThis.WebSocket = MockWebSocket as unknown as typeof WebSocket; }); -afterEach(() => { +afterEach(async () => { globalThis.WebSocket = originalWebSocket; + globalThis.fetch = originalFetch; + resetRequestLatencyStateForTests(); + resetWsConnectionStateForTests(); + await __resetClientTracingForTests(); vi.restoreAllMocks(); }); @@ -141,6 +167,184 @@ describe("WsTransport", () => { await transport.dispose(); }); + it("tracks initial connection failures for the app error state", async () => { + const transport = new WsTransport("ws://localhost:3020"); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + expect(getWsConnectionStatus()).toMatchObject({ + attemptCount: 1, + phase: "connecting", + socketUrl: "ws://localhost:3020/ws", + }); + + socket.error(); + socket.close(1006, "server unavailable"); + + await waitFor(() => { + expect(getWsConnectionStatus()).toMatchObject({ + closeCode: 1006, + closeReason: "server unavailable", + hasConnected: false, + lastError: "Unable to connect to the T3 server WebSocket.", + phase: "disconnected", + }); + }); + expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("error"); + + await transport.dispose(); + }); + + it("surfaces reconnecting state after a live socket disconnects", async () => { + const transport = new WsTransport("ws://localhost:3020"); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + socket.open(); + + await waitFor(() => { + expect(getWsConnectionStatus()).toMatchObject({ + hasConnected: true, + phase: "connected", + }); + }); + + socket.close(1013, "try again later"); + + await waitFor(() => { + expect(getWsConnectionStatus()).toMatchObject({ + closeReason: "try again later", + hasConnected: true, + }); + }); + expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("reconnecting"); + + await transport.dispose(); + }); + + it("reconnects the websocket session without disposing the transport", async () => { + const transport = new WsTransport("ws://localhost:3020"); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const firstSocket = getSocket(); + firstSocket.open(); + + await waitFor(() => { + expect(getWsConnectionStatus()).toMatchObject({ + hasConnected: true, + phase: "connected", + }); + }); + + await transport.reconnect(); + + await waitFor(() => { + expect(sockets).toHaveLength(2); + }); + + const secondSocket = getSocket(); + expect(secondSocket).not.toBe(firstSocket); + expect(firstSocket.readyState).toBe(MockWebSocket.CLOSED); + + const requestPromise = transport.request((client) => + client[WS_METHODS.serverUpsertKeybinding]({ + command: "terminal.toggle", + key: "ctrl+k", + }), + ); + + secondSocket.open(); + + await waitFor(() => { + expect(secondSocket.sent).toHaveLength(1); + }); + + const requestMessage = JSON.parse(secondSocket.sent[0] ?? "{}") as { id: string }; + secondSocket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: requestMessage.id, + exit: { + _tag: "Success", + value: { + keybindings: [], + issues: [], + }, + }, + }), + ); + + await expect(requestPromise).resolves.toEqual({ + keybindings: [], + issues: [], + }); + + await transport.dispose(); + }); + + it("marks unary requests as slow until the first server ack arrives", async () => { + const transport = new WsTransport("ws://localhost:3020"); + + const requestPromise = transport.request((client) => + client[WS_METHODS.serverUpsertKeybinding]({ + command: "terminal.toggle", + key: "ctrl+k", + }), + ); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + socket.open(); + + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); + + const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { id: string }; + await waitFor(() => { + expect(getSlowRpcAckRequests()).toMatchObject([ + { + requestId: requestMessage.id, + tag: WS_METHODS.serverUpsertKeybinding, + }, + ]); + }, 5_000); + + socket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: requestMessage.id, + exit: { + _tag: "Success", + value: { + keybindings: [], + issues: [], + }, + }, + }), + ); + + await expect(requestPromise).resolves.toEqual({ + keybindings: [], + issues: [], + }); + expect(getSlowRpcAckRequests()).toEqual([]); + + await transport.dispose(); + }, 10_000); + it("sends unary RPC requests and resolves successful exits", async () => { const transport = new WsTransport("ws://localhost:3020"); @@ -250,10 +454,12 @@ describe("WsTransport", () => { it("re-subscribes stream listeners after the stream exits", async () => { const transport = new WsTransport("ws://localhost:3020"); const listener = vi.fn(); + const onResubscribe = vi.fn(); const unsubscribe = transport.subscribe( (client) => client[WS_METHODS.subscribeServerLifecycle]({}), listener, + { onResubscribe }, ); await waitFor(() => { expect(sockets).toHaveLength(1); @@ -301,6 +507,7 @@ describe("WsTransport", () => { .find((message) => message._tag === "Request" && message.id !== firstRequest.id); expect(nextRequest).toBeDefined(); }); + expect(onResubscribe).toHaveBeenCalledOnce(); const secondRequest = socket.sent .map((message) => JSON.parse(message) as { _tag?: string; id?: string; tag?: string }) @@ -339,6 +546,52 @@ describe("WsTransport", () => { await transport.dispose(); }); + it("does not fire onResubscribe when the first stream attempt exits before any value", async () => { + const transport = new WsTransport("ws://localhost:3020"); + const listener = vi.fn(); + const onResubscribe = vi.fn(); + + const unsubscribe = transport.subscribe( + (client) => client[WS_METHODS.subscribeServerLifecycle]({}), + listener, + { onResubscribe }, + ); + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + socket.open(); + + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); + + const firstRequest = JSON.parse(socket.sent[0] ?? "{}") as { id: string }; + socket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: firstRequest.id, + exit: { + _tag: "Success", + value: null, + }, + }), + ); + + await waitFor(() => { + const nextRequest = socket.sent + .map((message) => JSON.parse(message) as { _tag?: string; id?: string }) + .find((message) => message._tag === "Request" && message.id !== firstRequest.id); + expect(nextRequest).toBeDefined(); + }); + expect(onResubscribe).not.toHaveBeenCalled(); + expect(listener).not.toHaveBeenCalled(); + + unsubscribe(); + await transport.dispose(); + }); + it("streams finite request events without re-subscribing", async () => { const transport = new WsTransport("ws://localhost:3020"); const listener = vi.fn(); @@ -422,11 +675,21 @@ describe("WsTransport", () => { }; const transport = { disposed: false, - clientScope: {} as never, - runtime, + session: { + clientScope: {} as never, + runtime, + }, + closeSession: ( + WsTransport.prototype as unknown as { + closeSession: (session: { + clientScope: unknown; + runtime: { dispose: () => Promise; runPromise: () => Promise }; + }) => Promise; + } + ).closeSession, } as unknown as WsTransport; - WsTransport.prototype.dispose.call(transport); + void WsTransport.prototype.dispose.call(transport); expect(runtime.runPromise).toHaveBeenCalledTimes(1); expect(runtime.dispose).not.toHaveBeenCalled(); @@ -440,4 +703,46 @@ describe("WsTransport", () => { expect(callOrder).toEqual(["close:start", "close:done", "runtime:dispose"]); }); + + it("propagates OTLP trace ids for ws transport requests when client tracing is enabled", async () => { + await configureClientTracing({ + exportIntervalMs: 10, + }); + + const transport = new WsTransport("ws://localhost:3020"); + const requestPromise = transport.request((client) => client[WS_METHODS.serverGetSettings]({})); + + await waitFor(() => { + expect(sockets).toHaveLength(1); + }); + + const socket = getSocket(); + socket.open(); + + await waitFor(() => { + expect(socket.sent).toHaveLength(1); + }); + + const requestMessage = JSON.parse(socket.sent[0] ?? "{}") as { + id: string; + spanId?: string; + traceId?: string; + }; + expect(requestMessage.traceId).toMatch(/^[0-9a-f]{32}$/); + expect(requestMessage.spanId).toMatch(/^[0-9a-f]{16}$/); + + socket.serverMessage( + JSON.stringify({ + _tag: "Exit", + requestId: requestMessage.id, + exit: { + _tag: "Success", + value: DEFAULT_SERVER_SETTINGS, + }, + }), + ); + + await expect(requestPromise).resolves.toEqual(DEFAULT_SERVER_SETTINGS); + await transport.dispose(); + }); }); diff --git a/apps/web/src/wsTransport.ts b/apps/web/src/wsTransport.ts index 70042261d5..3e435ee167 100644 --- a/apps/web/src/wsTransport.ts +++ b/apps/web/src/wsTransport.ts @@ -1,14 +1,26 @@ -import { Duration, Effect, Exit, ManagedRuntime, Option, Scope, Stream } from "effect"; +import { + Cause, + Duration, + Effect, + Exit, + Layer, + ManagedRuntime, + Option, + Scope, + Stream, +} from "effect"; +import { RpcClient } from "effect/unstable/rpc"; +import { ClientTracingLive, configureClientTracing } from "./observability/clientTracing"; import { createWsRpcProtocolLayer, makeWsRpcProtocolClient, type WsRpcProtocolClient, } from "./rpc/protocol"; -import { RpcClient } from "effect/unstable/rpc"; interface SubscribeOptions { readonly retryDelay?: Duration.Input; + readonly onResubscribe?: () => void; } interface RequestOptions { @@ -16,6 +28,13 @@ interface RequestOptions { } const DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS = Duration.millis(250); +const NOOP: () => void = () => undefined; + +interface TransportSession { + readonly clientPromise: Promise; + readonly clientScope: Scope.Closeable; + readonly runtime: ManagedRuntime.ManagedRuntime; +} function formatErrorMessage(error: unknown): string { if (error instanceof Error && error.message.trim().length > 0) { @@ -25,17 +44,16 @@ function formatErrorMessage(error: unknown): string { } export class WsTransport { - private readonly runtime: ManagedRuntime.ManagedRuntime; - private readonly clientScope: Scope.Closeable; - private readonly clientPromise: Promise; + private readonly tracingReady: Promise; + private readonly url: string | undefined; private disposed = false; + private reconnectChain: Promise = Promise.resolve(); + private session: TransportSession; constructor(url?: string) { - this.runtime = ManagedRuntime.make(createWsRpcProtocolLayer(url)); - this.clientScope = this.runtime.runSync(Scope.make()); - this.clientPromise = this.runtime.runPromise( - Scope.provide(this.clientScope)(makeWsRpcProtocolClient), - ); + this.url = url; + this.tracingReady = configureClientTracing(); + this.session = this.createSession(); } async request( @@ -46,8 +64,10 @@ export class WsTransport { throw new Error("Transport disposed"); } - const client = await this.clientPromise; - return await this.runtime.runPromise(Effect.suspend(() => execute(client))); + await this.tracingReady; + const session = this.session; + const client = await session.clientPromise; + return await session.runtime.runPromise(Effect.suspend(() => execute(client))); } async requestStream( @@ -58,8 +78,10 @@ export class WsTransport { throw new Error("Transport disposed"); } - const client = await this.clientPromise; - await this.runtime.runPromise( + await this.tracingReady; + const session = this.session; + const client = await session.clientPromise; + await session.runtime.runPromise( Stream.runForEach(connect(client), (value) => Effect.sync(() => { try { @@ -82,15 +104,132 @@ export class WsTransport { } let active = true; - const retryDelayMs = options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS; - const cancel = this.runtime.runCallback( - Effect.promise(() => this.clientPromise).pipe( + let hasReceivedValue = false; + const retryDelayMs = Duration.toMillis( + Duration.fromInputUnsafe(options?.retryDelay ?? DEFAULT_SUBSCRIPTION_RETRY_DELAY_MS), + ); + let cancelCurrentStream: () => void = NOOP; + + void (async () => { + for (;;) { + if (!active || this.disposed) { + return; + } + + try { + if (hasReceivedValue) { + try { + options?.onResubscribe?.(); + } catch { + // Swallow reconnect hook errors so the stream can recover. + } + } + + const session = this.session; + const runningStream = this.runStreamOnSession( + session, + connect, + listener, + () => active, + () => { + hasReceivedValue = true; + }, + ); + cancelCurrentStream = runningStream.cancel; + await runningStream.completed; + cancelCurrentStream = NOOP; + } catch (error) { + cancelCurrentStream = NOOP; + if (!active || this.disposed) { + return; + } + + console.warn("WebSocket RPC subscription disconnected", { + error: formatErrorMessage(error), + }); + await sleep(retryDelayMs); + } + } + })(); + + return () => { + active = false; + cancelCurrentStream(); + }; + } + + async reconnect() { + if (this.disposed) { + throw new Error("Transport disposed"); + } + + const reconnectOperation = this.reconnectChain.then(async () => { + if (this.disposed) { + throw new Error("Transport disposed"); + } + + const previousSession = this.session; + this.session = this.createSession(); + await this.closeSession(previousSession); + }); + + this.reconnectChain = reconnectOperation.catch(() => undefined); + await reconnectOperation; + } + + async dispose() { + if (this.disposed) { + return; + } + this.disposed = true; + await this.closeSession(this.session); + } + + private closeSession(session: TransportSession) { + return session.runtime.runPromise(Scope.close(session.clientScope, Exit.void)).finally(() => { + session.runtime.dispose(); + }); + } + + private createSession(): TransportSession { + const runtime = ManagedRuntime.make( + Layer.mergeAll(createWsRpcProtocolLayer(this.url), ClientTracingLive), + ); + const clientScope = runtime.runSync(Scope.make()); + return { + runtime, + clientScope, + clientPromise: runtime.runPromise(Scope.provide(clientScope)(makeWsRpcProtocolClient)), + }; + } + + private runStreamOnSession( + session: TransportSession, + connect: (client: WsRpcProtocolClient) => Stream.Stream, + listener: (value: TValue) => void, + isActive: () => boolean, + markValueReceived: () => void, + ): { + readonly cancel: () => void; + readonly completed: Promise; + } { + let resolveCompleted!: () => void; + let rejectCompleted!: (error: unknown) => void; + const completed = new Promise((resolve, reject) => { + resolveCompleted = resolve; + rejectCompleted = reject; + }); + const cancel = session.runtime.runCallback( + Effect.promise(() => this.tracingReady).pipe( + Effect.flatMap(() => Effect.promise(() => session.clientPromise)), Effect.flatMap((client) => Stream.runForEach(connect(client), (value) => Effect.sync(() => { - if (!active) { + if (!isActive()) { return; } + + markValueReceived(); try { listener(value); } catch { @@ -99,33 +238,28 @@ export class WsTransport { }), ), ), - Effect.catch((error) => { - if (!active || this.disposed) { - return Effect.interrupt; - } - return Effect.sync(() => { - console.warn("WebSocket RPC subscription disconnected", { - error: formatErrorMessage(error), - }); - }).pipe(Effect.andThen(Effect.sleep(retryDelayMs))); - }), - Effect.forever, ), + { + onExit: (exit) => { + if (Exit.isSuccess(exit)) { + resolveCompleted(); + return; + } + + rejectCompleted(Cause.squash(exit.cause)); + }, + }, ); - return () => { - active = false; - cancel(); + return { + cancel, + completed, }; } - - async dispose() { - if (this.disposed) { - return; - } - this.disposed = true; - await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void)).finally(() => { - this.runtime.dispose(); - }); - } +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); } diff --git a/docs/observability.md b/docs/observability.md new file mode 100644 index 0000000000..dde1093570 --- /dev/null +++ b/docs/observability.md @@ -0,0 +1,519 @@ +# Observability + +T3 Code has one server-side observability model: + +- pretty logs go to stdout for humans +- completed spans go to a local NDJSON trace file +- traces and metrics can also be exported over OTLP to a real backend like Grafana LGTM + +The local trace file is the persisted source of truth. There is no separate persisted server log file anymore. + +## Where To Find Things + +### Logs + +Logs are human-facing only: + +- destination: stdout +- format: `Logger.consolePretty()` +- persistence: none + +If you want a log message to show up in the trace file, emit it inside an active span with `Effect.log...`. `Logger.tracerLogger` will attach it as a span event. + +### Traces + +Completed spans are written as NDJSON records to `serverTracePath` (by default, `~/.t3/userdata/logs/server.trace.ndjson`). + +Important fields in each record: + +- `name`: span name +- `traceId`, `spanId`, `parentSpanId`: correlation +- `durationMs`: elapsed time +- `attributes`: structured context +- `events`: embedded logs and custom events +- `exit`: `Success`, `Failure`, or `Interrupted` + +The schema lives in `apps/server/src/observability/TraceRecord.ts`. + +### Metrics + +Metrics are not written to a local file. + +- local persistence: none +- remote export: OTLP only, when configured +- current definitions: `apps/server/src/observability/Metrics.ts` + +If OTLP is not configured, metrics still exist in-process, but you will not have a local artifact to inspect. + +### Related Artifacts + +Provider event NDJSON files still exist for provider runtime streams. Those are separate from the main server trace file. + +## Run The Server In Instrumented Mode + +There are two useful modes: + +- local-only: stdout + local `server.trace.ndjson` +- full local observability: stdout + local trace file + OTLP export to Grafana/Tempo/Prometheus + +The local trace file is always on. OTLP export is opt-in. + +### Option 1: Local Traces Only + +You do not need any extra env vars. Just run the app normally and inspect `server.trace.ndjson`. + +Examples: + +```bash +npx t3 +``` + +```bash +bun dev +``` + +```bash +bun dev:desktop +``` + +### Option 2: Run With A Local LGTM Stack + +#### 1. Start Grafana LGTM + +```bash +docker run --name lgtm \ + -p 3000:3000 \ + -p 4317:4317 \ + -p 4318:4318 \ + --rm -ti \ + grafana/otel-lgtm +``` + +Then open `http://localhost:3000`. + +Default Grafana login: + +- username: `admin` +- password: `admin` + +#### 2. Export OTLP env vars + +```bash +export T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces +export T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics +export T3CODE_OTLP_SERVICE_NAME=t3-local +``` + +Optional: + +```bash +export T3CODE_TRACE_MIN_LEVEL=Info +export T3CODE_TRACE_TIMING_ENABLED=true +``` + +#### 3. Launch the app from that same shell + +CLI: + +```bash +npx t3 +``` + +Monorepo web/server dev: + +```bash +bun dev +``` + +Monorepo desktop dev: + +```bash +bun dev:desktop +``` + +Packaged desktop app: + +Launch the actual app executable from the same shell so the desktop app and embedded backend inherit `T3CODE_OTLP_*`. + +macOS app bundle example: + +```bash +T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \ +T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \ +T3CODE_OTLP_SERVICE_NAME=t3-desktop \ +"/Applications/T3 Code.app/Contents/MacOS/T3 Code" +``` + +Direct binary example: + +```bash +T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \ +T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \ +T3CODE_OTLP_SERVICE_NAME=t3-desktop \ +./path/to/your/desktop-app-binary +``` + +Do not rely on launching from Finder, Spotlight, the dock, or the Start menu after setting shell env vars. Those launches usually will not pick them up. + +#### 4. Fully restart after changing env + +The backend reads observability config at process start. If you change OTLP env vars, stop the app completely and start it again. + +## How To Use Traces And Metrics To Debug The Server + +### Start With The Local Trace File + +The trace file is the fastest way to inspect raw span data. + +Tail it: + +```bash +tail -f "$T3CODE_HOME/userdata/logs/server.trace.ndjson" +``` + +In monorepo dev, use: + +```bash +tail -f ./dev/logs/server.trace.ndjson +``` + +Show failed spans: + +```bash +jq -c 'select(.exit._tag != "Success") | { + name, + durationMs, + exit, + attributes +}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" +``` + +Show slow spans: + +```bash +jq -c 'select(.durationMs > 1000) | { + name, + durationMs, + traceId, + spanId +}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" +``` + +Inspect embedded log events: + +```bash +jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | { + name, + durationMs, + events: [ + .events[] + | select(.attributes["effect.logLevel"] != null) + | { + message: .name, + level: .attributes["effect.logLevel"] + } + ] +}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" +``` + +Follow one trace: + +```bash +jq -r 'select(.traceId == "TRACE_ID_HERE") | [ + .name, + .spanId, + (.parentSpanId // "-"), + .durationMs +] | @tsv' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" +``` + +Filter orchestration commands: + +```bash +jq -c 'select(.attributes["orchestration.command_type"] != null) | { + name, + durationMs, + commandType: .attributes["orchestration.command_type"], + aggregateKind: .attributes["orchestration.aggregate_kind"] +}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" +``` + +Filter git activity: + +```bash +jq -c 'select(.attributes["git.operation"] != null) | { + name, + durationMs, + operation: .attributes["git.operation"], + cwd: .attributes["git.cwd"], + hookEvents: [ + .events[] + | select(.name == "git.hook.started" or .name == "git.hook.finished") + ] +}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" +``` + +### Use Tempo When You Need A Real Trace Viewer + +Tempo is better than raw NDJSON when you want to: + +- search across many traces +- inspect parent/child relationships visually +- compare many slow traces +- drill into one failing request without hand-joining by `traceId` + +Recommended flow in Grafana: + +1. Open `Explore`. +2. Pick the `Tempo` data source. +3. Set the time range to something recent like `Last 15 minutes`. +4. Start broad. Do not begin with a very narrow query. +5. Look for spans from your configured service name, then narrow by span name or attributes. + +Good first searches: + +- service name such as `t3-local`, `t3-dev`, or `t3-desktop` +- span names like `sql.execute`, `git.runCommand`, `provider.sendTurn` +- orchestration spans with attributes like `orchestration.command_type` + +Once you know traces are arriving, narrower TraceQL queries like `name = "sql.execute"` become useful. + +### Use Metrics To See Systemic Problems + +Traces are best for one request. Metrics are best for trends. + +Good metric families to watch: + +- `t3_rpc_request_duration` +- `t3_orchestration_command_duration` +- `t3_orchestration_command_ack_duration` +- `t3_provider_turn_duration` +- `t3_git_command_duration` +- `t3_db_query_duration` + +Counters tell you volume and failure rate: + +- `t3_rpc_requests_total` +- `t3_orchestration_commands_total` +- `t3_provider_turns_total` +- `t3_git_commands_total` +- `t3_db_queries_total` + +Use metrics when the question is: + +- "is this always slow?" +- "did this get worse after a change?" +- "which command type is failing most often?" + +Use traces when the question is: + +- "what happened in this specific request?" +- "which child span caused this one slow interaction?" +- "what logs were emitted inside the failing flow?" + +### What The New Ack Metric Means + +`t3_orchestration_command_ack_duration` measures: + +- start: command dispatch enters the orchestration engine +- end: the first committed domain event for that command is published by the server + +That is a server-side acknowledgment metric. It does not measure: + +- websocket transit to the browser +- client receipt +- React render time + +If you need those later, add client-side instrumentation or a dedicated server fanout metric. + +## Common Workflows + +### "Why did this request fail?" + +1. Start with the local NDJSON file. +2. Find spans where `exit._tag != "Success"`. +3. Group by `traceId`. +4. Inspect sibling spans and span events. +5. If needed, move to Tempo for the full trace tree. + +### "Why is the UI feeling slow?" + +1. Search for slow top-level spans in the trace file or Tempo. +2. Check child spans for sqlite, git, provider, or terminal work. +3. Look at the matching duration metrics to see whether the slowness is systemic. + +### "Did this command take too long to acknowledge?" + +1. Check `t3_orchestration_command_ack_duration` by `commandType`. +2. If it is high, inspect the corresponding orchestration trace. +3. Look at child spans for projection, sqlite, provider, or git work. + +### "Are git hooks causing latency?" + +1. Filter `git.operation` spans. +2. Inspect `git.hook.started` and `git.hook.finished` events. +3. Compare hook timing to the enclosing git span duration. + +### "Why do I have spans locally but nothing in Grafana?" + +Usually one of these is true: + +- `T3CODE_OTLP_TRACES_URL` was not set +- the app was launched from a different environment than the one where you exported the vars +- the app was not fully restarted after changing env +- Grafana is looking at the wrong time range or service name + +If the local NDJSON file is updating, local tracing is working. The problem is almost always OTLP export configuration or process startup. + +## How To Think About Adding Tracing To Future Code + +### Prefer Boundaries Over Tiny Helpers + +Good span boundaries: + +- RPC methods +- orchestration command handling +- provider adapter calls +- external process calls +- persistence writes +- queue handoffs + +Avoid tracing every tiny helper. Most helpers should inherit the active span rather than create a new one. + +### Reuse `Effect.fn(...)` Where It Already Exists + +The codebase already uses `Effect.fn("name")` heavily. That should usually be your first tracing boundary. + +For ad hoc work: + +```ts +import { Effect } from "effect"; + +const runThing = Effect.gen(function* () { + yield* Effect.annotateCurrentSpan({ + "thing.id": "abc123", + "thing.kind": "example", + }); + + yield* Effect.logInfo("starting thing"); + return yield* doWork(); +}).pipe(Effect.withSpan("thing.run")); +``` + +### Put High-Cardinality Detail On Spans + +Use span annotations for IDs, paths, and other detailed context: + +```ts +yield * + Effect.annotateCurrentSpan({ + "provider.thread_id": input.threadId, + "provider.request_id": input.requestId, + "git.cwd": input.cwd, + }); +``` + +### Keep Metric Labels Low Cardinality + +Good metric labels: + +- operation kind +- method name +- provider kind +- aggregate kind +- outcome + +Bad metric labels: + +- raw thread IDs +- command IDs +- file paths +- cwd +- full prompts +- full model strings when a normalized family label would do + +Detailed context belongs on spans, not metrics. + +### Use Logs As Span Events + +Logs inside a span become part of the trace story: + +```ts +yield * Effect.logInfo("starting provider turn"); +yield * Effect.logDebug("waiting for approval response"); +``` + +Those messages show up as span events because `Logger.tracerLogger` is installed. + +### Use The Pipeable Metrics API + +`withMetrics(...)` is the default way to attach a counter and timer to an effect: + +```ts +import { someCounter, someDuration, withMetrics } from "../observability/Metrics.ts"; + +const program = doWork().pipe( + withMetrics({ + counter: someCounter, + timer: someDuration, + attributes: { + operation: "work", + }, + }), +); +``` + +## Detailed API Reference + +### Runtime Wiring + +The server observability layer is assembled in `apps/server/src/observability/Layers/Observability.ts`. + +It provides: + +- pretty stdout logger +- `Logger.tracerLogger` +- local NDJSON tracer +- optional OTLP trace exporter +- optional OTLP metrics exporter +- Effect trace-level and timing refs + +### Env Vars + +Local trace file: + +- `T3CODE_TRACE_FILE`: override trace file path +- `T3CODE_TRACE_MAX_BYTES`: per-file rotation size, default `10485760` +- `T3CODE_TRACE_MAX_FILES`: rotated file count, default `10` +- `T3CODE_TRACE_BATCH_WINDOW_MS`: flush window, default `200` +- `T3CODE_TRACE_MIN_LEVEL`: minimum trace level, default `Info` +- `T3CODE_TRACE_TIMING_ENABLED`: enable timing metadata, default `true` + +OTLP export: + +- `T3CODE_OTLP_TRACES_URL`: OTLP trace endpoint +- `T3CODE_OTLP_METRICS_URL`: OTLP metric endpoint +- `T3CODE_OTLP_EXPORT_INTERVAL_MS`: export interval, default `10000` +- `T3CODE_OTLP_SERVICE_NAME`: service name, default `t3-server` + +If the OTLP URLs are unset, local tracing still works and metrics stay in-process only. + +### What Is Instrumented Today + +Current high-value span and metric boundaries include: + +- Effect RPC websocket request spans from `effect/rpc` +- RPC request metrics in `apps/server/src/observability/RpcInstrumentation.ts` +- startup phases +- orchestration command processing +- orchestration command acknowledgment latency +- provider session and turn operations +- git command execution and git hook events +- terminal session lifecycle +- sqlite query execution + +### Current Constraints + +- logs outside spans are not persisted +- metrics are not snapshotted locally +- the old `serverLogPath` still exists in config for compatibility, but the trace file is the persisted artifact that matters diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.ts index 26b00aff68..4ecaa72c49 100644 --- a/packages/contracts/src/editor.ts +++ b/packages/contracts/src/editor.ts @@ -1,21 +1,32 @@ import { Schema } from "effect"; import { TrimmedNonEmptyString } from "./baseSchemas"; +export const EditorLaunchStyle = Schema.Literals(["direct-path", "goto", "line-column"]); +export type EditorLaunchStyle = typeof EditorLaunchStyle.Type; + +type EditorDefinition = { + readonly id: string; + readonly label: string; + readonly command: string | null; + readonly launchStyle: EditorLaunchStyle; +}; + export const EDITORS = [ - { id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true }, - { id: "trae", label: "Trae", command: "trae", supportsGoto: true }, - { id: "vscode", label: "VS Code", command: "code", supportsGoto: true }, + { id: "cursor", label: "Cursor", command: "cursor", launchStyle: "goto" }, + { id: "trae", label: "Trae", command: "trae", launchStyle: "goto" }, + { id: "vscode", label: "VS Code", command: "code", launchStyle: "goto" }, { id: "vscode-insiders", label: "VS Code Insiders", command: "code-insiders", - supportsGoto: true, + launchStyle: "goto", }, - { id: "vscodium", label: "VSCodium", command: "codium", supportsGoto: true }, - { id: "zed", label: "Zed", command: "zed", supportsGoto: false }, - { id: "antigravity", label: "Antigravity", command: "agy", supportsGoto: false }, - { id: "file-manager", label: "File Manager", command: null, supportsGoto: false }, -] as const; + { id: "vscodium", label: "VSCodium", command: "codium", launchStyle: "goto" }, + { id: "zed", label: "Zed", command: "zed", launchStyle: "direct-path" }, + { id: "antigravity", label: "Antigravity", command: "agy", launchStyle: "goto" }, + { id: "idea", label: "IntelliJ IDEA", command: "idea", launchStyle: "line-column" }, + { id: "file-manager", label: "File Manager", command: null, launchStyle: "direct-path" }, +] as const satisfies ReadonlyArray; export const EditorId = Schema.Literals(EDITORS.map((e) => e.id)); export type EditorId = typeof EditorId.Type; diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 525ae7ee0d..f28a74f6de 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -1,5 +1,5 @@ import { Schema } from "effect"; -import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas"; +import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas"; const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString; const GIT_LIST_BRANCHES_MAX_LIMIT = 200; @@ -147,6 +147,7 @@ export const GitPreparePullRequestThreadInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, reference: GitPullRequestReference, mode: GitPreparePullRequestThreadMode, + threadId: Schema.optional(ThreadId), }); export type GitPreparePullRequestThreadInput = typeof GitPreparePullRequestThreadInput.Type; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 3114f6f5be..57a1c4c3dc 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -180,6 +180,11 @@ export interface NativeApi { input: OrchestrationGetFullThreadDiffInput, ) => Promise; replayEvents: (fromSequenceExclusive: number) => Promise; - onDomainEvent: (callback: (event: OrchestrationEvent) => void) => () => void; + onDomainEvent: ( + callback: (event: OrchestrationEvent) => void, + options?: { + onResubscribe?: () => void; + }, + ) => () => void; }; } diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 06bb35038d..53e84f1b98 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -195,6 +195,47 @@ it.effect("preserves explicit provider and runtime mode in thread.turn.start", ( }), ); +it.effect("accepts bootstrap metadata in thread.turn.start", () => + Effect.gen(function* () { + const parsed = yield* decodeThreadTurnStartCommand({ + type: "thread.turn.start", + commandId: "cmd-turn-bootstrap", + threadId: "thread-1", + message: { + messageId: "msg-bootstrap", + role: "user", + text: "hello", + attachments: [], + }, + bootstrap: { + createThread: { + projectId: "project-1", + title: "Bootstrap thread", + modelSelection: { + provider: "codex", + model: "gpt-5.4", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + }, + prepareWorktree: { + projectCwd: "/tmp/workspace", + baseBranch: "main", + branch: "t3code/example", + }, + runSetupScript: true, + }, + createdAt: "2026-01-01T00:00:00.000Z", + }); + assert.strictEqual(parsed.bootstrap?.createThread?.projectId, "project-1"); + assert.strictEqual(parsed.bootstrap?.prepareWorktree?.baseBranch, "main"); + assert.strictEqual(parsed.bootstrap?.runSetupScript, true); + }), +); + it.effect("decodes thread.created runtime mode for historical events", () => Effect.gen(function* () { const parsed = yield* decodeThreadCreatedPayload({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index bd7e374f32..6c7f073612 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -384,6 +384,31 @@ const ThreadInteractionModeSetCommand = Schema.Struct({ createdAt: IsoDateTime, }); +const ThreadTurnStartBootstrapCreateThread = Schema.Struct({ + projectId: ProjectId, + title: TrimmedNonEmptyString, + modelSelection: ModelSelection, + runtimeMode: RuntimeMode, + interactionMode: ProviderInteractionMode, + branch: Schema.NullOr(TrimmedNonEmptyString), + worktreePath: Schema.NullOr(TrimmedNonEmptyString), + createdAt: IsoDateTime, +}); + +const ThreadTurnStartBootstrapPrepareWorktree = Schema.Struct({ + projectCwd: TrimmedNonEmptyString, + baseBranch: TrimmedNonEmptyString, + branch: Schema.optional(TrimmedNonEmptyString), +}); + +const ThreadTurnStartBootstrap = Schema.Struct({ + createThread: Schema.optional(ThreadTurnStartBootstrapCreateThread), + prepareWorktree: Schema.optional(ThreadTurnStartBootstrapPrepareWorktree), + runSetupScript: Schema.optional(Schema.Boolean), +}); + +export type ThreadTurnStartBootstrap = typeof ThreadTurnStartBootstrap.Type; + export const ThreadTurnStartCommand = Schema.Struct({ type: Schema.Literal("thread.turn.start"), commandId: CommandId, @@ -400,6 +425,7 @@ export const ThreadTurnStartCommand = Schema.Struct({ interactionMode: ProviderInteractionMode.pipe( Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE), ), + bootstrap: Schema.optional(ThreadTurnStartBootstrap), sourceProposedPlan: Schema.optional(SourceProposedPlanReference), createdAt: IsoDateTime, }); @@ -418,6 +444,7 @@ const ClientThreadTurnStartCommand = Schema.Struct({ titleSeed: Schema.optional(TrimmedNonEmptyString), runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, + bootstrap: Schema.optional(ThreadTurnStartBootstrap), sourceProposedPlan: Schema.optional(SourceProposedPlanReference), createdAt: IsoDateTime, }); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index d4038deb3a..776a0a89e9 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -72,6 +72,16 @@ export type ServerProvider = typeof ServerProvider.Type; export const ServerProviders = Schema.Array(ServerProvider); export type ServerProviders = typeof ServerProviders.Type; +export const ServerObservability = Schema.Struct({ + logsDirectoryPath: TrimmedNonEmptyString, + localTracingEnabled: Schema.Boolean, + otlpTracesUrl: Schema.optional(TrimmedNonEmptyString), + otlpTracesEnabled: Schema.Boolean, + otlpMetricsUrl: Schema.optional(TrimmedNonEmptyString), + otlpMetricsEnabled: Schema.Boolean, +}); +export type ServerObservability = typeof ServerObservability.Type; + export const ServerConfig = Schema.Struct({ cwd: TrimmedNonEmptyString, keybindingsConfigPath: TrimmedNonEmptyString, @@ -79,6 +89,7 @@ export const ServerConfig = Schema.Struct({ issues: ServerConfigIssues, providers: ServerProviders, availableEditors: Schema.Array(EditorId), + observability: ServerObservability, settings: ServerSettings, }); export type ServerConfig = typeof ServerConfig.Type; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index c28b566daa..6633ce42a6 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -71,6 +71,12 @@ export const ClaudeSettings = Schema.Struct({ }); export type ClaudeSettings = typeof ClaudeSettings.Type; +export const ObservabilitySettings = Schema.Struct({ + otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(() => "")), + otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(() => "")), +}); +export type ObservabilitySettings = typeof ObservabilitySettings.Type; + export const ServerSettings = Schema.Struct({ enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)), defaultThreadEnvMode: ThreadEnvMode.pipe( @@ -88,6 +94,7 @@ export const ServerSettings = Schema.Struct({ codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))), claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))), }).pipe(Schema.withDecodingDefault(() => ({}))), + observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(() => ({}))), }); export type ServerSettings = typeof ServerSettings.Type; @@ -158,6 +165,12 @@ export const ServerSettingsPatch = Schema.Struct({ enableAssistantStreaming: Schema.optionalKey(Schema.Boolean), defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode), textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch), + observability: Schema.optionalKey( + Schema.Struct({ + otlpTracesUrl: Schema.optionalKey(Schema.String), + otlpMetricsUrl: Schema.optionalKey(Schema.String), + }), + ), providers: Schema.optionalKey( Schema.Struct({ codex: Schema.optionalKey(CodexSettingsPatch), diff --git a/packages/contracts/src/terminal.test.ts b/packages/contracts/src/terminal.test.ts index 614df05141..1bef8db3a0 100644 --- a/packages/contracts/src/terminal.test.ts +++ b/packages/contracts/src/terminal.test.ts @@ -63,6 +63,7 @@ describe("TerminalOpenInput", () => { const parsed = decodeSync(TerminalOpenInput, { threadId: "thread-1", cwd: "/tmp/project", + worktreePath: "/tmp/project/.t3/worktrees/feature-a", cols: 100, rows: 24, env: { @@ -74,6 +75,7 @@ describe("TerminalOpenInput", () => { T3CODE_PROJECT_ROOT: "/tmp/project", CUSTOM_FLAG: "1", }); + expect(parsed.worktreePath).toBe("/tmp/project/.t3/worktrees/feature-a"); }); it("rejects invalid env keys", () => { @@ -157,6 +159,7 @@ describe("TerminalSessionSnapshot", () => { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cwd: "/tmp/project", + worktreePath: null, status: "running", pid: 1234, history: "hello\n", @@ -205,4 +208,27 @@ describe("TerminalEvent", () => { }), ).toBe(true); }); + + it("accepts started events with snapshot worktree metadata", () => { + expect( + decodes(TerminalEvent, { + type: "started", + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + createdAt: new Date().toISOString(), + snapshot: { + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cwd: "/tmp/project/.t3/worktrees/feature-a", + worktreePath: "/tmp/project/.t3/worktrees/feature-a", + status: "running", + pid: 1234, + history: "", + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + }, + }), + ).toBe(true); + }); }); diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 4344706bc2..8b20254def 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -37,6 +37,7 @@ export type TerminalSessionInput = Schema.Codec.Encoded export const TerminalRestartInput = Schema.Struct({ ...TerminalSessionInput.fields, cwd: TrimmedNonEmptyStringSchema, + worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)), cols: TerminalColsSchema, rows: TerminalRowsSchema, env: Schema.optional(TerminalEnvSchema), @@ -82,6 +84,7 @@ export const TerminalSessionSnapshot = Schema.Struct({ threadId: Schema.String.check(Schema.isNonEmpty()), terminalId: Schema.String.check(Schema.isNonEmpty()), cwd: Schema.String.check(Schema.isNonEmpty()), + worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema), status: TerminalSessionStatus, pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))), history: Schema.String, diff --git a/packages/shared/package.json b/packages/shared/package.json index b35d23ef15..b71d52d700 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -40,9 +40,17 @@ "types": "./src/Struct.ts", "import": "./src/Struct.ts" }, + "./serverSettings": { + "types": "./src/serverSettings.ts", + "import": "./src/serverSettings.ts" + }, "./String": { "types": "./src/String.ts", "import": "./src/String.ts" + }, + "./projectScripts": { + "types": "./src/projectScripts.ts", + "import": "./src/projectScripts.ts" } }, "scripts": { diff --git a/packages/shared/src/projectScripts.ts b/packages/shared/src/projectScripts.ts new file mode 100644 index 0000000000..199a55bf3c --- /dev/null +++ b/packages/shared/src/projectScripts.ts @@ -0,0 +1,37 @@ +import type { ProjectScript } from "@t3tools/contracts"; + +interface ProjectScriptRuntimeEnvInput { + project: { + cwd: string; + }; + worktreePath?: string | null; + extraEnv?: Record; +} + +export function projectScriptCwd(input: { + project: { + cwd: string; + }; + worktreePath?: string | null; +}): string { + return input.worktreePath ?? input.project.cwd; +} + +export function projectScriptRuntimeEnv( + input: ProjectScriptRuntimeEnvInput, +): Record { + const env: Record = { + T3CODE_PROJECT_ROOT: input.project.cwd, + }; + if (input.worktreePath) { + env.T3CODE_WORKTREE_PATH = input.worktreePath; + } + if (input.extraEnv) { + return { ...env, ...input.extraEnv }; + } + return env; +} + +export function setupProjectScript(scripts: readonly ProjectScript[]): ProjectScript | null { + return scripts.find((script) => script.runOnWorktreeCreate) ?? null; +} diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts new file mode 100644 index 0000000000..0ac5e415df --- /dev/null +++ b/packages/shared/src/serverSettings.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; +import { + extractPersistedServerObservabilitySettings, + normalizePersistedServerSettingString, + parsePersistedServerObservabilitySettings, +} from "./serverSettings"; + +describe("serverSettings helpers", () => { + it("normalizes optional persisted strings", () => { + expect(normalizePersistedServerSettingString(undefined)).toBeUndefined(); + expect(normalizePersistedServerSettingString(" ")).toBeUndefined(); + expect(normalizePersistedServerSettingString(" http://localhost:4318/v1/traces ")).toBe( + "http://localhost:4318/v1/traces", + ); + }); + + it("extracts persisted observability settings", () => { + expect( + extractPersistedServerObservabilitySettings({ + observability: { + otlpTracesUrl: " http://localhost:4318/v1/traces ", + otlpMetricsUrl: " http://localhost:4318/v1/metrics ", + }, + }), + ).toEqual({ + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }); + }); + + it("parses lenient persisted settings JSON", () => { + expect( + parsePersistedServerObservabilitySettings( + JSON.stringify({ + observability: { + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }, + }), + ), + ).toEqual({ + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpMetricsUrl: "http://localhost:4318/v1/metrics", + }); + }); + + it("falls back cleanly when persisted settings are invalid", () => { + expect(parsePersistedServerObservabilitySettings("{")).toEqual({ + otlpTracesUrl: undefined, + otlpMetricsUrl: undefined, + }); + }); +}); diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts new file mode 100644 index 0000000000..e7b25606dc --- /dev/null +++ b/packages/shared/src/serverSettings.ts @@ -0,0 +1,40 @@ +import { ServerSettings } from "@t3tools/contracts"; +import { Schema } from "effect"; +import { fromLenientJson } from "./schemaJson"; + +const ServerSettingsJson = fromLenientJson(ServerSettings); + +export interface PersistedServerObservabilitySettings { + readonly otlpTracesUrl: string | undefined; + readonly otlpMetricsUrl: string | undefined; +} + +export function normalizePersistedServerSettingString( + value: string | null | undefined, +): string | undefined { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : undefined; +} + +export function extractPersistedServerObservabilitySettings(input: { + readonly observability?: { + readonly otlpTracesUrl?: string; + readonly otlpMetricsUrl?: string; + }; +}): PersistedServerObservabilitySettings { + return { + otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl), + otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl), + }; +} + +export function parsePersistedServerObservabilitySettings( + raw: string, +): PersistedServerObservabilitySettings { + try { + const decoded = Schema.decodeUnknownSync(ServerSettingsJson)(raw); + return extractPersistedServerObservabilitySettings(decoded); + } catch { + return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined }; + } +} diff --git a/turbo.json b/turbo.json index 9359376f59..47d7091385 100644 --- a/turbo.json +++ b/turbo.json @@ -11,7 +11,17 @@ "T3CODE_NO_BROWSER", "T3CODE_HOME", "T3CODE_AUTH_TOKEN", - "T3CODE_DESKTOP_WS_URL" + "T3CODE_DESKTOP_WS_URL", + "T3CODE_TRACE_MIN_LEVEL", + "T3CODE_TRACE_TIMING_ENABLED", + "T3CODE_TRACE_FILE", + "T3CODE_TRACE_MAX_BYTES", + "T3CODE_TRACE_MAX_FILES", + "T3CODE_TRACE_BATCH_WINDOW_MS", + "T3CODE_OTLP_TRACES_URL", + "T3CODE_OTLP_METRICS_URL", + "T3CODE_OTLP_EXPORT_INTERVAL_MS", + "T3CODE_OTLP_SERVICE_NAME" ], "tasks": { "build": {