From 988862989dfe85e23d8fad8016dba0dc931d4ce3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 2 Apr 2026 17:24:21 -0700 Subject: [PATCH] Surface observability config in the settings UI - expose logs folder and OTLP tracing state in server config - add a Diagnostics section with an open-logs-folder action - update tests and observability docs for the new config shape --- apps/server/src/server.test.ts | 10 + apps/server/src/ws.ts | 8 + apps/web/src/components/ChatView.browser.tsx | 6 + .../components/KeybindingsToast.browser.tsx | 6 + .../settings/SettingsPanels.browser.tsx | 91 +++ .../components/settings/SettingsPanels.tsx | 109 +++- apps/web/src/rpc/serverState.test.ts | 6 + apps/web/src/rpc/serverState.ts | 5 + apps/web/src/wsNativeApi.test.ts | 6 + docs/observability.md | 609 ++++++++++-------- packages/contracts/src/server.ts | 11 + 11 files changed, 566 insertions(+), 301 deletions(-) create mode 100644 apps/web/src/components/settings/SettingsPanels.browser.tsx diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 2c7a8eabac..0e8b909c99 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -542,6 +542,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({ @@ -570,6 +574,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, { diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 3fab1850ca..5210d3748b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -72,6 +72,14 @@ 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, }; }); diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index b0263cbf40..f9f1362d0e 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -135,6 +135,12 @@ function createBaseServerConfig(): ServerConfig { }, ], availableEditors: [], + observability: { + logsDirectoryPath: "/repo/project/.t3/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, settings: { ...DEFAULT_SERVER_SETTINGS, ...DEFAULT_CLIENT_SETTINGS, diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index b8398e7b8f..de7d84b4ec 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -56,6 +56,12 @@ function createBaseServerConfig(): ServerConfig { }, ], availableEditors: [], + observability: { + logsDirectoryPath: "/repo/project/.t3/logs", + localTracingEnabled: true, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + }, settings: { enableAssistantStreaming: false, defaultThreadEnvMode: "local" as const, diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx new file mode 100644 index 0000000000..090f6f12ad --- /dev/null +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -0,0 +1,91 @@ +import "../../index.css"; + +import { DEFAULT_SERVER_SETTINGS, type NativeApi, type ServerConfig } from "@t3tools/contracts"; +import { page } from "vitest/browser"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { render } from "vitest-browser-react"; + +import { __resetNativeApiForTests } from "../../nativeApi"; +import { AppAtomRegistryProvider } from "../../rpc/atomRegistry"; +import { resetServerStateForTests, setServerConfigSnapshot } from "../../rpc/serverState"; +import { GeneralSettingsPanel } from "./SettingsPanels"; + +function createBaseServerConfig(): ServerConfig { + return { + cwd: "/repo/project", + keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", + keybindings: [], + issues: [], + providers: [], + availableEditors: ["cursor"], + observability: { + logsDirectoryPath: "/repo/project/.t3/logs", + localTracingEnabled: true, + otlpTracesUrl: "http://localhost:4318/v1/traces", + otlpTracesEnabled: true, + otlpMetricsEnabled: false, + }, + settings: DEFAULT_SERVER_SETTINGS, + }; +} + +describe("GeneralSettingsPanel observability", () => { + 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 e3e620030b..d534eefaa4 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/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/wsNativeApi.test.ts b/apps/web/src/wsNativeApi.test.ts index c9bcc7ffd2..47f78f967f 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, }; diff --git a/docs/observability.md b/docs/observability.md index edf8d44bd9..dde1093570 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -1,20 +1,84 @@ # Observability -This server now has one observability model: +T3 Code has one server-side observability model: -- pretty logs to stdout for humans -- completed spans written to a local NDJSON trace file -- optional OTLP export for traces and metrics +- 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 source of truth for persisted diagnostics. +The local trace file is the persisted source of truth. There is no separate persisted server log file anymore. -## Quick Start +## Where To Find Things -If you just want a local Grafana stack and working telemetry in a few minutes, use `grafana/otel-lgtm`. +### Logs -### 1. Start a local LGTM stack +Logs are human-facing only: -Grafana publishes a single-container dev/test image for local OpenTelemetry work: +- 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 \ @@ -25,224 +89,95 @@ docker run --name lgtm \ grafana/otel-lgtm ``` -Wait for the container to report that the collector and stack are ready, then open `http://localhost:3000`. +Then open `http://localhost:3000`. -Grafana login: +Default Grafana login: - username: `admin` - password: `admin` -### 2. Point T3 Code at the local collector - -Our server exporters use OTLP HTTP, so set full OTLP HTTP endpoints: +#### 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 -``` - -Optional but useful: - -```bash export T3CODE_OTLP_SERVICE_NAME=t3-local +``` + +Optional: + +```bash export T3CODE_TRACE_MIN_LEVEL=Info +export T3CODE_TRACE_TIMING_ENABLED=true ``` -### 3. Run the app you care about +#### 3. Launch the app from that same shell -#### Published CLI +CLI: ```bash npx t3 ``` -#### Monorepo web/server dev +Monorepo web/server dev: ```bash bun dev ``` -#### Monorepo desktop dev +Monorepo desktop dev: ```bash bun dev:desktop ``` -#### Packaged desktop app +Packaged desktop app: -Launch it from a terminal in the same environment so the desktop process inherits `T3CODE_OTLP_*`. +Launch the actual app executable from the same shell so the desktop app and embedded backend inherit `T3CODE_OTLP_*`. -Important: - -- the desktop app forwards these env vars to the embedded backend process -- launching from Finder / Spotlight / Start Menu / dock icons usually will not inject new shell env vars - -### 4. Where to look in Grafana - -For this app today: - -- traces: use the `Tempo` data source -- metrics: use the `Prometheus` data source -- logs: do not expect much in `Loki` yet, because T3 Code does not export OTLP logs as a separate signal - -The useful first stop is usually `Explore`: - -1. Open `Explore` -2. Pick `Tempo` to inspect traces -3. Search for spans by service name, span name, or span attributes -4. Switch to `Prometheus` to inspect counters and latency metrics - -### 5. Keep the local trace file enabled too - -Even when exporting to LGTM, the server still writes the local NDJSON trace file. That is useful for: - -- quick local `jq` inspection -- debugging before Grafana is open -- checking raw span/event payloads - -So the normal local-dev setup is: - -- pretty stdout for live debugging -- local trace file for raw inspection -- LGTM for search, aggregation, and dashboards - -## What Gets Recorded - -### Traces - -Every completed span is written as one NDJSON record to `serverTracePath`. - -Default path: - -```txt -//logs/server.trace.ndjson -``` - -In normal runs that resolves from `T3CODE_HOME`. In dev mode it uses `dev/logs`; otherwise it uses `userdata/logs`. - -The trace record shape lives in `apps/server/src/observability/TraceRecord.ts`. - -Useful fields: - -- `name`: span name -- `traceId`, `spanId`, `parentSpanId`: correlation -- `durationMs`: elapsed time -- `attributes`: structured context -- `events`: embedded log events and custom events -- `exit`: `Success`, `Failure`, or `Interrupted` - -### Logs - -Application logs are not persisted as a separate file anymore. - -- `Logger.consolePretty()` writes human-readable logs to stdout -- `Logger.tracerLogger` turns `Effect.log...` calls inside an active span into span events -- logs emitted outside a span are stdout-only - -That means if you want a log message to survive into the trace file, it needs to happen inside a traced effect. - -### Metrics - -Metrics are first-class in code, but they are not written to a local file. - -- local persistence: none -- remote export: OTLP only, when configured - -Metric definitions live in `apps/server/src/observability/Metrics.ts`. - -## 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 - -## Config - -### Local Trace File - -- `T3CODE_TRACE_FILE`: override the 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 simply stay in-process. - -## Common Run Modes - -### CLI or `npx t3` - -This is the easiest way to test observability outside the monorepo: - -```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-cli - -npx t3 -``` - -### Monorepo `bun dev` - -`bun dev` forwards your shell environment to the server process, so the same OTLP vars work: - -```bash -T3CODE_OTLP_TRACES_URL=http://localhost:4318/v1/traces \ -T3CODE_OTLP_METRICS_URL=http://localhost:4318/v1/metrics \ -T3CODE_OTLP_SERVICE_NAME=t3-dev \ -bun dev -``` - -### Monorepo `bun dev:desktop` - -Desktop dev mode also inherits the shell environment, and the Electron main process forwards OTLP env vars to the child backend: - -```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-dev \ -bun dev:desktop -``` - -### Packaged desktop app - -For packaged builds, start the app from a terminal if you want one-off local OTLP config: +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" ``` -If you launch the app from the OS UI instead, the env vars usually will not be present. +Direct binary example: -## How To Read The Trace File +```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 +``` -The trace file is NDJSON, so `jq` is the easiest way to explore it. +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. -### Tail everything +#### 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" ``` -### Show failures only +In monorepo dev, use: + +```bash +tail -f ./dev/logs/server.trace.ndjson +``` + +Show failed spans: ```bash jq -c 'select(.exit._tag != "Success") | { @@ -253,7 +188,7 @@ jq -c 'select(.exit._tag != "Success") | { }' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" ``` -### Find slow spans +Show slow spans: ```bash jq -c 'select(.durationMs > 1000) | { @@ -264,7 +199,7 @@ jq -c 'select(.durationMs > 1000) | { }' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" ``` -### Inspect embedded log events +Inspect embedded log events: ```bash jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | { @@ -281,7 +216,7 @@ jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | { }' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" ``` -### Follow one trace +Follow one trace: ```bash jq -r 'select(.traceId == "TRACE_ID_HERE") | [ @@ -292,19 +227,7 @@ jq -r 'select(.traceId == "TRACE_ID_HERE") | [ ] | @tsv' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" ``` -### Filter provider work - -```bash -jq -c 'select(.attributes["provider.thread_id"] == "thread_123") | { - name, - durationMs, - provider: .attributes["provider.kind"], - model: .attributes["provider.model"], - exit: .exit._tag -}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" -``` - -### Filter orchestration commands +Filter orchestration commands: ```bash jq -c 'select(.attributes["orchestration.command_type"] != null) | { @@ -315,7 +238,7 @@ jq -c 'select(.attributes["orchestration.command_type"] != null) | { }' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" ``` -### Filter git activity +Filter git activity: ```bash jq -c 'select(.attributes["git.operation"] != null) | { @@ -330,26 +253,138 @@ jq -c 'select(.attributes["git.operation"] != null) | { }' "$T3CODE_HOME/userdata/logs/server.trace.ndjson" ``` -## What Is Instrumented Today +### Use Tempo When You Need A Real Trace Viewer -Current high-value span and metric boundaries include: +Tempo is better than raw NDJSON when you want to: -- Effect RPC websocket request spans from `effect/rpc` -- RPC request metrics in `apps/server/src/observability/RpcInstrumentation.ts` -- startup phases -- orchestration command processing -- provider session and turn operations -- git command execution and git hook events -- terminal session lifecycle -- sqlite query execution +- search across many traces +- inspect parent/child relationships visually +- compare many slow traces +- drill into one failing request without hand-joining by `traceId` -Provider event NDJSON logging still exists separately for provider-runtime event streams. That is not the same artifact as the server trace file. +Recommended flow in Grafana: -## How To Instrument New Code +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. -### 1. Create or reuse a span +Good first searches: -Prefer existing `Effect.fn("name")` boundaries where possible. For ad hoc work, wrap it: +- 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"; @@ -365,13 +400,56 @@ const runThing = Effect.gen(function* () { }).pipe(Effect.withSpan("thing.run")); ``` -### 2. Add metrics with the pipeable API +### Put High-Cardinality Detail On Spans -Use `withMetrics(...)` from `apps/server/src/observability/Metrics.ts`. +Use span annotations for IDs, paths, and other detailed context: ```ts -import { Effect } from "effect"; +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( @@ -385,84 +463,57 @@ const program = doWork().pipe( ); ``` -Use low-cardinality metric attributes only. +## Detailed API Reference -Good metric labels: +### Runtime Wiring -- operation kind -- method name -- provider kind -- outcome +The server observability layer is assembled in `apps/server/src/observability/Layers/Observability.ts`. -Bad metric labels: +It provides: -- raw thread IDs -- command IDs -- file paths -- cwd -- full prompts -- high-cardinality model strings when a normalized family label would do +- pretty stdout logger +- `Logger.tracerLogger` +- local NDJSON tracer +- optional OTLP trace exporter +- optional OTLP metrics exporter +- Effect trace-level and timing refs -Put that detailed context on spans instead. +### Env Vars -### 3. Use span annotations for high-cardinality detail +Local trace file: -```ts -yield * - Effect.annotateCurrentSpan({ - "provider.thread_id": input.threadId, - "provider.request_id": input.requestId, - "git.cwd": input.cwd, - }); -``` +- `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` -### 4. Use logs as span events +OTLP export: -If you want a trace to tell the story of what happened, log inside the span: +- `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` -```ts -yield * Effect.logInfo("starting provider turn"); -yield * Effect.logDebug("waiting for approval response"); -``` +If the OTLP URLs are unset, local tracing still works and metrics stay in-process only. -Those messages will show up as span events in the trace file because `Logger.tracerLogger` is installed. +### What Is Instrumented Today -## Practical Workflows +Current high-value span and metric boundaries include: -### “Why did this request fail?” +- 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 -1. Find failed spans with `exit._tag != "Success"`. -2. Group by `traceId`. -3. Inspect sibling spans and embedded log events. -4. Look at attributes like `provider.thread_id`, `orchestration.command_type`, or `git.operation`. - -### “Why is the UI feeling slow?” - -1. Sort spans by `durationMs`. -2. Look at top-level RPC request spans. -3. Check child spans for provider, git, terminal, or sqlite work. -4. Compare slow traces against metrics in your OTLP backend once metrics export is enabled. - -### “Are git hooks causing latency?” - -1. Filter spans with `git.operation`. -2. Inspect `git.hook.started` and `git.hook.finished` events. -3. Compare hook event timing to the enclosing git span duration. - -### “Where should I add more instrumentation?” - -Add spans or annotations at boundaries: - -- queue handoff -- provider adapter calls -- external process calls -- persistence writes -- RPC methods that fan out into multiple subsystems - -Avoid tracing every tiny helper. The useful unit is usually a boundary or a phase. - -## Current Constraints +### 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 observability artifact that matters +- 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/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;